您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

HasTransactionAction.php 16KB

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