Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

HasTransactionAction.php 15KB

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