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

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