Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

Transactions.php 32KB

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