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

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