You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

HasTransactionAction.php 15KB

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