You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Transactions.php 32KB

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