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

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