Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

HasTransactionAction.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. <?php
  2. namespace App\Concerns;
  3. use App\Enums\Accounting\AccountCategory;
  4. use App\Enums\Accounting\JournalEntryType;
  5. use App\Enums\Accounting\TransactionType;
  6. use App\Filament\Forms\Components\CustomTableRepeater;
  7. use App\Models\Accounting\Account;
  8. use App\Models\Accounting\JournalEntry;
  9. use App\Models\Accounting\Transaction;
  10. use App\Models\Banking\BankAccount;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use Awcodes\TableRepeater\Header;
  14. use Filament\Forms;
  15. use Filament\Forms\Components\Actions\Action as FormAction;
  16. use Filament\Forms\Form;
  17. use Filament\Support\Enums\IconPosition;
  18. use Filament\Support\Enums\IconSize;
  19. use Illuminate\Contracts\View\View;
  20. use Illuminate\Support\Str;
  21. trait HasTransactionAction
  22. {
  23. use HasJournalEntryActions;
  24. protected ?TransactionType $transactionType = null;
  25. public function type(TransactionType $type): static
  26. {
  27. $this->transactionType = $type;
  28. return $this;
  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' => static::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() ? static::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. ->afterStateUpdated(function (Forms\Set $set, $state, $old, Forms\Get $get) {
  81. $amount = CurrencyConverter::convertAndSet(
  82. BankAccount::find($state)->account->currency_code,
  83. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  84. $get('amount')
  85. );
  86. if ($amount !== null) {
  87. $set('amount', $amount);
  88. }
  89. })
  90. ->required(),
  91. Forms\Components\Select::make('type')
  92. ->label('Type')
  93. ->live()
  94. ->options([
  95. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  96. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  97. ])
  98. ->required()
  99. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', static::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  100. Forms\Components\TextInput::make('amount')
  101. ->label('Amount')
  102. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  103. ->required(),
  104. Forms\Components\Select::make('account_id')
  105. ->label('Category')
  106. ->options(fn (Forms\Get $get, ?Transaction $transaction) => Transaction::getChartAccountOptions(type: TransactionType::parse($get('type')), nominalAccountsOnly: true, currentAccountId: $transaction?->account_id))
  107. ->searchable()
  108. ->preload()
  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::getChartAccountOptions(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. ->label("Add {$typeLabel} entry")
  330. ->button()
  331. ->outlined()
  332. ->color($type->isDebit() ? 'primary' : 'gray')
  333. ->iconSize(IconSize::Small)
  334. ->iconPosition(IconPosition::Before)
  335. ->action(function (CustomTableRepeater $component) use ($type) {
  336. $state = $component->getState();
  337. $newUuid = (string) Str::uuid();
  338. $state[$newUuid] = $this->defaultEntry($type);
  339. $component->state($state);
  340. });
  341. }
  342. public function getJournalTransactionModalFooter(): View
  343. {
  344. return view(
  345. 'filament.company.components.actions.journal-entry-footer',
  346. [
  347. 'debitAmount' => $this->getFormattedDebitAmount(),
  348. 'creditAmount' => $this->getFormattedCreditAmount(),
  349. 'difference' => $this->getFormattedBalanceDifference(),
  350. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  351. ],
  352. );
  353. }
  354. public static function getUncategorizedAccountByType(TransactionType $type): ?Account
  355. {
  356. [$category, $accountName] = match ($type) {
  357. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  358. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  359. default => [null, null],
  360. };
  361. return Account::where('category', $category)
  362. ->where('name', $accountName)
  363. ->first();
  364. }
  365. }