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

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