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.

Transactions.php 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. <?php
  2. namespace App\Filament\Company\Pages\Accounting;
  3. use App\Concerns\HasJournalEntryActions;
  4. use App\Enums\Accounting\AccountCategory;
  5. use App\Enums\Accounting\JournalEntryType;
  6. use App\Enums\Accounting\TransactionType;
  7. use App\Facades\Accounting;
  8. use App\Filament\Company\Pages\Service\ConnectedAccount;
  9. use App\Filament\Forms\Components\DateRangeSelect;
  10. use App\Filament\Forms\Components\JournalEntryRepeater;
  11. use App\Filament\Tables\Actions\ReplicateBulkAction;
  12. use App\Models\Accounting\Account;
  13. use App\Models\Accounting\JournalEntry;
  14. use App\Models\Accounting\Transaction;
  15. use App\Models\Banking\BankAccount;
  16. use App\Models\Company;
  17. use App\Utilities\Currency\CurrencyAccessor;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use Awcodes\TableRepeater\Header;
  20. use Exception;
  21. use Filament\Actions;
  22. use Filament\Facades\Filament;
  23. use Filament\Forms;
  24. use Filament\Forms\Components\Actions\Action as FormAction;
  25. use Filament\Forms\Components\DatePicker;
  26. use Filament\Forms\Components\Grid;
  27. use Filament\Forms\Components\Select;
  28. use Filament\Forms\Components\Tabs;
  29. use Filament\Forms\Components\Tabs\Tab;
  30. use Filament\Forms\Components\Textarea;
  31. use Filament\Forms\Components\TextInput;
  32. use Filament\Forms\Form;
  33. use Filament\Forms\Get;
  34. use Filament\Forms\Set;
  35. use Filament\Pages\Page;
  36. use Filament\Support\Colors\Color;
  37. use Filament\Support\Enums\FontWeight;
  38. use Filament\Support\Enums\IconPosition;
  39. use Filament\Support\Enums\IconSize;
  40. use Filament\Support\Enums\MaxWidth;
  41. use Filament\Tables;
  42. use Filament\Tables\Concerns\InteractsWithTable;
  43. use Filament\Tables\Contracts\HasTable;
  44. use Filament\Tables\Table;
  45. use Illuminate\Contracts\View\View;
  46. use Illuminate\Database\Eloquent\Builder;
  47. use Illuminate\Support\Carbon;
  48. use Illuminate\Support\Collection;
  49. use Illuminate\Support\Str;
  50. /**
  51. * @property Form $form
  52. */
  53. class Transactions extends Page implements HasTable
  54. {
  55. use HasJournalEntryActions;
  56. use InteractsWithTable;
  57. protected static string $view = 'filament.company.pages.accounting.transactions';
  58. protected static ?string $model = Transaction::class;
  59. protected static ?string $navigationGroup = 'Accounting';
  60. public string $fiscalYearStartDate = '';
  61. public string $fiscalYearEndDate = '';
  62. public function mount(): void
  63. {
  64. /** @var Company $company */
  65. $company = Filament::getTenant();
  66. $this->fiscalYearStartDate = $company->locale->fiscalYearStartDate();
  67. $this->fiscalYearEndDate = $company->locale->fiscalYearEndDate();
  68. }
  69. public static function getModel(): string
  70. {
  71. return static::$model;
  72. }
  73. public static function getEloquentQuery(): Builder
  74. {
  75. return static::getModel()::query();
  76. }
  77. public function getMaxContentWidth(): MaxWidth | string | null
  78. {
  79. return 'max-w-8xl';
  80. }
  81. protected function getHeaderActions(): array
  82. {
  83. return [
  84. $this->buildTransactionAction('addIncome', 'Add income', TransactionType::Deposit),
  85. $this->buildTransactionAction('addExpense', 'Add expense', TransactionType::Withdrawal),
  86. Actions\CreateAction::make('addTransfer')
  87. ->label('Add transfer')
  88. ->modalHeading('Add Transfer')
  89. ->modalWidth(MaxWidth::ThreeExtraLarge)
  90. ->model(static::getModel())
  91. ->fillForm(fn (): array => $this->getFormDefaultsForType(TransactionType::Transfer))
  92. ->form(fn (Form $form) => $this->transferForm($form))
  93. ->button()
  94. ->outlined(),
  95. Actions\ActionGroup::make([
  96. Actions\CreateAction::make('addJournalTransaction')
  97. ->label('Add journal transaction')
  98. ->fillForm(fn (): array => $this->getFormDefaultsForType(TransactionType::Journal))
  99. ->modalWidth(MaxWidth::Screen)
  100. ->extraModalWindowAttributes([
  101. 'class' => 'journal-transaction-modal',
  102. ])
  103. ->model(static::getModel())
  104. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  105. ->modalSubmitAction(fn (Actions\StaticAction $action) => $action->disabled(! $this->isJournalEntryBalanced()))
  106. ->groupedIcon(null)
  107. ->modalHeading('Journal Entry')
  108. ->mutateFormDataUsing(static fn (array $data) => array_merge($data, ['type' => TransactionType::Journal]))
  109. ->afterFormFilled(fn () => $this->resetJournalEntryAmounts())
  110. ->after(fn (Transaction $transaction) => $transaction->updateAmountIfBalanced()),
  111. Actions\Action::make('connectBank')
  112. ->label('Connect your bank')
  113. ->url(ConnectedAccount::getUrl()),
  114. ])
  115. ->label('More')
  116. ->button()
  117. ->outlined()
  118. ->dropdownWidth('max-w-fit')
  119. ->dropdownPlacement('bottom-end')
  120. ->icon('heroicon-c-chevron-down')
  121. ->iconSize(IconSize::Small)
  122. ->iconPosition(IconPosition::After),
  123. ];
  124. }
  125. public function transferForm(Form $form): Form
  126. {
  127. return $form
  128. ->schema([
  129. Forms\Components\DatePicker::make('posted_at')
  130. ->label('Date')
  131. ->required(),
  132. Forms\Components\TextInput::make('description')
  133. ->label('Description'),
  134. Forms\Components\Select::make('bank_account_id')
  135. ->label('From account')
  136. ->options(fn (Get $get, ?Transaction $transaction) => $this->getBankAccountOptions(excludedAccountId: $get('account_id'), currentBankAccountId: $transaction?->bank_account_id))
  137. ->live()
  138. ->searchable()
  139. ->afterStateUpdated(function (Set $set, $state, $old, Get $get) {
  140. $amount = CurrencyConverter::convertAndSet(
  141. BankAccount::find($state)->account->currency_code,
  142. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  143. $get('amount')
  144. );
  145. if ($amount !== null) {
  146. $set('amount', $amount);
  147. }
  148. })
  149. ->required(),
  150. Forms\Components\Select::make('type')
  151. ->label('Type')
  152. ->options([
  153. TransactionType::Transfer->value => TransactionType::Transfer->getLabel(),
  154. ])
  155. ->disabled()
  156. ->dehydrated()
  157. ->required(),
  158. Forms\Components\TextInput::make('amount')
  159. ->label('Amount')
  160. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  161. ->required(),
  162. Forms\Components\Select::make('account_id')
  163. ->label('To account')
  164. ->live()
  165. ->options(fn (Get $get, ?Transaction $transaction) => $this->getBankAccountAccountOptions(excludedBankAccountId: $get('bank_account_id'), currentAccountId: $transaction?->account_id))
  166. ->searchable()
  167. ->required(),
  168. Forms\Components\Textarea::make('notes')
  169. ->label('Notes')
  170. ->autosize()
  171. ->rows(10)
  172. ->columnSpanFull(),
  173. ])
  174. ->columns();
  175. }
  176. public function transactionForm(Form $form): Form
  177. {
  178. return $form
  179. ->schema([
  180. Forms\Components\DatePicker::make('posted_at')
  181. ->label('Date')
  182. ->required(),
  183. Forms\Components\TextInput::make('description')
  184. ->label('Description'),
  185. Forms\Components\Select::make('bank_account_id')
  186. ->label('Account')
  187. ->options(fn (?Transaction $transaction) => $this->getBankAccountOptions(currentBankAccountId: $transaction?->bank_account_id))
  188. ->live()
  189. ->searchable()
  190. ->afterStateUpdated(function (Set $set, $state, $old, Get $get) {
  191. $amount = CurrencyConverter::convertAndSet(
  192. BankAccount::find($state)->account->currency_code,
  193. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  194. $get('amount')
  195. );
  196. if ($amount !== null) {
  197. $set('amount', $amount);
  198. }
  199. })
  200. ->required(),
  201. Forms\Components\Select::make('type')
  202. ->label('Type')
  203. ->live()
  204. ->options([
  205. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  206. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  207. ])
  208. ->required()
  209. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', static::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  210. Forms\Components\TextInput::make('amount')
  211. ->label('Amount')
  212. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  213. ->required(),
  214. Forms\Components\Select::make('account_id')
  215. ->label('Category')
  216. ->options(fn (Forms\Get $get, ?Transaction $transaction) => $this->getChartAccountOptions(type: TransactionType::parse($get('type')), nominalAccountsOnly: true, currentAccountId: $transaction?->account_id))
  217. ->searchable()
  218. ->preload()
  219. ->required(),
  220. Forms\Components\Textarea::make('notes')
  221. ->label('Notes')
  222. ->autosize()
  223. ->rows(10)
  224. ->columnSpanFull(),
  225. ])
  226. ->columns();
  227. }
  228. public function journalTransactionForm(Form $form): Form
  229. {
  230. return $form
  231. ->schema([
  232. Tabs::make('Tabs')
  233. ->contained(false)
  234. ->tabs([
  235. $this->getJournalTransactionFormEditTab(),
  236. $this->getJournalTransactionFormNotesTab(),
  237. ]),
  238. ])
  239. ->columns(1);
  240. }
  241. /**
  242. * @throws Exception
  243. */
  244. public function table(Table $table): Table
  245. {
  246. return $table
  247. ->query(static::getEloquentQuery())
  248. ->modifyQueryUsing(function (Builder $query) {
  249. $query->with([
  250. 'account',
  251. 'bankAccount.account',
  252. 'journalEntries.account',
  253. ])
  254. ->where(function (Builder $query) {
  255. $query->whereNull('transactionable_id')
  256. ->orWhere('is_payment', true);
  257. });
  258. })
  259. ->columns([
  260. Tables\Columns\TextColumn::make('posted_at')
  261. ->label('Date')
  262. ->sortable()
  263. ->defaultDateFormat(),
  264. Tables\Columns\TextColumn::make('type')
  265. ->label('Type')
  266. ->sortable()
  267. ->toggleable(isToggledHiddenByDefault: true),
  268. Tables\Columns\TextColumn::make('description')
  269. ->label('Description')
  270. ->limit(50)
  271. ->toggleable(),
  272. Tables\Columns\TextColumn::make('bankAccount.account.name')
  273. ->label('Account')
  274. ->toggleable(),
  275. Tables\Columns\TextColumn::make('account.name')
  276. ->label('Category')
  277. ->prefix(static fn (Transaction $transaction) => $transaction->type->isTransfer() ? 'Transfer to ' : null)
  278. ->toggleable()
  279. ->state(static fn (Transaction $transaction) => $transaction->account->name ?? 'Journal Entry'),
  280. Tables\Columns\TextColumn::make('amount')
  281. ->label('Amount')
  282. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  283. ->color(
  284. static fn (Transaction $transaction) => match ($transaction->type) {
  285. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  286. TransactionType::Journal => 'primary',
  287. default => null,
  288. }
  289. )
  290. ->sortable()
  291. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code),
  292. ])
  293. ->recordClasses(static fn (Transaction $transaction) => $transaction->reviewed ? 'bg-primary-300/10' : null)
  294. ->defaultSort('posted_at', 'desc')
  295. ->filters([
  296. Tables\Filters\SelectFilter::make('bank_account_id')
  297. ->label('Account')
  298. ->searchable()
  299. ->options(fn () => $this->getBankAccountOptions(false)),
  300. Tables\Filters\SelectFilter::make('account_id')
  301. ->label('Category')
  302. ->multiple()
  303. ->options(fn () => $this->getChartAccountOptions(nominalAccountsOnly: false)),
  304. Tables\Filters\TernaryFilter::make('reviewed')
  305. ->label('Status')
  306. ->native(false)
  307. ->trueLabel('Reviewed')
  308. ->falseLabel('Not Reviewed'),
  309. Tables\Filters\SelectFilter::make('type')
  310. ->label('Type')
  311. ->native(false)
  312. ->options(TransactionType::class),
  313. $this->buildDateRangeFilter('posted_at', 'Posted', true),
  314. $this->buildDateRangeFilter('updated_at', 'Last modified'),
  315. ])
  316. ->filtersFormSchema(fn (array $filters): array => [
  317. Grid::make()
  318. ->schema([
  319. $filters['bank_account_id'],
  320. $filters['account_id'],
  321. $filters['reviewed'],
  322. $filters['type'],
  323. ])
  324. ->columnSpanFull()
  325. ->extraAttributes(['class' => 'border-b border-gray-200 dark:border-white/10 pb-8']),
  326. $filters['posted_at'],
  327. $filters['updated_at'],
  328. ])
  329. ->filtersFormWidth(MaxWidth::ThreeExtraLarge)
  330. ->actions([
  331. Tables\Actions\Action::make('markAsReviewed')
  332. ->label('Mark as reviewed')
  333. ->view('filament.company.components.tables.actions.mark-as-reviewed')
  334. ->icon(static fn (Transaction $transaction) => $transaction->reviewed ? 'heroicon-s-check-circle' : 'heroicon-o-check-circle')
  335. ->color(static fn (Transaction $transaction, Tables\Actions\Action $action) => match (static::determineTransactionState($transaction, $action)) {
  336. 'reviewed' => 'primary',
  337. 'unreviewed' => Color::rgb('rgb(' . Color::Gray[600] . ')'),
  338. 'uncategorized' => 'gray',
  339. })
  340. ->tooltip(static fn (Transaction $transaction, Tables\Actions\Action $action) => match (static::determineTransactionState($transaction, $action)) {
  341. 'reviewed' => 'Reviewed',
  342. 'unreviewed' => 'Mark as reviewed',
  343. 'uncategorized' => 'Categorize first to mark as reviewed',
  344. })
  345. ->disabled(fn (Transaction $transaction): bool => $transaction->isUncategorized())
  346. ->action(fn (Transaction $transaction) => $transaction->update(['reviewed' => ! $transaction->reviewed])),
  347. Tables\Actions\ActionGroup::make([
  348. Tables\Actions\ActionGroup::make([
  349. Tables\Actions\EditAction::make('editTransaction')
  350. ->label('Edit transaction')
  351. ->modalHeading('Edit Transaction')
  352. ->modalWidth(MaxWidth::ThreeExtraLarge)
  353. ->form(fn (Form $form) => $this->transactionForm($form))
  354. ->visible(static fn (Transaction $transaction) => $transaction->type->isStandard()),
  355. Tables\Actions\EditAction::make('editTransfer')
  356. ->label('Edit transfer')
  357. ->modalHeading('Edit Transfer')
  358. ->modalWidth(MaxWidth::ThreeExtraLarge)
  359. ->form(fn (Form $form) => $this->transferForm($form))
  360. ->visible(static fn (Transaction $transaction) => $transaction->type->isTransfer()),
  361. Tables\Actions\EditAction::make('editJournalTransaction')
  362. ->label('Edit journal transaction')
  363. ->modalHeading('Journal Entry')
  364. ->modalWidth(MaxWidth::Screen)
  365. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  366. ->afterFormFilled(function (Transaction $transaction) {
  367. $debitAmounts = $transaction->journalEntries->sumDebits()->getAmount();
  368. $creditAmounts = $transaction->journalEntries->sumCredits()->getAmount();
  369. $this->setDebitAmount($debitAmounts);
  370. $this->setCreditAmount($creditAmounts);
  371. })
  372. ->modalSubmitAction(fn (Actions\StaticAction $action) => $action->disabled(! $this->isJournalEntryBalanced()))
  373. ->after(fn (Transaction $transaction) => $transaction->updateAmountIfBalanced())
  374. ->visible(static fn (Transaction $transaction) => $transaction->type->isJournal()),
  375. Tables\Actions\ReplicateAction::make()
  376. ->excludeAttributes(['created_by', 'updated_by', 'created_at', 'updated_at'])
  377. ->modal(false)
  378. ->beforeReplicaSaved(static function (Transaction $replica) {
  379. $replica->description = '(Copy of) ' . $replica->description;
  380. })
  381. ->after(static function (Transaction $original, Transaction $replica) {
  382. $original->journalEntries->each(function (JournalEntry $entry) use ($replica) {
  383. $entry->replicate([
  384. 'transaction_id',
  385. ])->fill([
  386. 'transaction_id' => $replica->id,
  387. ])->save();
  388. });
  389. }),
  390. ])->dropdown(false),
  391. Tables\Actions\DeleteAction::make(),
  392. ]),
  393. ])
  394. ->bulkActions([
  395. Tables\Actions\BulkActionGroup::make([
  396. Tables\Actions\DeleteBulkAction::make(),
  397. ReplicateBulkAction::make()
  398. ->label('Replicate')
  399. ->modalWidth(MaxWidth::Large)
  400. ->modalDescription('Replicating transactions will also replicate their journal entries. Are you sure you want to proceed?')
  401. ->successNotificationTitle('Transactions replicated successfully')
  402. ->failureNotificationTitle('Failed to replicate transactions')
  403. ->deselectRecordsAfterCompletion()
  404. ->excludeAttributes(['created_by', 'updated_by', 'created_at', 'updated_at'])
  405. ->beforeReplicaSaved(static function (Transaction $replica) {
  406. $replica->description = '(Copy of) ' . $replica->description;
  407. })
  408. ->withReplicatedRelationships(['journalEntries']),
  409. ]),
  410. ]);
  411. }
  412. protected function buildTransactionAction(string $name, string $label, TransactionType $type): Actions\CreateAction
  413. {
  414. return Actions\CreateAction::make($name)
  415. ->label($label)
  416. ->modalWidth(MaxWidth::ThreeExtraLarge)
  417. ->model(static::getModel())
  418. ->fillForm(fn (): array => $this->getFormDefaultsForType($type))
  419. ->form(fn (Form $form) => $this->transactionForm($form))
  420. ->button()
  421. ->outlined();
  422. }
  423. protected function getFormDefaultsForType(TransactionType $type): array
  424. {
  425. $commonDefaults = [
  426. 'posted_at' => today(),
  427. ];
  428. return match ($type) {
  429. TransactionType::Deposit, TransactionType::Withdrawal, TransactionType::Transfer => array_merge($commonDefaults, $this->transactionDefaults($type)),
  430. TransactionType::Journal => array_merge($commonDefaults, $this->journalEntryDefaults()),
  431. };
  432. }
  433. protected function journalEntryDefaults(): array
  434. {
  435. return [
  436. 'journalEntries' => [
  437. $this->defaultEntry(JournalEntryType::Debit),
  438. $this->defaultEntry(JournalEntryType::Credit),
  439. ],
  440. ];
  441. }
  442. protected function defaultEntry(JournalEntryType $journalEntryType): array
  443. {
  444. return [
  445. 'type' => $journalEntryType,
  446. 'account_id' => static::getUncategorizedAccountByType($journalEntryType->isDebit() ? TransactionType::Withdrawal : TransactionType::Deposit)?->id,
  447. 'amount' => '0.00',
  448. ];
  449. }
  450. protected function transactionDefaults(TransactionType $type): array
  451. {
  452. return [
  453. 'type' => $type,
  454. 'bank_account_id' => BankAccount::where('enabled', true)->first()?->id,
  455. 'amount' => '0.00',
  456. 'account_id' => ! $type->isTransfer() ? static::getUncategorizedAccountByType($type)->id : null,
  457. ];
  458. }
  459. public static function getUncategorizedAccountByType(TransactionType $type): ?Account
  460. {
  461. [$category, $accountName] = match ($type) {
  462. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  463. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  464. default => [null, null],
  465. };
  466. return Account::where('category', $category)
  467. ->where('name', $accountName)
  468. ->first();
  469. }
  470. protected function getJournalTransactionFormEditTab(): Tab
  471. {
  472. return Tab::make('Edit')
  473. ->label('Edit')
  474. ->icon('heroicon-o-pencil-square')
  475. ->schema([
  476. $this->getTransactionDetailsGrid(),
  477. $this->getJournalEntriesTableRepeater(),
  478. ]);
  479. }
  480. protected function getJournalTransactionFormNotesTab(): Tab
  481. {
  482. return Tab::make('Notes')
  483. ->label('Notes')
  484. ->icon('heroicon-o-clipboard')
  485. ->id('notes')
  486. ->schema([
  487. $this->getTransactionDetailsGrid(),
  488. Textarea::make('notes')
  489. ->label('Notes')
  490. ->rows(10)
  491. ->autosize(),
  492. ]);
  493. }
  494. protected function getTransactionDetailsGrid(): Grid
  495. {
  496. return Grid::make(8)
  497. ->schema([
  498. DatePicker::make('posted_at')
  499. ->label('Date')
  500. ->softRequired()
  501. ->displayFormat('Y-m-d'),
  502. TextInput::make('description')
  503. ->label('Description')
  504. ->columnSpan(2),
  505. ]);
  506. }
  507. protected function getJournalEntriesTableRepeater(): JournalEntryRepeater
  508. {
  509. return JournalEntryRepeater::make('journalEntries')
  510. ->relationship('journalEntries')
  511. ->hiddenLabel()
  512. ->columns(4)
  513. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  514. ->schema($this->getJournalEntriesTableRepeaterSchema())
  515. ->streamlined()
  516. ->deletable(fn (JournalEntryRepeater $repeater) => $repeater->getItemsCount() > 2)
  517. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  518. return $action
  519. ->action(function (array $arguments, JournalEntryRepeater $component): void {
  520. $items = $component->getState();
  521. $amount = $items[$arguments['item']]['amount'];
  522. $type = $items[$arguments['item']]['type'];
  523. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  524. unset($items[$arguments['item']]);
  525. $component->state($items);
  526. $component->callAfterStateUpdated();
  527. });
  528. })
  529. ->minItems(2)
  530. ->defaultItems(2)
  531. ->addable(false)
  532. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  533. ->extraActions([
  534. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  535. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  536. ]);
  537. }
  538. protected function getJournalEntriesTableRepeaterHeaders(): array
  539. {
  540. return [
  541. Header::make('type')
  542. ->width('150px')
  543. ->label('Type'),
  544. Header::make('description')
  545. ->width('320px')
  546. ->label('Description'),
  547. Header::make('account_id')
  548. ->width('320px')
  549. ->label('Account'),
  550. Header::make('amount')
  551. ->width('192px')
  552. ->label('Amount'),
  553. ];
  554. }
  555. protected function getJournalEntriesTableRepeaterSchema(): array
  556. {
  557. return [
  558. Select::make('type')
  559. ->label('Type')
  560. ->options(JournalEntryType::class)
  561. ->live()
  562. ->afterStateUpdated(function (Get $get, Set $set, $state, $old) {
  563. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  564. })
  565. ->softRequired(),
  566. TextInput::make('description')
  567. ->label('Description'),
  568. Select::make('account_id')
  569. ->label('Account')
  570. ->options(fn (?JournalEntry $journalEntry): array => $this->getChartAccountOptions(currentAccountId: $journalEntry?->account_id))
  571. ->live()
  572. ->softRequired()
  573. ->searchable(),
  574. TextInput::make('amount')
  575. ->label('Amount')
  576. ->live()
  577. ->mask(moneyMask(CurrencyAccessor::getDefaultCurrency()))
  578. ->afterStateUpdated(function (Get $get, Set $set, ?string $state, ?string $old) {
  579. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  580. })
  581. ->softRequired(),
  582. ];
  583. }
  584. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  585. {
  586. $typeLabel = $type->getLabel();
  587. return FormAction::make("add{$typeLabel}Entry")
  588. ->label("Add {$typeLabel} entry")
  589. ->button()
  590. ->outlined()
  591. ->color($type->isDebit() ? 'primary' : 'gray')
  592. ->iconSize(IconSize::Small)
  593. ->iconPosition(IconPosition::Before)
  594. ->action(function (JournalEntryRepeater $component) use ($type) {
  595. $state = $component->getState();
  596. $newUuid = (string) Str::uuid();
  597. $state[$newUuid] = $this->defaultEntry($type);
  598. $component->state($state);
  599. });
  600. }
  601. public function getJournalTransactionModalFooter(): View
  602. {
  603. return view(
  604. 'filament.company.components.actions.journal-entry-footer',
  605. [
  606. 'debitAmount' => $this->getFormattedDebitAmount(),
  607. 'creditAmount' => $this->getFormattedCreditAmount(),
  608. 'difference' => $this->getFormattedBalanceDifference(),
  609. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  610. ],
  611. );
  612. }
  613. /**
  614. * @throws Exception
  615. */
  616. protected function buildDateRangeFilter(string $fieldPrefix, string $label, bool $hasBottomBorder = false): Tables\Filters\Filter
  617. {
  618. return Tables\Filters\Filter::make($fieldPrefix)
  619. ->columnSpanFull()
  620. ->form([
  621. Grid::make()
  622. ->live()
  623. ->schema([
  624. DateRangeSelect::make("{$fieldPrefix}_date_range")
  625. ->label($label)
  626. ->selectablePlaceholder(false)
  627. ->placeholder('Select a date range')
  628. ->startDateField("{$fieldPrefix}_start_date")
  629. ->endDateField("{$fieldPrefix}_end_date"),
  630. DatePicker::make("{$fieldPrefix}_start_date")
  631. ->label("{$label} from")
  632. ->columnStart(1)
  633. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  634. $set("{$fieldPrefix}_date_range", 'Custom');
  635. }),
  636. DatePicker::make("{$fieldPrefix}_end_date")
  637. ->label("{$label} to")
  638. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  639. $set("{$fieldPrefix}_date_range", 'Custom');
  640. }),
  641. ])
  642. ->extraAttributes($hasBottomBorder ? ['class' => 'border-b border-gray-200 dark:border-white/10 pb-8'] : []),
  643. ])
  644. ->query(function (Builder $query, array $data) use ($fieldPrefix): Builder {
  645. $query
  646. ->when($data["{$fieldPrefix}_start_date"], fn (Builder $query, $startDate) => $query->whereDate($fieldPrefix, '>=', $startDate))
  647. ->when($data["{$fieldPrefix}_end_date"], fn (Builder $query, $endDate) => $query->whereDate($fieldPrefix, '<=', $endDate));
  648. return $query;
  649. })
  650. ->indicateUsing(function (array $data) use ($fieldPrefix, $label): array {
  651. $indicators = [];
  652. $this->addIndicatorForDateRange($data, "{$fieldPrefix}_start_date", "{$fieldPrefix}_end_date", $label, $indicators);
  653. return $indicators;
  654. });
  655. }
  656. protected function addIndicatorForSingleSelection($data, $key, $label, &$indicators): void
  657. {
  658. if (filled($data[$key])) {
  659. $indicators[] = Tables\Filters\Indicator::make($label)
  660. ->removeField($key);
  661. }
  662. }
  663. protected function addMultipleSelectionIndicator($data, $key, callable $labelRetriever, $field, &$indicators): void
  664. {
  665. if (filled($data[$key])) {
  666. $labels = collect($data[$key])->map($labelRetriever);
  667. $additionalCount = $labels->count() - 1;
  668. $indicatorLabel = $additionalCount > 0 ? "{$labels->first()} + {$additionalCount}" : $labels->first();
  669. $indicators[] = Tables\Filters\Indicator::make($indicatorLabel)
  670. ->removeField($field);
  671. }
  672. }
  673. protected function addIndicatorForDateRange($data, $startKey, $endKey, $labelPrefix, &$indicators): void
  674. {
  675. $formattedStartDate = filled($data[$startKey]) ? Carbon::parse($data[$startKey])->toFormattedDateString() : null;
  676. $formattedEndDate = filled($data[$endKey]) ? Carbon::parse($data[$endKey])->toFormattedDateString() : null;
  677. if ($formattedStartDate && $formattedEndDate) {
  678. // If both start and end dates are set, show the combined date range as the indicator, no specific field needs to be removed since the entire filter will be removed
  679. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix}: {$formattedStartDate} - {$formattedEndDate}");
  680. } else {
  681. if ($formattedStartDate) {
  682. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} After: {$formattedStartDate}")
  683. ->removeField($startKey);
  684. }
  685. if ($formattedEndDate) {
  686. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} Before: {$formattedEndDate}")
  687. ->removeField($endKey);
  688. }
  689. }
  690. }
  691. protected static function determineTransactionState(Transaction $transaction, Tables\Actions\Action $action): string
  692. {
  693. if ($transaction->reviewed) {
  694. return 'reviewed';
  695. }
  696. if ($transaction->reviewed === false && $action->isEnabled()) {
  697. return 'unreviewed';
  698. }
  699. return 'uncategorized';
  700. }
  701. protected function getBankAccountOptions(?int $excludedAccountId = null, ?int $currentBankAccountId = null): array
  702. {
  703. return BankAccount::query()
  704. ->whereHas('account', function (Builder $query) {
  705. $query->where('archived', false);
  706. })
  707. ->with(['account' => function ($query) {
  708. $query->where('archived', false);
  709. }, 'account.subtype' => function ($query) {
  710. $query->select(['id', 'name']);
  711. }])
  712. ->when($excludedAccountId, fn (Builder $query) => $query->where('account_id', '!=', $excludedAccountId))
  713. ->when($currentBankAccountId, fn (Builder $query) => $query->orWhere('id', $currentBankAccountId))
  714. ->get()
  715. ->groupBy('account.subtype.name')
  716. ->map(fn (Collection $bankAccounts, string $subtype) => $bankAccounts->pluck('account.name', 'id'))
  717. ->toArray();
  718. }
  719. protected function getBankAccountAccountOptions(?int $excludedBankAccountId = null, ?int $currentAccountId = null): array
  720. {
  721. return Account::query()
  722. ->whereHas('bankAccount', function (Builder $query) use ($excludedBankAccountId) {
  723. // Exclude the specific bank account if provided
  724. if ($excludedBankAccountId) {
  725. $query->whereNot('id', $excludedBankAccountId);
  726. }
  727. })
  728. ->where(function (Builder $query) use ($currentAccountId) {
  729. $query->where('archived', false)
  730. ->orWhere('id', $currentAccountId);
  731. })
  732. ->get()
  733. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  734. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  735. ->toArray();
  736. }
  737. protected function getChartAccountOptions(?TransactionType $type = null, ?bool $nominalAccountsOnly = null, ?int $currentAccountId = null): array
  738. {
  739. $nominalAccountsOnly ??= false;
  740. $excludedCategory = match ($type) {
  741. TransactionType::Deposit => AccountCategory::Expense,
  742. TransactionType::Withdrawal => AccountCategory::Revenue,
  743. default => null,
  744. };
  745. return Account::query()
  746. ->when($nominalAccountsOnly, fn (Builder $query) => $query->doesntHave('bankAccount'))
  747. ->when($excludedCategory, fn (Builder $query) => $query->whereNot('category', $excludedCategory))
  748. ->where(function (Builder $query) use ($currentAccountId) {
  749. $query->where('archived', false)
  750. ->orWhere('id', $currentAccountId);
  751. })
  752. ->get()
  753. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  754. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  755. ->toArray();
  756. }
  757. protected function getBalanceForAllAccounts(): string
  758. {
  759. return Accounting::getTotalBalanceForAllBankAccounts($this->fiscalYearStartDate, $this->fiscalYearEndDate)->format();
  760. }
  761. }