Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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