Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Transactions.php 35KB

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