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 33KB

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