您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

HasTransactionAction.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace App\Concerns;
  3. use App\Enums\Accounting\JournalEntryType;
  4. use App\Enums\Accounting\TransactionType;
  5. use App\Filament\Forms\Components\CustomTableRepeater;
  6. use App\Models\Accounting\JournalEntry;
  7. use App\Models\Accounting\Transaction;
  8. use App\Models\Banking\BankAccount;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use Awcodes\TableRepeater\Header;
  11. use Closure;
  12. use Filament\Forms;
  13. use Filament\Forms\Components\Actions\Action as FormAction;
  14. use Filament\Forms\Form;
  15. use Filament\Support\RawJs;
  16. use Illuminate\Contracts\View\View;
  17. use Illuminate\Support\Str;
  18. trait HasTransactionAction
  19. {
  20. use HasJournalEntryActions;
  21. protected TransactionType | Closure | null $transactionType = null;
  22. public function type(TransactionType | Closure | null $type = null): static
  23. {
  24. $this->transactionType = $type;
  25. return $this;
  26. }
  27. public function getTransactionType(): ?TransactionType
  28. {
  29. return $this->evaluate($this->transactionType);
  30. }
  31. protected function getFormDefaultsForType(TransactionType $type): array
  32. {
  33. $commonDefaults = [
  34. 'posted_at' => today(),
  35. ];
  36. return match ($type) {
  37. TransactionType::Deposit, TransactionType::Withdrawal, TransactionType::Transfer => array_merge($commonDefaults, $this->transactionDefaults($type)),
  38. TransactionType::Journal => array_merge($commonDefaults, $this->journalEntryDefaults()),
  39. };
  40. }
  41. protected function journalEntryDefaults(): array
  42. {
  43. return [
  44. 'journalEntries' => [
  45. $this->defaultEntry(JournalEntryType::Debit),
  46. $this->defaultEntry(JournalEntryType::Credit),
  47. ],
  48. ];
  49. }
  50. protected function defaultEntry(JournalEntryType $journalEntryType): array
  51. {
  52. return [
  53. 'type' => $journalEntryType,
  54. 'account_id' => Transaction::getUncategorizedAccountByType($journalEntryType->isDebit() ? TransactionType::Withdrawal : TransactionType::Deposit)?->id,
  55. 'amount' => '0.00',
  56. ];
  57. }
  58. protected function transactionDefaults(TransactionType $type): array
  59. {
  60. return [
  61. 'type' => $type,
  62. 'bank_account_id' => BankAccount::where('enabled', true)->first()?->id,
  63. 'amount' => '0.00',
  64. 'account_id' => ! $type->isTransfer() ? Transaction::getUncategorizedAccountByType($type)->id : null,
  65. ];
  66. }
  67. public function transactionForm(Form $form): Form
  68. {
  69. return $form
  70. ->schema([
  71. Forms\Components\DatePicker::make('posted_at')
  72. ->label('Date')
  73. ->required(),
  74. Forms\Components\TextInput::make('description')
  75. ->label('Description'),
  76. Forms\Components\Select::make('bank_account_id')
  77. ->label('Account')
  78. ->options(fn (?Transaction $transaction) => Transaction::getBankAccountOptions(currentBankAccountId: $transaction?->bank_account_id))
  79. ->live()
  80. ->searchable()
  81. ->required(),
  82. Forms\Components\Select::make('type')
  83. ->label('Type')
  84. ->live()
  85. ->options([
  86. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  87. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  88. ])
  89. ->required()
  90. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', Transaction::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  91. Forms\Components\TextInput::make('amount')
  92. ->label('Amount')
  93. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  94. ->required(),
  95. Forms\Components\Select::make('account_id')
  96. ->label('Category')
  97. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getTransactionAccountOptions(type: TransactionType::parse($get('type')), currentAccountId: $transaction?->account_id))
  98. ->searchable()
  99. ->required(),
  100. Forms\Components\Textarea::make('notes')
  101. ->label('Notes')
  102. ->autosize()
  103. ->rows(10)
  104. ->columnSpanFull(),
  105. ])
  106. ->columns();
  107. }
  108. public function transferForm(Form $form): Form
  109. {
  110. return $form
  111. ->schema([
  112. Forms\Components\DatePicker::make('posted_at')
  113. ->label('Date')
  114. ->required(),
  115. Forms\Components\TextInput::make('description')
  116. ->label('Description'),
  117. Forms\Components\Select::make('bank_account_id')
  118. ->label('From account')
  119. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountOptions(excludedAccountId: $get('account_id'), currentBankAccountId: $transaction?->bank_account_id))
  120. ->live()
  121. ->searchable()
  122. ->required(),
  123. Forms\Components\Select::make('type')
  124. ->label('Type')
  125. ->options([
  126. TransactionType::Transfer->value => TransactionType::Transfer->getLabel(),
  127. ])
  128. ->disabled()
  129. ->dehydrated()
  130. ->required(),
  131. Forms\Components\TextInput::make('amount')
  132. ->label('Amount')
  133. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  134. ->required(),
  135. Forms\Components\Select::make('account_id')
  136. ->label('To account')
  137. ->live()
  138. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountAccountOptions(excludedBankAccountId: $get('bank_account_id'), currentAccountId: $transaction?->account_id))
  139. ->searchable()
  140. ->required(),
  141. Forms\Components\Textarea::make('notes')
  142. ->label('Notes')
  143. ->autosize()
  144. ->rows(10)
  145. ->columnSpanFull(),
  146. ])
  147. ->columns();
  148. }
  149. public function journalTransactionForm(Form $form): Form
  150. {
  151. return $form
  152. ->schema([
  153. Forms\Components\Tabs::make('Tabs')
  154. ->contained(false)
  155. ->tabs([
  156. $this->getJournalTransactionFormEditTab(),
  157. $this->getJournalTransactionFormNotesTab(),
  158. ]),
  159. ])
  160. ->columns(1);
  161. }
  162. protected function getJournalTransactionFormEditTab(): Forms\Components\Tabs\Tab
  163. {
  164. return Forms\Components\Tabs\Tab::make('Edit')
  165. ->label('Edit')
  166. ->icon('heroicon-o-pencil-square')
  167. ->schema([
  168. $this->getTransactionDetailsGrid(),
  169. $this->getJournalEntriesTableRepeater(),
  170. ]);
  171. }
  172. protected function getJournalTransactionFormNotesTab(): Forms\Components\Tabs\Tab
  173. {
  174. return Forms\Components\Tabs\Tab::make('Notes')
  175. ->label('Notes')
  176. ->icon('heroicon-o-clipboard')
  177. ->id('notes')
  178. ->schema([
  179. $this->getTransactionDetailsGrid(),
  180. Forms\Components\Textarea::make('notes')
  181. ->label('Notes')
  182. ->rows(10)
  183. ->autosize(),
  184. ]);
  185. }
  186. protected function getTransactionDetailsGrid(): Forms\Components\Grid
  187. {
  188. return Forms\Components\Grid::make(8)
  189. ->schema([
  190. Forms\Components\DatePicker::make('posted_at')
  191. ->label('Date')
  192. ->softRequired()
  193. ->displayFormat('Y-m-d'),
  194. Forms\Components\TextInput::make('description')
  195. ->label('Description')
  196. ->columnSpan(2),
  197. ]);
  198. }
  199. protected function getJournalEntriesTableRepeater(): CustomTableRepeater
  200. {
  201. return CustomTableRepeater::make('journalEntries')
  202. ->relationship('journalEntries')
  203. ->hiddenLabel()
  204. ->columns(4)
  205. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  206. ->schema($this->getJournalEntriesTableRepeaterSchema())
  207. ->deletable(fn (CustomTableRepeater $repeater) => $repeater->getItemsCount() > 2)
  208. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  209. return $action
  210. ->action(function (array $arguments, CustomTableRepeater $component): void {
  211. $items = $component->getState();
  212. $amount = $items[$arguments['item']]['amount'];
  213. $type = $items[$arguments['item']]['type'];
  214. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  215. unset($items[$arguments['item']]);
  216. $component->state($items);
  217. $component->callAfterStateUpdated();
  218. });
  219. })
  220. ->rules([
  221. function () {
  222. return function (string $attribute, $value, \Closure $fail) {
  223. if (empty($value) || ! is_array($value)) {
  224. $fail('Journal entries are required.');
  225. return;
  226. }
  227. $hasDebit = false;
  228. $hasCredit = false;
  229. foreach ($value as $entry) {
  230. if (! isset($entry['type'])) {
  231. continue;
  232. }
  233. if (JournalEntryType::parse($entry['type'])->isDebit()) {
  234. $hasDebit = true;
  235. } elseif (JournalEntryType::parse($entry['type'])->isCredit()) {
  236. $hasCredit = true;
  237. }
  238. if ($hasDebit && $hasCredit) {
  239. break;
  240. }
  241. }
  242. if (! $hasDebit) {
  243. $fail('At least one debit entry is required.');
  244. }
  245. if (! $hasCredit) {
  246. $fail('At least one credit entry is required.');
  247. }
  248. };
  249. },
  250. ])
  251. ->minItems(2)
  252. ->defaultItems(2)
  253. ->addable(false)
  254. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  255. ->extraActions([
  256. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  257. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  258. ]);
  259. }
  260. protected function getJournalEntriesTableRepeaterHeaders(): array
  261. {
  262. return [
  263. Header::make('type')
  264. ->width('150px')
  265. ->label('Type'),
  266. Header::make('description')
  267. ->width('320px')
  268. ->label('Description'),
  269. Header::make('account_id')
  270. ->width('320px')
  271. ->label('Account'),
  272. Header::make('amount')
  273. ->width('192px')
  274. ->label('Amount'),
  275. ];
  276. }
  277. protected function getJournalEntriesTableRepeaterSchema(): array
  278. {
  279. return [
  280. Forms\Components\Select::make('type')
  281. ->label('Type')
  282. ->options(JournalEntryType::class)
  283. ->live()
  284. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, $state, $old) {
  285. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  286. })
  287. ->softRequired(),
  288. Forms\Components\TextInput::make('description')
  289. ->label('Description'),
  290. Forms\Components\Select::make('account_id')
  291. ->label('Account')
  292. ->options(fn (?JournalEntry $journalEntry): array => Transaction::getJournalAccountOptions(currentAccountId: $journalEntry?->account_id))
  293. ->softRequired()
  294. ->searchable(),
  295. Forms\Components\TextInput::make('amount')
  296. ->label('Amount')
  297. ->live()
  298. ->mask(RawJs::make('$money($input)'))
  299. ->dehydrateStateUsing(function (?string $state): ?int {
  300. if (blank($state)) {
  301. return null;
  302. }
  303. // Remove thousand separators
  304. $cleaned = str_replace(',', '', $state);
  305. // If no decimal point, assume it's whole dollars (add .00)
  306. if (! str_contains($cleaned, '.')) {
  307. $cleaned .= '.00';
  308. }
  309. // Convert to float then to cents (integer)
  310. return (int) round((float) $cleaned * 100);
  311. })
  312. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, ?string $state, ?string $old) {
  313. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  314. })
  315. ->softRequired(),
  316. ];
  317. }
  318. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  319. {
  320. $typeLabel = $type->getLabel();
  321. return FormAction::make("add{$typeLabel}Entry")
  322. ->button()
  323. ->outlined()
  324. ->color($type->isDebit() ? 'primary' : 'gray')
  325. ->action(function (CustomTableRepeater $component) use ($type) {
  326. $state = $component->getState();
  327. $newUuid = (string) Str::uuid();
  328. $state[$newUuid] = $this->defaultEntry($type);
  329. $component->state($state);
  330. });
  331. }
  332. public function getJournalTransactionModalFooter(): View
  333. {
  334. return view(
  335. 'filament.company.components.actions.journal-entry-footer',
  336. [
  337. 'debitAmount' => $this->getFormattedDebitAmount(),
  338. 'creditAmount' => $this->getFormattedCreditAmount(),
  339. 'difference' => $this->getFormattedBalanceDifference(),
  340. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  341. ],
  342. );
  343. }
  344. }