Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

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