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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824
  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\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(): JournalEntryRepeater
  510. {
  511. return JournalEntryRepeater::make('journalEntries')
  512. ->relationship('journalEntries')
  513. ->hiddenLabel()
  514. ->columns(4)
  515. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  516. ->schema($this->getJournalEntriesTableRepeaterSchema())
  517. ->streamlined()
  518. ->deletable(fn (JournalEntryRepeater $repeater) => $repeater->getItemsCount() > 2)
  519. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  520. return $action
  521. ->action(function (array $arguments, JournalEntryRepeater $component): void {
  522. $items = $component->getState();
  523. $amount = $items[$arguments['item']]['amount'];
  524. $type = $items[$arguments['item']]['type'];
  525. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  526. unset($items[$arguments['item']]);
  527. $component->state($items);
  528. $component->callAfterStateUpdated();
  529. });
  530. })
  531. ->minItems(2)
  532. ->defaultItems(2)
  533. ->addable(false)
  534. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  535. ->extraActions([
  536. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  537. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  538. ]);
  539. }
  540. protected function getJournalEntriesTableRepeaterHeaders(): array
  541. {
  542. return [
  543. Header::make('type')
  544. ->width('150px')
  545. ->label('Type'),
  546. Header::make('description')
  547. ->width('320px')
  548. ->label('Description'),
  549. Header::make('account_id')
  550. ->width('320px')
  551. ->label('Account'),
  552. Header::make('amount')
  553. ->width('192px')
  554. ->label('Amount'),
  555. ];
  556. }
  557. protected function getJournalEntriesTableRepeaterSchema(): array
  558. {
  559. return [
  560. Select::make('type')
  561. ->label('Type')
  562. ->options(JournalEntryType::class)
  563. ->live()
  564. ->afterStateUpdated(function (Get $get, Set $set, $state, $old) {
  565. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  566. })
  567. ->softRequired(),
  568. TextInput::make('description')
  569. ->label('Description'),
  570. Select::make('account_id')
  571. ->label('Account')
  572. ->options(fn (?JournalEntry $journalEntry): array => $this->getChartAccountOptions(currentAccountId: $journalEntry?->account_id))
  573. ->live()
  574. ->softRequired()
  575. ->searchable(),
  576. TextInput::make('amount')
  577. ->label('Amount')
  578. ->live()
  579. ->mask(moneyMask(CurrencyAccessor::getDefaultCurrency()))
  580. ->afterStateUpdated(function (Get $get, Set $set, ?string $state, ?string $old) {
  581. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  582. })
  583. ->softRequired(),
  584. ];
  585. }
  586. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  587. {
  588. $typeLabel = $type->getLabel();
  589. return FormAction::make("add{$typeLabel}Entry")
  590. ->label("Add {$typeLabel} entry")
  591. ->button()
  592. ->outlined()
  593. ->color($type->isDebit() ? 'primary' : 'gray')
  594. ->iconSize(IconSize::Small)
  595. ->iconPosition(IconPosition::Before)
  596. ->action(function (JournalEntryRepeater $component) use ($type) {
  597. $state = $component->getState();
  598. $newUuid = (string) Str::uuid();
  599. $state[$newUuid] = $this->defaultEntry($type);
  600. $component->state($state);
  601. });
  602. }
  603. public function getJournalTransactionModalFooter(): View
  604. {
  605. return view(
  606. 'filament.company.components.actions.journal-entry-footer',
  607. [
  608. 'debitAmount' => $this->getFormattedDebitAmount(),
  609. 'creditAmount' => $this->getFormattedCreditAmount(),
  610. 'difference' => $this->getFormattedBalanceDifference(),
  611. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  612. ],
  613. );
  614. }
  615. /**
  616. * @throws Exception
  617. */
  618. protected function buildDateRangeFilter(string $fieldPrefix, string $label, bool $hasBottomBorder = false): Tables\Filters\Filter
  619. {
  620. return Tables\Filters\Filter::make($fieldPrefix)
  621. ->columnSpanFull()
  622. ->form([
  623. Grid::make()
  624. ->live()
  625. ->schema([
  626. DateRangeSelect::make("{$fieldPrefix}_date_range")
  627. ->label($label)
  628. ->selectablePlaceholder(false)
  629. ->placeholder('Select a date range')
  630. ->startDateField("{$fieldPrefix}_start_date")
  631. ->endDateField("{$fieldPrefix}_end_date"),
  632. DatePicker::make("{$fieldPrefix}_start_date")
  633. ->label("{$label} from")
  634. ->columnStart(1)
  635. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  636. $set("{$fieldPrefix}_date_range", 'Custom');
  637. }),
  638. DatePicker::make("{$fieldPrefix}_end_date")
  639. ->label("{$label} to")
  640. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  641. $set("{$fieldPrefix}_date_range", 'Custom');
  642. }),
  643. ])
  644. ->extraAttributes($hasBottomBorder ? ['class' => 'border-b border-gray-200 dark:border-white/10 pb-8'] : []),
  645. ])
  646. ->query(function (Builder $query, array $data) use ($fieldPrefix): Builder {
  647. $query
  648. ->when($data["{$fieldPrefix}_start_date"], fn (Builder $query, $startDate) => $query->whereDate($fieldPrefix, '>=', $startDate))
  649. ->when($data["{$fieldPrefix}_end_date"], fn (Builder $query, $endDate) => $query->whereDate($fieldPrefix, '<=', $endDate));
  650. return $query;
  651. })
  652. ->indicateUsing(function (array $data) use ($fieldPrefix, $label): array {
  653. $indicators = [];
  654. $this->addIndicatorForDateRange($data, "{$fieldPrefix}_start_date", "{$fieldPrefix}_end_date", $label, $indicators);
  655. return $indicators;
  656. });
  657. }
  658. protected function addIndicatorForSingleSelection($data, $key, $label, &$indicators): void
  659. {
  660. if (filled($data[$key])) {
  661. $indicators[] = Tables\Filters\Indicator::make($label)
  662. ->removeField($key);
  663. }
  664. }
  665. protected function addMultipleSelectionIndicator($data, $key, callable $labelRetriever, $field, &$indicators): void
  666. {
  667. if (filled($data[$key])) {
  668. $labels = collect($data[$key])->map($labelRetriever);
  669. $additionalCount = $labels->count() - 1;
  670. $indicatorLabel = $additionalCount > 0 ? "{$labels->first()} + {$additionalCount}" : $labels->first();
  671. $indicators[] = Tables\Filters\Indicator::make($indicatorLabel)
  672. ->removeField($field);
  673. }
  674. }
  675. protected function addIndicatorForDateRange($data, $startKey, $endKey, $labelPrefix, &$indicators): void
  676. {
  677. $formattedStartDate = filled($data[$startKey]) ? Carbon::parse($data[$startKey])->toFormattedDateString() : null;
  678. $formattedEndDate = filled($data[$endKey]) ? Carbon::parse($data[$endKey])->toFormattedDateString() : null;
  679. if ($formattedStartDate && $formattedEndDate) {
  680. // 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
  681. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix}: {$formattedStartDate} - {$formattedEndDate}");
  682. } else {
  683. if ($formattedStartDate) {
  684. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} After: {$formattedStartDate}")
  685. ->removeField($startKey);
  686. }
  687. if ($formattedEndDate) {
  688. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} Before: {$formattedEndDate}")
  689. ->removeField($endKey);
  690. }
  691. }
  692. }
  693. protected static function determineTransactionState(Transaction $transaction, Tables\Actions\Action $action): string
  694. {
  695. if ($transaction->reviewed) {
  696. return 'reviewed';
  697. }
  698. if ($transaction->reviewed === false && $action->isEnabled()) {
  699. return 'unreviewed';
  700. }
  701. return 'uncategorized';
  702. }
  703. protected function getBankAccountOptions(?int $excludedAccountId = null, ?int $currentBankAccountId = null): array
  704. {
  705. return BankAccount::query()
  706. ->whereHas('account', function (Builder $query) {
  707. $query->where('archived', false);
  708. })
  709. ->with(['account' => function ($query) {
  710. $query->where('archived', false);
  711. }, 'account.subtype' => function ($query) {
  712. $query->select(['id', 'name']);
  713. }])
  714. ->when($excludedAccountId, fn (Builder $query) => $query->where('account_id', '!=', $excludedAccountId))
  715. ->when($currentBankAccountId, fn (Builder $query) => $query->orWhere('id', $currentBankAccountId))
  716. ->get()
  717. ->groupBy('account.subtype.name')
  718. ->map(fn (Collection $bankAccounts, string $subtype) => $bankAccounts->pluck('account.name', 'id'))
  719. ->toArray();
  720. }
  721. protected function getBankAccountAccountOptions(?int $excludedBankAccountId = null, ?int $currentAccountId = null): array
  722. {
  723. return Account::query()
  724. ->whereHas('bankAccount', function (Builder $query) use ($excludedBankAccountId) {
  725. // Exclude the specific bank account if provided
  726. if ($excludedBankAccountId) {
  727. $query->whereNot('id', $excludedBankAccountId);
  728. }
  729. })
  730. ->where(function (Builder $query) use ($currentAccountId) {
  731. $query->where('archived', false)
  732. ->orWhere('id', $currentAccountId);
  733. })
  734. ->get()
  735. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  736. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  737. ->toArray();
  738. }
  739. protected function getChartAccountOptions(?TransactionType $type = null, ?bool $nominalAccountsOnly = null, ?int $currentAccountId = null): array
  740. {
  741. $nominalAccountsOnly ??= false;
  742. $excludedCategory = match ($type) {
  743. TransactionType::Deposit => AccountCategory::Expense,
  744. TransactionType::Withdrawal => AccountCategory::Revenue,
  745. default => null,
  746. };
  747. return Account::query()
  748. ->when($nominalAccountsOnly, fn (Builder $query) => $query->doesntHave('bankAccount'))
  749. ->when($excludedCategory, fn (Builder $query) => $query->whereNot('category', $excludedCategory))
  750. ->where(function (Builder $query) use ($currentAccountId) {
  751. $query->where('archived', false)
  752. ->orWhere('id', $currentAccountId);
  753. })
  754. ->get()
  755. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  756. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  757. ->toArray();
  758. }
  759. protected function getBalanceForAllAccounts(): string
  760. {
  761. return Accounting::getTotalBalanceForAllBankAccounts($this->fiscalYearStartDate, $this->fiscalYearEndDate)->format();
  762. }
  763. }