You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Transactions.php 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740
  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\Enums\Setting\DateFormat;
  8. use App\Facades\Accounting;
  9. use App\Filament\Company\Pages\Service\ConnectedAccount;
  10. use App\Forms\Components\DateRangeSelect;
  11. use App\Forms\Components\JournalEntryRepeater;
  12. use App\Models\Accounting\Account;
  13. use App\Models\Accounting\Transaction;
  14. use App\Models\Banking\BankAccount;
  15. use App\Models\Company;
  16. use App\Models\Setting\Localization;
  17. use Awcodes\TableRepeater\Header;
  18. use Exception;
  19. use Filament\Actions;
  20. use Filament\Facades\Filament;
  21. use Filament\Forms;
  22. use Filament\Forms\Components\Actions\Action as FormAction;
  23. use Filament\Forms\Components\DatePicker;
  24. use Filament\Forms\Components\Grid;
  25. use Filament\Forms\Components\Select;
  26. use Filament\Forms\Components\Tabs;
  27. use Filament\Forms\Components\Tabs\Tab;
  28. use Filament\Forms\Components\Textarea;
  29. use Filament\Forms\Components\TextInput;
  30. use Filament\Forms\Form;
  31. use Filament\Forms\Get;
  32. use Filament\Forms\Set;
  33. use Filament\Pages\Page;
  34. use Filament\Support\Colors\Color;
  35. use Filament\Support\Enums\Alignment;
  36. use Filament\Support\Enums\FontWeight;
  37. use Filament\Support\Enums\IconPosition;
  38. use Filament\Support\Enums\IconSize;
  39. use Filament\Support\Enums\MaxWidth;
  40. use Filament\Support\RawJs;
  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 $navigationParentItem = 'Chart of Accounts';
  60. protected static ?string $navigationGroup = 'Accounting';
  61. public ?string $bankAccountIdFiltered = 'all';
  62. public string $fiscalYearStartDate = '';
  63. public string $fiscalYearEndDate = '';
  64. public function mount(): void
  65. {
  66. /** @var Company $company */
  67. $company = Filament::getTenant();
  68. $this->fiscalYearStartDate = $company->locale->fiscalYearStartDate();
  69. $this->fiscalYearEndDate = $company->locale->fiscalYearEndDate();
  70. }
  71. public static function getModel(): string
  72. {
  73. return static::$model;
  74. }
  75. public static function getEloquentQuery(): Builder
  76. {
  77. return static::getModel()::query();
  78. }
  79. protected function getHeaderActions(): array
  80. {
  81. return [
  82. $this->buildTransactionAction('addIncome', 'Add Income', TransactionType::Deposit),
  83. $this->buildTransactionAction('addExpense', 'Add Expense', TransactionType::Withdrawal),
  84. Actions\ActionGroup::make([
  85. Actions\CreateAction::make('addJournalTransaction')
  86. ->label('Add Journal Transaction')
  87. ->fillForm(fn (): array => $this->getFormDefaultsForType(TransactionType::Journal))
  88. ->modalWidth(MaxWidth::Screen)
  89. ->model(static::getModel())
  90. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  91. ->modalSubmitAction(fn (Actions\StaticAction $action) => $action->disabled(! $this->isJournalEntryBalanced()))
  92. ->groupedIcon(null)
  93. ->modalHeading('Journal Entry')
  94. ->mutateFormDataUsing(static fn (array $data) => array_merge($data, ['type' => TransactionType::Journal]))
  95. ->afterFormFilled(fn () => $this->resetJournalEntryAmounts()),
  96. Actions\Action::make('connectBank')
  97. ->label('Connect Your Bank')
  98. ->url(ConnectedAccount::getUrl()),
  99. ])
  100. ->label('More')
  101. ->button()
  102. ->outlined()
  103. ->dropdownWidth('max-w-fit')
  104. ->dropdownPlacement('bottom-end')
  105. ->icon('heroicon-c-chevron-down')
  106. ->iconSize(IconSize::Small)
  107. ->iconPosition(IconPosition::After),
  108. ];
  109. }
  110. public function form(Form $form): Form
  111. {
  112. return $form
  113. ->schema([
  114. Forms\Components\Select::make('bankAccountIdFiltered')
  115. ->label('Account')
  116. ->hiddenLabel()
  117. ->allowHtml()
  118. ->options(fn () => $this->getBankAccountOptions(true, true))
  119. ->live()
  120. ->selectablePlaceholder(false)
  121. ->columnSpan(4),
  122. ])
  123. ->columns(14);
  124. }
  125. public function transactionForm(Form $form): Form
  126. {
  127. return $form
  128. ->schema([
  129. Forms\Components\DatePicker::make('posted_at')
  130. ->label('Date')
  131. ->required()
  132. ->displayFormat('Y-m-d'),
  133. Forms\Components\TextInput::make('description')
  134. ->label('Description'),
  135. Forms\Components\Select::make('bank_account_id')
  136. ->label('Account')
  137. ->options(fn () => $this->getBankAccountOptions())
  138. ->live()
  139. ->searchable()
  140. ->required(),
  141. Forms\Components\Select::make('type')
  142. ->label('Type')
  143. ->live()
  144. ->options([
  145. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  146. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  147. ])
  148. ->required()
  149. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', static::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  150. Forms\Components\TextInput::make('amount')
  151. ->label('Amount')
  152. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? 'USD')
  153. ->required(),
  154. Forms\Components\Select::make('account_id')
  155. ->label('Category')
  156. ->options(fn (Forms\Get $get) => $this->getChartAccountOptions(type: TransactionType::parse($get('type')), nominalAccountsOnly: true))
  157. ->searchable()
  158. ->preload()
  159. ->required(),
  160. Forms\Components\Textarea::make('notes')
  161. ->label('Notes')
  162. ->autosize()
  163. ->rows(10)
  164. ->columnSpanFull(),
  165. ])
  166. ->columns();
  167. }
  168. public function journalTransactionForm(Form $form): Form
  169. {
  170. return $form
  171. ->schema([
  172. Tabs::make('Tabs')
  173. ->contained(false)
  174. ->tabs([
  175. $this->getJournalTransactionFormEditTab(),
  176. $this->getJournalTransactionFormNotesTab(),
  177. ]),
  178. ])
  179. ->columns(1);
  180. }
  181. /**
  182. * @throws Exception
  183. */
  184. public function table(Table $table): Table
  185. {
  186. return $table
  187. ->query(static::getEloquentQuery())
  188. ->modifyQueryUsing(function (Builder $query) {
  189. if ($this->bankAccountIdFiltered !== 'all') {
  190. $query->where('bank_account_id', $this->bankAccountIdFiltered);
  191. }
  192. })
  193. ->columns([
  194. Tables\Columns\TextColumn::make('posted_at')
  195. ->label('Date')
  196. ->sortable()
  197. ->formatStateUsing(static function ($state) {
  198. $dateFormat = Localization::firstOrFail()->date_format->value ?? DateFormat::DEFAULT;
  199. return Carbon::parse($state)->translatedFormat($dateFormat);
  200. }),
  201. Tables\Columns\TextColumn::make('description')
  202. ->limit(30)
  203. ->label('Description'),
  204. Tables\Columns\TextColumn::make('bankAccount.account.name')
  205. ->label('Account'),
  206. Tables\Columns\TextColumn::make('account.name')
  207. ->label('Category')
  208. ->state(static fn (Transaction $record) => $record->account->name ?? 'Journal Entry'),
  209. Tables\Columns\TextColumn::make('amount')
  210. ->label('Amount')
  211. ->weight(static fn (Transaction $record) => $record->reviewed ? null : FontWeight::SemiBold)
  212. ->color(
  213. static fn (Transaction $record) => match ($record->type) {
  214. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  215. TransactionType::Journal => 'primary',
  216. default => null,
  217. }
  218. )
  219. ->currency(static fn (Transaction $record) => $record->bankAccount->account->currency_code ?? 'USD', true)
  220. ->state(fn (Transaction $record) => $record->type === TransactionType::Journal ? $record->journalEntries->first()->amount : $record->amount),
  221. ])
  222. ->recordClasses(static fn (Transaction $record) => $record->reviewed ? 'bg-primary-300/10' : null)
  223. ->defaultSort('posted_at', 'desc')
  224. ->filters([
  225. Tables\Filters\Filter::make('filters')
  226. ->columnSpanFull()
  227. ->form([
  228. Grid::make()
  229. ->schema([
  230. Select::make('account_id')
  231. ->label('Category')
  232. ->options(fn () => $this->getChartAccountOptions(nominalAccountsOnly: true))
  233. ->multiple()
  234. ->searchable(),
  235. Select::make('reviewed')
  236. ->label('Status')
  237. ->native(false)
  238. ->options([
  239. '1' => 'Reviewed',
  240. '0' => 'Not Reviewed',
  241. ]),
  242. Select::make('type')
  243. ->label('Type')
  244. ->options(TransactionType::class)
  245. ->multiple(),
  246. ])
  247. ->extraAttributes([
  248. 'class' => 'border-b border-gray-200 dark:border-white/10 pb-8',
  249. ]),
  250. ])->query(function (Builder $query, array $data): Builder {
  251. if (filled($data['reviewed'])) {
  252. $reviewedStatus = $data['reviewed'] === '1';
  253. $query->where('reviewed', $reviewedStatus);
  254. }
  255. $query
  256. ->when($data['account_id'], fn (Builder $query, $accountIds) => $query->whereIn('account_id', $accountIds))
  257. ->when($data['type'], fn (Builder $query, $types) => $query->whereIn('type', $types));
  258. return $query;
  259. })
  260. ->indicateUsing(function (array $data): array {
  261. $indicators = [];
  262. $this->addIndicatorForSingleSelection($data, 'reviewed', $data['reviewed'] === '1' ? 'Reviewed' : 'Not Reviewed', $indicators);
  263. $this->addMultipleSelectionIndicator($data, 'account_id', fn ($accountId) => Account::find($accountId)->name, 'account_id', $indicators);
  264. $this->addMultipleSelectionIndicator($data, 'type', fn ($type) => TransactionType::parse($type)->getLabel(), 'type', $indicators);
  265. return $indicators;
  266. }),
  267. $this->buildDateRangeFilter('posted_at', 'Posted', true),
  268. $this->buildDateRangeFilter('updated_at', 'Last Modified'),
  269. ], layout: Tables\Enums\FiltersLayout::Modal)
  270. ->deferFilters()
  271. ->filtersFormColumns(2)
  272. ->filtersTriggerAction(
  273. fn (Tables\Actions\Action $action) => $action
  274. ->stickyModalHeader()
  275. ->stickyModalFooter()
  276. ->modalWidth(MaxWidth::ThreeExtraLarge)
  277. ->modalFooterActionsAlignment(Alignment::End)
  278. ->modalCancelAction(false)
  279. ->extraModalFooterActions(function (Table $table) use ($action) {
  280. return [
  281. $table->getFiltersApplyAction()
  282. ->close(),
  283. Actions\StaticAction::make('cancel')
  284. ->label($action->getModalCancelActionLabel())
  285. ->button()
  286. ->close()
  287. ->color('gray'),
  288. Tables\Actions\Action::make('resetFilters')
  289. ->label(__('Clear All'))
  290. ->color('primary')
  291. ->link()
  292. ->extraAttributes([
  293. 'class' => 'me-auto',
  294. ])
  295. ->action('resetTableFiltersForm'),
  296. ];
  297. })
  298. )
  299. ->actions([
  300. Tables\Actions\Action::make('markAsReviewed')
  301. ->label('Mark as Reviewed')
  302. ->view('filament.company.components.tables.actions.mark-as-reviewed')
  303. ->icon(static fn (Transaction $record) => $record->reviewed ? 'heroicon-s-check-circle' : 'heroicon-o-check-circle')
  304. ->color(static fn (Transaction $record, Tables\Actions\Action $action) => match (static::determineTransactionState($record, $action)) {
  305. 'reviewed' => 'primary',
  306. 'unreviewed' => Color::rgb('rgb(' . Color::Gray[600] . ')'),
  307. 'uncategorized' => 'gray',
  308. })
  309. ->tooltip(static fn (Transaction $record, Tables\Actions\Action $action) => match (static::determineTransactionState($record, $action)) {
  310. 'reviewed' => 'Reviewed',
  311. 'unreviewed' => 'Mark as Reviewed',
  312. 'uncategorized' => 'Categorize first to mark as reviewed',
  313. })
  314. ->disabled(fn (Transaction $record): bool => $record->isUncategorized())
  315. ->action(fn (Transaction $record) => $record->update(['reviewed' => ! $record->reviewed])),
  316. Tables\Actions\ActionGroup::make([
  317. Tables\Actions\EditAction::make('updateTransaction')
  318. ->label('Edit Transaction')
  319. ->modalHeading('Edit Transaction')
  320. ->modalWidth(MaxWidth::ThreeExtraLarge)
  321. ->form(fn (Form $form) => $this->transactionForm($form))
  322. ->hidden(static fn (Transaction $record) => $record->type === TransactionType::Journal),
  323. Tables\Actions\EditAction::make('updateJournalTransaction')
  324. ->label('Edit Journal Transaction')
  325. ->modalHeading('Journal Entry')
  326. ->modalWidth(MaxWidth::Screen)
  327. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  328. ->afterFormFilled(function (Transaction $record) {
  329. $debitAmounts = $record->journalEntries->where('type', JournalEntryType::Debit)->sum('amount');
  330. $creditAmounts = $record->journalEntries->where('type', JournalEntryType::Credit)->sum('amount');
  331. $this->setDebitAmount($debitAmounts);
  332. $this->setCreditAmount($creditAmounts);
  333. })
  334. ->hidden(static fn (Transaction $record) => $record->type !== TransactionType::Journal),
  335. Tables\Actions\DeleteAction::make(),
  336. Tables\Actions\ReplicateAction::make()
  337. ->excludeAttributes(['created_by', 'updated_by', 'created_at', 'updated_at'])
  338. ->modal(false)
  339. ->beforeReplicaSaved(static function (Transaction $replica) {
  340. $replica->description = '(Copy of) ' . $replica->description;
  341. }),
  342. ])
  343. ->dropdownPlacement('bottom-start')
  344. ->dropdownWidth('max-w-fit'),
  345. ])
  346. ->bulkActions([
  347. Tables\Actions\BulkActionGroup::make([
  348. Tables\Actions\DeleteBulkAction::make(),
  349. ]),
  350. ]);
  351. }
  352. protected function buildTransactionAction(string $name, string $label, TransactionType $type): Actions\CreateAction
  353. {
  354. return Actions\CreateAction::make($name)
  355. ->label($label)
  356. ->modalWidth(MaxWidth::ThreeExtraLarge)
  357. ->model(static::getModel())
  358. ->fillForm(fn (): array => $this->getFormDefaultsForType($type))
  359. ->form(fn (Form $form) => $this->transactionForm($form))
  360. ->button()
  361. ->outlined();
  362. }
  363. protected function getFormDefaultsForType(TransactionType $type): array
  364. {
  365. $commonDefaults = [
  366. 'posted_at' => now()->format('Y-m-d'),
  367. ];
  368. return match ($type) {
  369. TransactionType::Deposit, TransactionType::Withdrawal => array_merge($commonDefaults, $this->transactionDefaults($type)),
  370. TransactionType::Journal => array_merge($commonDefaults, $this->journalEntryDefaults()),
  371. };
  372. }
  373. protected function journalEntryDefaults(): array
  374. {
  375. return [
  376. 'journalEntries' => [
  377. $this->defaultEntry(JournalEntryType::Debit),
  378. $this->defaultEntry(JournalEntryType::Credit),
  379. ],
  380. ];
  381. }
  382. protected function defaultEntry(JournalEntryType $journalEntryType): array
  383. {
  384. return [
  385. 'type' => $journalEntryType,
  386. 'account_id' => static::getUncategorizedAccountByType($journalEntryType->isDebit() ? TransactionType::Withdrawal : TransactionType::Deposit)?->id,
  387. 'amount' => '0.00',
  388. ];
  389. }
  390. protected function transactionDefaults(TransactionType $type): array
  391. {
  392. return [
  393. 'type' => $type,
  394. 'bank_account_id' => BankAccount::where('enabled', true)->first()?->id,
  395. 'amount' => '0.00',
  396. 'account_id' => static::getUncategorizedAccountByType($type)?->id,
  397. ];
  398. }
  399. protected static function getUncategorizedAccountByType(TransactionType $type): ?Account
  400. {
  401. [$category, $accountName] = match ($type) {
  402. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  403. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  404. default => [null, null],
  405. };
  406. return Account::where('category', $category)
  407. ->where('name', $accountName)
  408. ->first();
  409. }
  410. protected function getJournalTransactionFormEditTab(): Tab
  411. {
  412. return Tab::make('Edit')
  413. ->label('Edit')
  414. ->icon('heroicon-o-pencil-square')
  415. ->schema([
  416. $this->getTransactionDetailsGrid(),
  417. $this->getJournalEntriesTableRepeater(),
  418. ]);
  419. }
  420. protected function getJournalTransactionFormNotesTab(): Tab
  421. {
  422. return Tab::make('Notes')
  423. ->label('Notes')
  424. ->icon('heroicon-o-clipboard')
  425. ->id('notes')
  426. ->schema([
  427. $this->getTransactionDetailsGrid(),
  428. Textarea::make('notes')
  429. ->label('Notes')
  430. ->rows(10)
  431. ->autosize(),
  432. ]);
  433. }
  434. protected function getTransactionDetailsGrid(): Grid
  435. {
  436. return Grid::make(8)
  437. ->schema([
  438. DatePicker::make('posted_at')
  439. ->label('Date')
  440. ->softRequired()
  441. ->displayFormat('Y-m-d'),
  442. TextInput::make('description')
  443. ->label('Description')
  444. ->columnSpan(2),
  445. ]);
  446. }
  447. protected function getJournalEntriesTableRepeater(): JournalEntryRepeater
  448. {
  449. return JournalEntryRepeater::make('journalEntries')
  450. ->relationship('journalEntries')
  451. ->hiddenLabel()
  452. ->columns(4)
  453. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  454. ->schema($this->getJournalEntriesTableRepeaterSchema())
  455. ->streamlined()
  456. ->deletable(fn (JournalEntryRepeater $repeater) => $repeater->getItemsCount() > 2)
  457. ->minItems(2)
  458. ->defaultItems(2)
  459. ->addable(false)
  460. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  461. ->extraActions([
  462. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  463. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  464. ]);
  465. }
  466. protected function getJournalEntriesTableRepeaterHeaders(): array
  467. {
  468. return [
  469. Header::make('type')
  470. ->width('150px')
  471. ->label('Type'),
  472. Header::make('description')
  473. ->width('320px')
  474. ->label('Description'),
  475. Header::make('account_id')
  476. ->width('320px')
  477. ->label('Account'),
  478. Header::make('amount')
  479. ->width('192px')
  480. ->label('Amount'),
  481. ];
  482. }
  483. protected function getJournalEntriesTableRepeaterSchema(): array
  484. {
  485. return [
  486. Select::make('type')
  487. ->label('Type')
  488. ->options(JournalEntryType::class)
  489. ->live()
  490. ->afterStateUpdated(function (Get $get, Set $set, ?string $state, ?string $old) {
  491. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  492. })
  493. ->softRequired(),
  494. TextInput::make('description')
  495. ->label('Description'),
  496. Select::make('account_id')
  497. ->label('Account')
  498. ->options(fn (): array => $this->getChartAccountOptions())
  499. ->live()
  500. ->softRequired()
  501. ->searchable(),
  502. TextInput::make('amount')
  503. ->label('Amount')
  504. ->live()
  505. ->mask(RawJs::make('$money($input)'))
  506. ->afterStateUpdated(function (Get $get, Set $set, ?string $state, ?string $old) {
  507. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  508. })
  509. ->softRequired(),
  510. ];
  511. }
  512. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  513. {
  514. $typeLabel = $type->getLabel();
  515. return FormAction::make("add{$typeLabel}Entry")
  516. ->label("Add {$typeLabel} Entry")
  517. ->button()
  518. ->outlined()
  519. ->color($type->isDebit() ? 'primary' : 'gray')
  520. ->iconSize(IconSize::Small)
  521. ->iconPosition(IconPosition::Before)
  522. ->action(function (JournalEntryRepeater $component) use ($type) {
  523. $state = $component->getState();
  524. $newUuid = (string) Str::uuid();
  525. $state[$newUuid] = $this->defaultEntry($type);
  526. $component->state($state);
  527. });
  528. }
  529. public function getJournalTransactionModalFooter(): View
  530. {
  531. return view(
  532. 'filament.company.components.actions.journal-entry-footer',
  533. [
  534. 'debitAmount' => $this->getFormattedDebitAmount(),
  535. 'creditAmount' => $this->getFormattedCreditAmount(),
  536. 'difference' => $this->getFormattedBalanceDifference(),
  537. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  538. ],
  539. );
  540. }
  541. /**
  542. * @throws Exception
  543. */
  544. protected function buildDateRangeFilter(string $fieldPrefix, string $label, bool $hasBottomBorder = false): Tables\Filters\Filter
  545. {
  546. return Tables\Filters\Filter::make($fieldPrefix)
  547. ->columnSpanFull()
  548. ->form([
  549. Grid::make()
  550. ->live()
  551. ->schema([
  552. DateRangeSelect::make("{$fieldPrefix}_date_range")
  553. ->label($label)
  554. ->selectablePlaceholder(false)
  555. ->placeholder('Select a date range')
  556. ->startDateField("{$fieldPrefix}_start_date")
  557. ->endDateField("{$fieldPrefix}_end_date"),
  558. DatePicker::make("{$fieldPrefix}_start_date")
  559. ->label("{$label} From")
  560. ->displayFormat('Y-m-d')
  561. ->columnStart(1)
  562. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  563. $set("{$fieldPrefix}_date_range", 'Custom');
  564. }),
  565. DatePicker::make("{$fieldPrefix}_end_date")
  566. ->label("{$label} To")
  567. ->displayFormat('Y-m-d')
  568. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  569. $set("{$fieldPrefix}_date_range", 'Custom');
  570. }),
  571. ])
  572. ->extraAttributes($hasBottomBorder ? ['class' => 'border-b border-gray-200 dark:border-white/10 pb-8'] : []),
  573. ])
  574. ->query(function (Builder $query, array $data) use ($fieldPrefix): Builder {
  575. $query
  576. ->when($data["{$fieldPrefix}_start_date"], fn (Builder $query, $startDate) => $query->whereDate($fieldPrefix, '>=', $startDate))
  577. ->when($data["{$fieldPrefix}_end_date"], fn (Builder $query, $endDate) => $query->whereDate($fieldPrefix, '<=', $endDate));
  578. return $query;
  579. })
  580. ->indicateUsing(function (array $data) use ($fieldPrefix, $label): array {
  581. $indicators = [];
  582. $this->addIndicatorForDateRange($data, "{$fieldPrefix}_start_date", "{$fieldPrefix}_end_date", $label, $indicators);
  583. return $indicators;
  584. });
  585. }
  586. protected function addIndicatorForSingleSelection($data, $key, $label, &$indicators): void
  587. {
  588. if (filled($data[$key])) {
  589. $indicators[] = Tables\Filters\Indicator::make($label)
  590. ->removeField($key);
  591. }
  592. }
  593. protected function addMultipleSelectionIndicator($data, $key, callable $labelRetriever, $field, &$indicators): void
  594. {
  595. if (filled($data[$key])) {
  596. $labels = collect($data[$key])->map($labelRetriever);
  597. $additionalCount = $labels->count() - 1;
  598. $indicatorLabel = $additionalCount > 0 ? "{$labels->first()} + {$additionalCount}" : $labels->first();
  599. $indicators[] = Tables\Filters\Indicator::make($indicatorLabel)
  600. ->removeField($field);
  601. }
  602. }
  603. protected function addIndicatorForDateRange($data, $startKey, $endKey, $labelPrefix, &$indicators): void
  604. {
  605. $formattedStartDate = filled($data[$startKey]) ? Carbon::parse($data[$startKey])->toFormattedDateString() : null;
  606. $formattedEndDate = filled($data[$endKey]) ? Carbon::parse($data[$endKey])->toFormattedDateString() : null;
  607. if ($formattedStartDate && $formattedEndDate) {
  608. // 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
  609. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix}: {$formattedStartDate} - {$formattedEndDate}");
  610. } else {
  611. if ($formattedStartDate) {
  612. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} After: {$formattedStartDate}")
  613. ->removeField($startKey);
  614. }
  615. if ($formattedEndDate) {
  616. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} Before: {$formattedEndDate}")
  617. ->removeField($endKey);
  618. }
  619. }
  620. }
  621. protected static function determineTransactionState(Transaction $record, Tables\Actions\Action $action): string
  622. {
  623. if ($record->reviewed) {
  624. return 'reviewed';
  625. }
  626. if ($record->reviewed === false && $action->isEnabled()) {
  627. return 'unreviewed';
  628. }
  629. return 'uncategorized';
  630. }
  631. protected function getChartAccountOptions(?TransactionType $type = null, bool $nominalAccountsOnly = false): array
  632. {
  633. $excludedCategory = match ($type) {
  634. TransactionType::Deposit => AccountCategory::Expense,
  635. TransactionType::Withdrawal => AccountCategory::Revenue,
  636. default => null,
  637. };
  638. return Account::query()
  639. ->when($nominalAccountsOnly, fn (Builder $query) => $query->whereNull('accountable_type'))
  640. ->when($excludedCategory, fn (Builder $query) => $query->whereNot('category', $excludedCategory))
  641. ->get()
  642. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  643. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  644. ->toArray();
  645. }
  646. protected function getBankAccountOptions(?bool $onlyWithTransactions = null, bool $isFilter = false): array
  647. {
  648. $onlyWithTransactions ??= false;
  649. $options = $isFilter ? [
  650. '' => ['all' => "All Accounts <span class='float-right'>{$this->getBalanceForAllAccounts()}</span>"],
  651. ] : [];
  652. $bankAccountOptions = BankAccount::with('account.subtype')
  653. ->when($onlyWithTransactions, fn (Builder $query) => $query->has('transactions'))
  654. ->get()
  655. ->groupBy('account.subtype.name')
  656. ->mapWithKeys(function (Collection $bankAccounts, string $subtype) use ($isFilter) {
  657. return [$subtype => $bankAccounts->mapWithKeys(function (BankAccount $bankAccount) use ($isFilter) {
  658. $label = $bankAccount->account->name;
  659. if ($isFilter) {
  660. $balance = $this->getAccountBalance($bankAccount->account);
  661. $label .= "<span class='float-right'>{$balance}</span>";
  662. }
  663. return [$bankAccount->id => $label];
  664. })];
  665. })
  666. ->toArray();
  667. return array_merge($options, $bankAccountOptions);
  668. }
  669. protected function getAccountBalance(Account $account): ?string
  670. {
  671. return Accounting::getEndingBalance($account, $this->fiscalYearStartDate, $this->fiscalYearEndDate)?->formattedForDisplay();
  672. }
  673. protected function getBalanceForAllAccounts(): string
  674. {
  675. return Accounting::getTotalBalanceForAllBankAccounts($this->fiscalYearStartDate, $this->fiscalYearEndDate)->formatted();
  676. }
  677. }