Вы не можете выбрать более 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' => company_today()->toDateString(),
  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. ->native()
  74. ->required(),
  75. Forms\Components\TextInput::make('description')
  76. ->label('Description'),
  77. Forms\Components\Select::make('bank_account_id')
  78. ->label('Account')
  79. ->options(fn (?Transaction $transaction) => Transaction::getBankAccountOptions(currentBankAccountId: $transaction?->bank_account_id))
  80. ->live()
  81. ->searchable()
  82. ->required(),
  83. Forms\Components\Select::make('type')
  84. ->label('Type')
  85. ->live()
  86. ->options([
  87. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  88. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  89. ])
  90. ->required()
  91. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', Transaction::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  92. Forms\Components\TextInput::make('amount')
  93. ->label('Amount')
  94. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  95. ->required(),
  96. Forms\Components\Select::make('account_id')
  97. ->label('Category')
  98. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getTransactionAccountOptions(type: TransactionType::parse($get('type')), currentAccountId: $transaction?->account_id))
  99. ->searchable()
  100. ->required(),
  101. Forms\Components\Textarea::make('notes')
  102. ->label('Notes')
  103. ->autosize()
  104. ->rows(10)
  105. ->columnSpanFull(),
  106. ])
  107. ->columns();
  108. }
  109. public function transferForm(Form $form): Form
  110. {
  111. return $form
  112. ->schema([
  113. Forms\Components\DatePicker::make('posted_at')
  114. ->label('Date')
  115. ->required(),
  116. Forms\Components\TextInput::make('description')
  117. ->label('Description'),
  118. Forms\Components\Select::make('bank_account_id')
  119. ->label('From account')
  120. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountOptions(excludedAccountId: $get('account_id'), currentBankAccountId: $transaction?->bank_account_id))
  121. ->live()
  122. ->searchable()
  123. ->required(),
  124. Forms\Components\Select::make('type')
  125. ->label('Type')
  126. ->options([
  127. TransactionType::Transfer->value => TransactionType::Transfer->getLabel(),
  128. ])
  129. ->disabled()
  130. ->dehydrated()
  131. ->required(),
  132. Forms\Components\TextInput::make('amount')
  133. ->label('Amount')
  134. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  135. ->required(),
  136. Forms\Components\Select::make('account_id')
  137. ->label('To account')
  138. ->live()
  139. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getBankAccountAccountOptions(excludedBankAccountId: $get('bank_account_id'), currentAccountId: $transaction?->account_id))
  140. ->searchable()
  141. ->required(),
  142. Forms\Components\Textarea::make('notes')
  143. ->label('Notes')
  144. ->autosize()
  145. ->rows(10)
  146. ->columnSpanFull(),
  147. ])
  148. ->columns();
  149. }
  150. public function journalTransactionForm(Form $form): Form
  151. {
  152. return $form
  153. ->schema([
  154. Forms\Components\Tabs::make('Tabs')
  155. ->contained(false)
  156. ->tabs([
  157. $this->getJournalTransactionFormEditTab(),
  158. $this->getJournalTransactionFormNotesTab(),
  159. ]),
  160. ])
  161. ->columns(1);
  162. }
  163. protected function getJournalTransactionFormEditTab(): Forms\Components\Tabs\Tab
  164. {
  165. return Forms\Components\Tabs\Tab::make('Edit')
  166. ->label('Edit')
  167. ->icon('heroicon-o-pencil-square')
  168. ->schema([
  169. $this->getTransactionDetailsGrid(),
  170. $this->getJournalEntriesTableRepeater(),
  171. ]);
  172. }
  173. protected function getJournalTransactionFormNotesTab(): Forms\Components\Tabs\Tab
  174. {
  175. return Forms\Components\Tabs\Tab::make('Notes')
  176. ->label('Notes')
  177. ->icon('heroicon-o-clipboard')
  178. ->id('notes')
  179. ->schema([
  180. $this->getTransactionDetailsGrid(),
  181. Forms\Components\Textarea::make('notes')
  182. ->label('Notes')
  183. ->rows(10)
  184. ->autosize(),
  185. ]);
  186. }
  187. protected function getTransactionDetailsGrid(): Forms\Components\Grid
  188. {
  189. return Forms\Components\Grid::make(6)
  190. ->schema([
  191. Forms\Components\DatePicker::make('posted_at')
  192. ->label('Date')
  193. ->softRequired(),
  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. }