Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

HasTransactionAction.php 14KB

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