您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Transactions.php 33KB

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