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

Transactions.php 36KB

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