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

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