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

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