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

HasTransactionAction.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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. ->afterStateUpdated(function (Forms\Set $set, $state, $old, Forms\Get $get) {
  82. $amount = CurrencyConverter::convertAndSet(
  83. BankAccount::find($state)->account->currency_code,
  84. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  85. $get('amount')
  86. );
  87. if ($amount !== null) {
  88. $set('amount', $amount);
  89. }
  90. })
  91. ->required(),
  92. Forms\Components\Select::make('type')
  93. ->label('Type')
  94. ->live()
  95. ->options([
  96. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  97. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  98. ])
  99. ->required()
  100. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', Transaction::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  101. Forms\Components\TextInput::make('amount')
  102. ->label('Amount')
  103. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  104. ->required(),
  105. Forms\Components\Select::make('account_id')
  106. ->label('Category')
  107. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getTransactionAccountOptions(type: TransactionType::parse($get('type')), currentAccountId: $transaction?->account_id))
  108. ->searchable()
  109. ->required(),
  110. Forms\Components\Textarea::make('notes')
  111. ->label('Notes')
  112. ->autosize()
  113. ->rows(10)
  114. ->columnSpanFull(),
  115. ])
  116. ->columns();
  117. }
  118. public function transferForm(Form $form): Form
  119. {
  120. return $form
  121. ->schema([
  122. Forms\Components\DatePicker::make('posted_at')
  123. ->label('Date')
  124. ->required(),
  125. Forms\Components\TextInput::make('description')
  126. ->label('Description'),
  127. Forms\Components\Select::make('bank_account_id')
  128. ->label('From account')
  129. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountOptions(excludedAccountId: $get('account_id'), currentBankAccountId: $transaction?->bank_account_id))
  130. ->live()
  131. ->searchable()
  132. ->afterStateUpdated(function (Forms\Set $set, $state, $old, Forms\Get $get) {
  133. $amount = CurrencyConverter::convertAndSet(
  134. BankAccount::find($state)->account->currency_code,
  135. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  136. $get('amount')
  137. );
  138. if ($amount !== null) {
  139. $set('amount', $amount);
  140. }
  141. })
  142. ->required(),
  143. Forms\Components\Select::make('type')
  144. ->label('Type')
  145. ->options([
  146. TransactionType::Transfer->value => TransactionType::Transfer->getLabel(),
  147. ])
  148. ->disabled()
  149. ->dehydrated()
  150. ->required(),
  151. Forms\Components\TextInput::make('amount')
  152. ->label('Amount')
  153. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  154. ->required(),
  155. Forms\Components\Select::make('account_id')
  156. ->label('To account')
  157. ->live()
  158. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountAccountOptions(excludedBankAccountId: $get('bank_account_id'), currentAccountId: $transaction?->account_id))
  159. ->searchable()
  160. ->required(),
  161. Forms\Components\Textarea::make('notes')
  162. ->label('Notes')
  163. ->autosize()
  164. ->rows(10)
  165. ->columnSpanFull(),
  166. ])
  167. ->columns();
  168. }
  169. public function journalTransactionForm(Form $form): Form
  170. {
  171. return $form
  172. ->schema([
  173. Forms\Components\Tabs::make('Tabs')
  174. ->contained(false)
  175. ->tabs([
  176. $this->getJournalTransactionFormEditTab(),
  177. $this->getJournalTransactionFormNotesTab(),
  178. ]),
  179. ])
  180. ->columns(1);
  181. }
  182. protected function getJournalTransactionFormEditTab(): Forms\Components\Tabs\Tab
  183. {
  184. return Forms\Components\Tabs\Tab::make('Edit')
  185. ->label('Edit')
  186. ->icon('heroicon-o-pencil-square')
  187. ->schema([
  188. $this->getTransactionDetailsGrid(),
  189. $this->getJournalEntriesTableRepeater(),
  190. ]);
  191. }
  192. protected function getJournalTransactionFormNotesTab(): Forms\Components\Tabs\Tab
  193. {
  194. return Forms\Components\Tabs\Tab::make('Notes')
  195. ->label('Notes')
  196. ->icon('heroicon-o-clipboard')
  197. ->id('notes')
  198. ->schema([
  199. $this->getTransactionDetailsGrid(),
  200. Forms\Components\Textarea::make('notes')
  201. ->label('Notes')
  202. ->rows(10)
  203. ->autosize(),
  204. ]);
  205. }
  206. protected function getTransactionDetailsGrid(): Forms\Components\Grid
  207. {
  208. return Forms\Components\Grid::make(8)
  209. ->schema([
  210. Forms\Components\DatePicker::make('posted_at')
  211. ->label('Date')
  212. ->softRequired()
  213. ->displayFormat('Y-m-d'),
  214. Forms\Components\TextInput::make('description')
  215. ->label('Description')
  216. ->columnSpan(2),
  217. ]);
  218. }
  219. protected function getJournalEntriesTableRepeater(): CustomTableRepeater
  220. {
  221. return CustomTableRepeater::make('journalEntries')
  222. ->relationship('journalEntries')
  223. ->hiddenLabel()
  224. ->columns(4)
  225. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  226. ->schema($this->getJournalEntriesTableRepeaterSchema())
  227. ->deletable(fn (CustomTableRepeater $repeater) => $repeater->getItemsCount() > 2)
  228. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  229. return $action
  230. ->action(function (array $arguments, CustomTableRepeater $component): void {
  231. $items = $component->getState();
  232. $amount = $items[$arguments['item']]['amount'];
  233. $type = $items[$arguments['item']]['type'];
  234. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  235. unset($items[$arguments['item']]);
  236. $component->state($items);
  237. $component->callAfterStateUpdated();
  238. });
  239. })
  240. ->rules([
  241. function () {
  242. return function (string $attribute, $value, \Closure $fail) {
  243. if (empty($value) || ! is_array($value)) {
  244. $fail('Journal entries are required.');
  245. return;
  246. }
  247. $hasDebit = false;
  248. $hasCredit = false;
  249. foreach ($value as $entry) {
  250. if (! isset($entry['type'])) {
  251. continue;
  252. }
  253. if (JournalEntryType::parse($entry['type'])->isDebit()) {
  254. $hasDebit = true;
  255. } elseif (JournalEntryType::parse($entry['type'])->isCredit()) {
  256. $hasCredit = true;
  257. }
  258. if ($hasDebit && $hasCredit) {
  259. break;
  260. }
  261. }
  262. if (! $hasDebit) {
  263. $fail('At least one debit entry is required.');
  264. }
  265. if (! $hasCredit) {
  266. $fail('At least one credit entry is required.');
  267. }
  268. };
  269. },
  270. ])
  271. ->minItems(2)
  272. ->defaultItems(2)
  273. ->addable(false)
  274. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  275. ->extraActions([
  276. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  277. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  278. ]);
  279. }
  280. protected function getJournalEntriesTableRepeaterHeaders(): array
  281. {
  282. return [
  283. Header::make('type')
  284. ->width('150px')
  285. ->label('Type'),
  286. Header::make('description')
  287. ->width('320px')
  288. ->label('Description'),
  289. Header::make('account_id')
  290. ->width('320px')
  291. ->label('Account'),
  292. Header::make('amount')
  293. ->width('192px')
  294. ->label('Amount'),
  295. ];
  296. }
  297. protected function getJournalEntriesTableRepeaterSchema(): array
  298. {
  299. return [
  300. Forms\Components\Select::make('type')
  301. ->label('Type')
  302. ->options(JournalEntryType::class)
  303. ->live()
  304. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, $state, $old) {
  305. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  306. })
  307. ->softRequired(),
  308. Forms\Components\TextInput::make('description')
  309. ->label('Description'),
  310. Forms\Components\Select::make('account_id')
  311. ->label('Account')
  312. ->options(fn (?JournalEntry $journalEntry): array => Transaction::getJournalAccountOptions(currentAccountId: $journalEntry?->account_id))
  313. ->softRequired()
  314. ->searchable(),
  315. Forms\Components\TextInput::make('amount')
  316. ->label('Amount')
  317. ->live()
  318. ->mask(moneyMask(CurrencyAccessor::getDefaultCurrency()))
  319. ->afterStateUpdated(function (Forms\Get $get, Forms\Set $set, ?string $state, ?string $old) {
  320. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  321. })
  322. ->softRequired(),
  323. ];
  324. }
  325. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  326. {
  327. $typeLabel = $type->getLabel();
  328. return FormAction::make("add{$typeLabel}Entry")
  329. ->button()
  330. ->outlined()
  331. ->color($type->isDebit() ? 'primary' : 'gray')
  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. }