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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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 Closure;
  13. use Filament\Forms;
  14. use Filament\Forms\Components\Actions\Action as FormAction;
  15. use Filament\Forms\Form;
  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' => company_today()->toDateString(),
  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(6)
  189. ->schema([
  190. Forms\Components\DatePicker::make('posted_at')
  191. ->label('Date')
  192. ->softRequired(),
  193. Forms\Components\TextInput::make('description')
  194. ->label('Description')
  195. ->columnSpan(2),
  196. ]);
  197. }
  198. protected function getJournalEntriesTableRepeater(): CustomTableRepeater
  199. {
  200. return CustomTableRepeater::make('journalEntries')
  201. ->relationship('journalEntries')
  202. ->hiddenLabel()
  203. ->columns(4)
  204. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  205. ->schema($this->getJournalEntriesTableRepeaterSchema())
  206. ->deletable(fn (CustomTableRepeater $repeater) => $repeater->getItemsCount() > 2)
  207. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  208. return $action
  209. ->action(function (array $arguments, CustomTableRepeater $component): void {
  210. $items = $component->getState();
  211. $amount = $items[$arguments['item']]['amount'];
  212. $type = $items[$arguments['item']]['type'];
  213. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  214. unset($items[$arguments['item']]);
  215. $component->state($items);
  216. $component->callAfterStateUpdated();
  217. });
  218. })
  219. ->rules([
  220. function () {
  221. return function (string $attribute, $value, \Closure $fail) {
  222. if (empty($value) || ! is_array($value)) {
  223. $fail('Journal entries are required.');
  224. return;
  225. }
  226. $hasDebit = false;
  227. $hasCredit = false;
  228. $totalDebits = 0;
  229. $totalCredits = 0;
  230. foreach ($value as $entry) {
  231. if (! isset($entry['type']) || ! isset($entry['amount'])) {
  232. continue;
  233. }
  234. $entryType = JournalEntryType::parse($entry['type']);
  235. $amount = CurrencyConverter::convertToCents($entry['amount'], 'USD');
  236. if ($entryType->isDebit()) {
  237. $hasDebit = true;
  238. $totalDebits += $amount;
  239. } elseif ($entryType->isCredit()) {
  240. $hasCredit = true;
  241. $totalCredits += $amount;
  242. }
  243. }
  244. if (! $hasDebit) {
  245. $fail('At least one debit entry is required.');
  246. }
  247. if (! $hasCredit) {
  248. $fail('At least one credit entry is required.');
  249. }
  250. if ($totalDebits !== $totalCredits) {
  251. $debitFormatted = CurrencyConverter::formatCentsToMoney($totalDebits, CurrencyAccessor::getDefaultCurrency());
  252. $creditFormatted = CurrencyConverter::formatCentsToMoney($totalCredits, CurrencyAccessor::getDefaultCurrency());
  253. $fail("Total debits ({$debitFormatted}) must equal total credits ({$creditFormatted}).");
  254. }
  255. };
  256. },
  257. ])
  258. ->minItems(2)
  259. ->defaultItems(2)
  260. ->addable(false)
  261. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  262. ->extraActions([
  263. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  264. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  265. ]);
  266. }
  267. protected function getJournalEntriesTableRepeaterHeaders(): array
  268. {
  269. return [
  270. Header::make('type')
  271. ->width('150px')
  272. ->label('Type'),
  273. Header::make('description')
  274. ->width('320px')
  275. ->label('Description'),
  276. Header::make('account_id')
  277. ->width('320px')
  278. ->label('Account'),
  279. Header::make('amount')
  280. ->width('192px')
  281. ->label('Amount'),
  282. ];
  283. }
  284. protected function getJournalEntriesTableRepeaterSchema(): array
  285. {
  286. return [
  287. Forms\Components\Select::make('type')
  288. ->label('Type')
  289. ->options(JournalEntryType::class)
  290. ->live()
  291. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, $state, $old) {
  292. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  293. })
  294. ->softRequired(),
  295. Forms\Components\TextInput::make('description')
  296. ->label('Description'),
  297. Forms\Components\Select::make('account_id')
  298. ->label('Account')
  299. ->options(fn (?JournalEntry $journalEntry): array => Transaction::getJournalAccountOptions(currentAccountId: $journalEntry?->account_id))
  300. ->softRequired()
  301. ->searchable(),
  302. Forms\Components\TextInput::make('amount')
  303. ->label('Amount')
  304. ->live(onBlur: true)
  305. ->money()
  306. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, ?string $state, ?string $old) {
  307. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  308. })
  309. ->softRequired(),
  310. ];
  311. }
  312. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  313. {
  314. $typeLabel = $type->getLabel();
  315. return FormAction::make("add{$typeLabel}Entry")
  316. ->button()
  317. ->outlined()
  318. ->color($type->isDebit() ? 'primary' : 'gray')
  319. ->action(function (CustomTableRepeater $component) use ($type) {
  320. $state = $component->getState();
  321. $newUuid = (string) Str::uuid();
  322. $state[$newUuid] = $this->defaultEntry($type);
  323. $component->state($state);
  324. });
  325. }
  326. public function getJournalTransactionModalFooter(): View
  327. {
  328. return view(
  329. 'filament.company.components.actions.journal-entry-footer',
  330. [
  331. 'debitAmount' => $this->getFormattedDebitAmount(),
  332. 'creditAmount' => $this->getFormattedCreditAmount(),
  333. 'difference' => $this->getFormattedBalanceDifference(),
  334. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  335. ],
  336. );
  337. }
  338. }