選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

HasTransactionAction.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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' => 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. $totalDebits = 0;
  230. $totalCredits = 0;
  231. foreach ($value as $entry) {
  232. if (! isset($entry['type']) || ! isset($entry['amount'])) {
  233. continue;
  234. }
  235. $entryType = JournalEntryType::parse($entry['type']);
  236. $amount = CurrencyConverter::convertToCents($entry['amount'], 'USD');
  237. if ($entryType->isDebit()) {
  238. $hasDebit = true;
  239. $totalDebits += $amount;
  240. } elseif ($entryType->isCredit()) {
  241. $hasCredit = true;
  242. $totalCredits += $amount;
  243. }
  244. }
  245. if (! $hasDebit) {
  246. $fail('At least one debit entry is required.');
  247. }
  248. if (! $hasCredit) {
  249. $fail('At least one credit entry is required.');
  250. }
  251. if ($totalDebits !== $totalCredits) {
  252. $debitFormatted = CurrencyConverter::formatCentsToMoney($totalDebits, CurrencyAccessor::getDefaultCurrency());
  253. $creditFormatted = CurrencyConverter::formatCentsToMoney($totalCredits, CurrencyAccessor::getDefaultCurrency());
  254. $fail("Total debits ({$debitFormatted}) must equal total credits ({$creditFormatted}).");
  255. }
  256. };
  257. },
  258. ])
  259. ->minItems(2)
  260. ->defaultItems(2)
  261. ->addable(false)
  262. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  263. ->extraActions([
  264. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  265. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  266. ]);
  267. }
  268. protected function getJournalEntriesTableRepeaterHeaders(): array
  269. {
  270. return [
  271. Header::make('type')
  272. ->width('150px')
  273. ->label('Type'),
  274. Header::make('description')
  275. ->width('320px')
  276. ->label('Description'),
  277. Header::make('account_id')
  278. ->width('320px')
  279. ->label('Account'),
  280. Header::make('amount')
  281. ->width('192px')
  282. ->label('Amount'),
  283. ];
  284. }
  285. protected function getJournalEntriesTableRepeaterSchema(): array
  286. {
  287. return [
  288. Forms\Components\Select::make('type')
  289. ->label('Type')
  290. ->options(JournalEntryType::class)
  291. ->live()
  292. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, $state, $old) {
  293. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  294. })
  295. ->softRequired(),
  296. Forms\Components\TextInput::make('description')
  297. ->label('Description'),
  298. Forms\Components\Select::make('account_id')
  299. ->label('Account')
  300. ->options(fn (?JournalEntry $journalEntry): array => Transaction::getJournalAccountOptions(currentAccountId: $journalEntry?->account_id))
  301. ->softRequired()
  302. ->searchable(),
  303. Forms\Components\TextInput::make('amount')
  304. ->label('Amount')
  305. ->live(onBlur: true)
  306. ->money()
  307. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, ?string $state, ?string $old) {
  308. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  309. })
  310. ->softRequired(),
  311. ];
  312. }
  313. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  314. {
  315. $typeLabel = $type->getLabel();
  316. return FormAction::make("add{$typeLabel}Entry")
  317. ->button()
  318. ->outlined()
  319. ->color($type->isDebit() ? 'primary' : 'gray')
  320. ->action(function (CustomTableRepeater $component) use ($type) {
  321. $state = $component->getState();
  322. $newUuid = (string) Str::uuid();
  323. $state[$newUuid] = $this->defaultEntry($type);
  324. $component->state($state);
  325. });
  326. }
  327. public function getJournalTransactionModalFooter(): View
  328. {
  329. return view(
  330. 'filament.company.components.actions.journal-entry-footer',
  331. [
  332. 'debitAmount' => $this->getFormattedDebitAmount(),
  333. 'creditAmount' => $this->getFormattedCreditAmount(),
  334. 'difference' => $this->getFormattedBalanceDifference(),
  335. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  336. ],
  337. );
  338. }
  339. }