Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

Transactions.php 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864
  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\CustomTableRepeater;
  10. use App\Filament\Forms\Components\DateRangeSelect;
  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\Services\PlaidService;
  18. use App\Utilities\Currency\CurrencyAccessor;
  19. use App\Utilities\Currency\CurrencyConverter;
  20. use Awcodes\TableRepeater\Header;
  21. use Exception;
  22. use Filament\Actions;
  23. use Filament\Facades\Filament;
  24. use Filament\Forms;
  25. use Filament\Forms\Components\Actions\Action as FormAction;
  26. use Filament\Forms\Components\DatePicker;
  27. use Filament\Forms\Components\Grid;
  28. use Filament\Forms\Components\Select;
  29. use Filament\Forms\Components\Tabs;
  30. use Filament\Forms\Components\Tabs\Tab;
  31. use Filament\Forms\Components\Textarea;
  32. use Filament\Forms\Components\TextInput;
  33. use Filament\Forms\Form;
  34. use Filament\Forms\Get;
  35. use Filament\Forms\Set;
  36. use Filament\Pages\Page;
  37. use Filament\Support\Colors\Color;
  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 $navigationGroup = 'Accounting';
  61. public string $fiscalYearStartDate = '';
  62. public string $fiscalYearEndDate = '';
  63. public function mount(): void
  64. {
  65. /** @var Company $company */
  66. $company = Filament::getTenant();
  67. $this->fiscalYearStartDate = $company->locale->fiscalYearStartDate();
  68. $this->fiscalYearEndDate = $company->locale->fiscalYearEndDate();
  69. }
  70. public static function getModel(): string
  71. {
  72. return static::$model;
  73. }
  74. public static function getEloquentQuery(): Builder
  75. {
  76. return static::getModel()::query();
  77. }
  78. public function getMaxContentWidth(): MaxWidth | string | null
  79. {
  80. return 'max-w-8xl';
  81. }
  82. protected function getHeaderActions(): array
  83. {
  84. return [
  85. $this->buildTransactionAction('addIncome', 'Add income', TransactionType::Deposit),
  86. $this->buildTransactionAction('addExpense', 'Add expense', TransactionType::Withdrawal),
  87. Actions\CreateAction::make('addTransfer')
  88. ->label('Add transfer')
  89. ->modalHeading('Add Transfer')
  90. ->modalWidth(MaxWidth::ThreeExtraLarge)
  91. ->model(static::getModel())
  92. ->fillForm(fn (): array => $this->getFormDefaultsForType(TransactionType::Transfer))
  93. ->form(fn (Form $form) => $this->transferForm($form))
  94. ->button()
  95. ->outlined(),
  96. Actions\ActionGroup::make([
  97. Actions\CreateAction::make('addJournalTransaction')
  98. ->label('Add journal transaction')
  99. ->fillForm(fn (): array => $this->getFormDefaultsForType(TransactionType::Journal))
  100. ->modalWidth(MaxWidth::Screen)
  101. ->extraModalWindowAttributes([
  102. 'class' => 'journal-transaction-modal',
  103. ])
  104. ->model(static::getModel())
  105. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  106. ->modalSubmitAction(fn (Actions\StaticAction $action) => $action->disabled(! $this->isJournalEntryBalanced()))
  107. ->groupedIcon(null)
  108. ->modalHeading('Journal Entry')
  109. ->mutateFormDataUsing(static fn (array $data) => array_merge($data, ['type' => TransactionType::Journal]))
  110. ->afterFormFilled(fn () => $this->resetJournalEntryAmounts())
  111. ->after(fn (Transaction $transaction) => $transaction->updateAmountIfBalanced()),
  112. Actions\Action::make('connectBank')
  113. ->label('Connect your bank')
  114. ->visible(app(PlaidService::class)->isEnabled())
  115. ->url(ConnectedAccount::getUrl()),
  116. ])
  117. ->label('More')
  118. ->button()
  119. ->outlined()
  120. ->dropdownWidth('max-w-fit')
  121. ->dropdownPlacement('bottom-end')
  122. ->icon('heroicon-c-chevron-down')
  123. ->iconSize(IconSize::Small)
  124. ->iconPosition(IconPosition::After),
  125. ];
  126. }
  127. public function transferForm(Form $form): Form
  128. {
  129. return $form
  130. ->schema([
  131. Forms\Components\DatePicker::make('posted_at')
  132. ->label('Date')
  133. ->required(),
  134. Forms\Components\TextInput::make('description')
  135. ->label('Description'),
  136. Forms\Components\Select::make('bank_account_id')
  137. ->label('From account')
  138. ->options(fn (Get $get, ?Transaction $transaction) => $this->getBankAccountOptions(excludedAccountId: $get('account_id'), currentBankAccountId: $transaction?->bank_account_id))
  139. ->live()
  140. ->searchable()
  141. ->afterStateUpdated(function (Set $set, $state, $old, Get $get) {
  142. $amount = CurrencyConverter::convertAndSet(
  143. BankAccount::find($state)->account->currency_code,
  144. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  145. $get('amount')
  146. );
  147. if ($amount !== null) {
  148. $set('amount', $amount);
  149. }
  150. })
  151. ->required(),
  152. Forms\Components\Select::make('type')
  153. ->label('Type')
  154. ->options([
  155. TransactionType::Transfer->value => TransactionType::Transfer->getLabel(),
  156. ])
  157. ->disabled()
  158. ->dehydrated()
  159. ->required(),
  160. Forms\Components\TextInput::make('amount')
  161. ->label('Amount')
  162. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  163. ->required(),
  164. Forms\Components\Select::make('account_id')
  165. ->label('To account')
  166. ->live()
  167. ->options(fn (Get $get, ?Transaction $transaction) => $this->getBankAccountAccountOptions(excludedBankAccountId: $get('bank_account_id'), currentAccountId: $transaction?->account_id))
  168. ->searchable()
  169. ->required(),
  170. Forms\Components\Textarea::make('notes')
  171. ->label('Notes')
  172. ->autosize()
  173. ->rows(10)
  174. ->columnSpanFull(),
  175. ])
  176. ->columns();
  177. }
  178. public function transactionForm(Form $form): Form
  179. {
  180. return $form
  181. ->schema([
  182. Forms\Components\DatePicker::make('posted_at')
  183. ->label('Date')
  184. ->required(),
  185. Forms\Components\TextInput::make('description')
  186. ->label('Description'),
  187. Forms\Components\Select::make('bank_account_id')
  188. ->label('Account')
  189. ->options(fn (?Transaction $transaction) => $this->getBankAccountOptions(currentBankAccountId: $transaction?->bank_account_id))
  190. ->live()
  191. ->searchable()
  192. ->afterStateUpdated(function (Set $set, $state, $old, Get $get) {
  193. $amount = CurrencyConverter::convertAndSet(
  194. BankAccount::find($state)->account->currency_code,
  195. BankAccount::find($old)->account->currency_code ?? CurrencyAccessor::getDefaultCurrency(),
  196. $get('amount')
  197. );
  198. if ($amount !== null) {
  199. $set('amount', $amount);
  200. }
  201. })
  202. ->required(),
  203. Forms\Components\Select::make('type')
  204. ->label('Type')
  205. ->live()
  206. ->options([
  207. TransactionType::Deposit->value => TransactionType::Deposit->getLabel(),
  208. TransactionType::Withdrawal->value => TransactionType::Withdrawal->getLabel(),
  209. ])
  210. ->required()
  211. ->afterStateUpdated(static fn (Forms\Set $set, $state) => $set('account_id', static::getUncategorizedAccountByType(TransactionType::parse($state))?->id)),
  212. Forms\Components\TextInput::make('amount')
  213. ->label('Amount')
  214. ->money(static fn (Forms\Get $get) => BankAccount::find($get('bank_account_id'))?->account?->currency_code ?? CurrencyAccessor::getDefaultCurrency())
  215. ->required(),
  216. Forms\Components\Select::make('account_id')
  217. ->label('Category')
  218. ->options(fn (Forms\Get $get, ?Transaction $transaction) => $this->getChartAccountOptions(type: TransactionType::parse($get('type')), nominalAccountsOnly: true, currentAccountId: $transaction?->account_id))
  219. ->searchable()
  220. ->preload()
  221. ->required(),
  222. Forms\Components\Textarea::make('notes')
  223. ->label('Notes')
  224. ->autosize()
  225. ->rows(10)
  226. ->columnSpanFull(),
  227. ])
  228. ->columns();
  229. }
  230. public function journalTransactionForm(Form $form): Form
  231. {
  232. return $form
  233. ->schema([
  234. Tabs::make('Tabs')
  235. ->contained(false)
  236. ->tabs([
  237. $this->getJournalTransactionFormEditTab(),
  238. $this->getJournalTransactionFormNotesTab(),
  239. ]),
  240. ])
  241. ->columns(1);
  242. }
  243. /**
  244. * @throws Exception
  245. */
  246. public function table(Table $table): Table
  247. {
  248. return $table
  249. ->query(static::getEloquentQuery())
  250. ->modifyQueryUsing(function (Builder $query) {
  251. $query->with([
  252. 'account',
  253. 'bankAccount.account',
  254. 'journalEntries.account',
  255. ])
  256. ->where(function (Builder $query) {
  257. $query->whereNull('transactionable_id')
  258. ->orWhere('is_payment', true);
  259. });
  260. })
  261. ->columns([
  262. Tables\Columns\TextColumn::make('posted_at')
  263. ->label('Date')
  264. ->sortable()
  265. ->defaultDateFormat(),
  266. Tables\Columns\TextColumn::make('type')
  267. ->label('Type')
  268. ->sortable()
  269. ->toggleable(isToggledHiddenByDefault: true),
  270. Tables\Columns\TextColumn::make('description')
  271. ->label('Description')
  272. ->limit(50)
  273. ->toggleable(),
  274. Tables\Columns\TextColumn::make('bankAccount.account.name')
  275. ->label('Account')
  276. ->toggleable(),
  277. Tables\Columns\TextColumn::make('account.name')
  278. ->label('Category')
  279. ->prefix(static fn (Transaction $transaction) => $transaction->type->isTransfer() ? 'Transfer to ' : null)
  280. ->toggleable()
  281. ->state(static fn (Transaction $transaction) => $transaction->account->name ?? 'Journal Entry'),
  282. Tables\Columns\TextColumn::make('amount')
  283. ->label('Amount')
  284. ->weight(static fn (Transaction $transaction) => $transaction->reviewed ? null : FontWeight::SemiBold)
  285. ->color(
  286. static fn (Transaction $transaction) => match ($transaction->type) {
  287. TransactionType::Deposit => Color::rgb('rgb(' . Color::Green[700] . ')'),
  288. TransactionType::Journal => 'primary',
  289. default => null,
  290. }
  291. )
  292. ->sortable()
  293. ->currency(static fn (Transaction $transaction) => $transaction->bankAccount?->account->currency_code),
  294. ])
  295. ->recordClasses(static fn (Transaction $transaction) => $transaction->reviewed ? 'bg-primary-300/10' : null)
  296. ->defaultSort('posted_at', 'desc')
  297. ->filters([
  298. Tables\Filters\SelectFilter::make('bank_account_id')
  299. ->label('Account')
  300. ->searchable()
  301. ->options(fn () => $this->getBankAccountOptions(false)),
  302. Tables\Filters\SelectFilter::make('account_id')
  303. ->label('Category')
  304. ->multiple()
  305. ->options(fn () => $this->getChartAccountOptions(nominalAccountsOnly: false)),
  306. Tables\Filters\TernaryFilter::make('reviewed')
  307. ->label('Status')
  308. ->native(false)
  309. ->trueLabel('Reviewed')
  310. ->falseLabel('Not Reviewed'),
  311. Tables\Filters\SelectFilter::make('type')
  312. ->label('Type')
  313. ->native(false)
  314. ->options(TransactionType::class),
  315. $this->buildDateRangeFilter('posted_at', 'Posted', true),
  316. $this->buildDateRangeFilter('updated_at', 'Last modified'),
  317. ])
  318. ->filtersFormSchema(fn (array $filters): array => [
  319. Grid::make()
  320. ->schema([
  321. $filters['bank_account_id'],
  322. $filters['account_id'],
  323. $filters['reviewed'],
  324. $filters['type'],
  325. ])
  326. ->columnSpanFull()
  327. ->extraAttributes(['class' => 'border-b border-gray-200 dark:border-white/10 pb-8']),
  328. $filters['posted_at'],
  329. $filters['updated_at'],
  330. ])
  331. ->filtersFormWidth(MaxWidth::ThreeExtraLarge)
  332. ->actions([
  333. Tables\Actions\Action::make('markAsReviewed')
  334. ->label('Mark as reviewed')
  335. ->view('filament.company.components.tables.actions.mark-as-reviewed')
  336. ->icon(static fn (Transaction $transaction) => $transaction->reviewed ? 'heroicon-s-check-circle' : 'heroicon-o-check-circle')
  337. ->color(static fn (Transaction $transaction, Tables\Actions\Action $action) => match (static::determineTransactionState($transaction, $action)) {
  338. 'reviewed' => 'primary',
  339. 'unreviewed' => Color::rgb('rgb(' . Color::Gray[600] . ')'),
  340. 'uncategorized' => 'gray',
  341. })
  342. ->tooltip(static fn (Transaction $transaction, Tables\Actions\Action $action) => match (static::determineTransactionState($transaction, $action)) {
  343. 'reviewed' => 'Reviewed',
  344. 'unreviewed' => 'Mark as reviewed',
  345. 'uncategorized' => 'Categorize first to mark as reviewed',
  346. })
  347. ->disabled(fn (Transaction $transaction): bool => $transaction->isUncategorized())
  348. ->action(fn (Transaction $transaction) => $transaction->update(['reviewed' => ! $transaction->reviewed])),
  349. Tables\Actions\ActionGroup::make([
  350. Tables\Actions\ActionGroup::make([
  351. Tables\Actions\EditAction::make('editTransaction')
  352. ->label('Edit transaction')
  353. ->modalHeading('Edit Transaction')
  354. ->modalWidth(MaxWidth::ThreeExtraLarge)
  355. ->form(fn (Form $form) => $this->transactionForm($form))
  356. ->visible(static fn (Transaction $transaction) => $transaction->type->isStandard()),
  357. Tables\Actions\EditAction::make('editTransfer')
  358. ->label('Edit transfer')
  359. ->modalHeading('Edit Transfer')
  360. ->modalWidth(MaxWidth::ThreeExtraLarge)
  361. ->form(fn (Form $form) => $this->transferForm($form))
  362. ->visible(static fn (Transaction $transaction) => $transaction->type->isTransfer()),
  363. Tables\Actions\EditAction::make('editJournalTransaction')
  364. ->label('Edit journal transaction')
  365. ->modalHeading('Journal Entry')
  366. ->modalWidth(MaxWidth::Screen)
  367. ->extraModalWindowAttributes([
  368. 'class' => 'journal-transaction-modal',
  369. ])
  370. ->form(fn (Form $form) => $this->journalTransactionForm($form))
  371. ->afterFormFilled(function (Transaction $transaction) {
  372. $debitAmounts = $transaction->journalEntries->sumDebits()->getAmount();
  373. $creditAmounts = $transaction->journalEntries->sumCredits()->getAmount();
  374. $this->setDebitAmount($debitAmounts);
  375. $this->setCreditAmount($creditAmounts);
  376. })
  377. ->modalSubmitAction(fn (Actions\StaticAction $action) => $action->disabled(! $this->isJournalEntryBalanced()))
  378. ->after(fn (Transaction $transaction) => $transaction->updateAmountIfBalanced())
  379. ->visible(static fn (Transaction $transaction) => $transaction->type->isJournal()),
  380. Tables\Actions\ReplicateAction::make()
  381. ->excludeAttributes(['created_by', 'updated_by', 'created_at', 'updated_at'])
  382. ->modal(false)
  383. ->beforeReplicaSaved(static function (Transaction $replica) {
  384. $replica->description = '(Copy of) ' . $replica->description;
  385. })
  386. ->after(static function (Transaction $original, Transaction $replica) {
  387. $original->journalEntries->each(function (JournalEntry $entry) use ($replica) {
  388. $entry->replicate([
  389. 'transaction_id',
  390. ])->fill([
  391. 'transaction_id' => $replica->id,
  392. ])->save();
  393. });
  394. }),
  395. ])->dropdown(false),
  396. Tables\Actions\DeleteAction::make(),
  397. ]),
  398. ])
  399. ->bulkActions([
  400. Tables\Actions\BulkActionGroup::make([
  401. Tables\Actions\DeleteBulkAction::make(),
  402. ReplicateBulkAction::make()
  403. ->label('Replicate')
  404. ->modalWidth(MaxWidth::Large)
  405. ->modalDescription('Replicating transactions will also replicate their journal entries. Are you sure you want to proceed?')
  406. ->successNotificationTitle('Transactions replicated successfully')
  407. ->failureNotificationTitle('Failed to replicate transactions')
  408. ->deselectRecordsAfterCompletion()
  409. ->excludeAttributes(['created_by', 'updated_by', 'created_at', 'updated_at'])
  410. ->beforeReplicaSaved(static function (Transaction $replica) {
  411. $replica->description = '(Copy of) ' . $replica->description;
  412. })
  413. ->withReplicatedRelationships(['journalEntries']),
  414. ]),
  415. ]);
  416. }
  417. protected function buildTransactionAction(string $name, string $label, TransactionType $type): Actions\CreateAction
  418. {
  419. return Actions\CreateAction::make($name)
  420. ->label($label)
  421. ->modalWidth(MaxWidth::ThreeExtraLarge)
  422. ->model(static::getModel())
  423. ->fillForm(fn (): array => $this->getFormDefaultsForType($type))
  424. ->form(fn (Form $form) => $this->transactionForm($form))
  425. ->button()
  426. ->outlined();
  427. }
  428. protected function getFormDefaultsForType(TransactionType $type): array
  429. {
  430. $commonDefaults = [
  431. 'posted_at' => today(),
  432. ];
  433. return match ($type) {
  434. TransactionType::Deposit, TransactionType::Withdrawal, TransactionType::Transfer => array_merge($commonDefaults, $this->transactionDefaults($type)),
  435. TransactionType::Journal => array_merge($commonDefaults, $this->journalEntryDefaults()),
  436. };
  437. }
  438. protected function journalEntryDefaults(): array
  439. {
  440. return [
  441. 'journalEntries' => [
  442. $this->defaultEntry(JournalEntryType::Debit),
  443. $this->defaultEntry(JournalEntryType::Credit),
  444. ],
  445. ];
  446. }
  447. protected function defaultEntry(JournalEntryType $journalEntryType): array
  448. {
  449. return [
  450. 'type' => $journalEntryType,
  451. 'account_id' => static::getUncategorizedAccountByType($journalEntryType->isDebit() ? TransactionType::Withdrawal : TransactionType::Deposit)?->id,
  452. 'amount' => '0.00',
  453. ];
  454. }
  455. protected function transactionDefaults(TransactionType $type): array
  456. {
  457. return [
  458. 'type' => $type,
  459. 'bank_account_id' => BankAccount::where('enabled', true)->first()?->id,
  460. 'amount' => '0.00',
  461. 'account_id' => ! $type->isTransfer() ? static::getUncategorizedAccountByType($type)->id : null,
  462. ];
  463. }
  464. public static function getUncategorizedAccountByType(TransactionType $type): ?Account
  465. {
  466. [$category, $accountName] = match ($type) {
  467. TransactionType::Deposit => [AccountCategory::Revenue, 'Uncategorized Income'],
  468. TransactionType::Withdrawal => [AccountCategory::Expense, 'Uncategorized Expense'],
  469. default => [null, null],
  470. };
  471. return Account::where('category', $category)
  472. ->where('name', $accountName)
  473. ->first();
  474. }
  475. protected function getJournalTransactionFormEditTab(): Tab
  476. {
  477. return Tab::make('Edit')
  478. ->label('Edit')
  479. ->icon('heroicon-o-pencil-square')
  480. ->schema([
  481. $this->getTransactionDetailsGrid(),
  482. $this->getJournalEntriesTableRepeater(),
  483. ]);
  484. }
  485. protected function getJournalTransactionFormNotesTab(): Tab
  486. {
  487. return Tab::make('Notes')
  488. ->label('Notes')
  489. ->icon('heroicon-o-clipboard')
  490. ->id('notes')
  491. ->schema([
  492. $this->getTransactionDetailsGrid(),
  493. Textarea::make('notes')
  494. ->label('Notes')
  495. ->rows(10)
  496. ->autosize(),
  497. ]);
  498. }
  499. protected function getTransactionDetailsGrid(): Grid
  500. {
  501. return Grid::make(8)
  502. ->schema([
  503. DatePicker::make('posted_at')
  504. ->label('Date')
  505. ->softRequired()
  506. ->displayFormat('Y-m-d'),
  507. TextInput::make('description')
  508. ->label('Description')
  509. ->columnSpan(2),
  510. ]);
  511. }
  512. protected function getJournalEntriesTableRepeater(): CustomTableRepeater
  513. {
  514. return CustomTableRepeater::make('journalEntries')
  515. ->relationship('journalEntries')
  516. ->hiddenLabel()
  517. ->columns(4)
  518. ->headers($this->getJournalEntriesTableRepeaterHeaders())
  519. ->schema($this->getJournalEntriesTableRepeaterSchema())
  520. ->deletable(fn (CustomTableRepeater $repeater) => $repeater->getItemsCount() > 2)
  521. ->deleteAction(function (Forms\Components\Actions\Action $action) {
  522. return $action
  523. ->action(function (array $arguments, CustomTableRepeater $component): void {
  524. $items = $component->getState();
  525. $amount = $items[$arguments['item']]['amount'];
  526. $type = $items[$arguments['item']]['type'];
  527. $this->updateJournalEntryAmount(JournalEntryType::parse($type), '0.00', $amount);
  528. unset($items[$arguments['item']]);
  529. $component->state($items);
  530. $component->callAfterStateUpdated();
  531. });
  532. })
  533. ->rules([
  534. function () {
  535. return function (string $attribute, $value, \Closure $fail) {
  536. if (empty($value) || ! is_array($value)) {
  537. $fail('Journal entries are required.');
  538. return;
  539. }
  540. $hasDebit = false;
  541. $hasCredit = false;
  542. foreach ($value as $entry) {
  543. if (! isset($entry['type'])) {
  544. continue;
  545. }
  546. if (JournalEntryType::parse($entry['type'])->isDebit()) {
  547. $hasDebit = true;
  548. } elseif (JournalEntryType::parse($entry['type'])->isCredit()) {
  549. $hasCredit = true;
  550. }
  551. if ($hasDebit && $hasCredit) {
  552. break;
  553. }
  554. }
  555. if (! $hasDebit) {
  556. $fail('At least one debit entry is required.');
  557. }
  558. if (! $hasCredit) {
  559. $fail('At least one credit entry is required.');
  560. }
  561. };
  562. },
  563. ])
  564. ->minItems(2)
  565. ->defaultItems(2)
  566. ->addable(false)
  567. ->footerItem(fn (): View => $this->getJournalTransactionModalFooter())
  568. ->extraActions([
  569. $this->buildAddJournalEntryAction(JournalEntryType::Debit),
  570. $this->buildAddJournalEntryAction(JournalEntryType::Credit),
  571. ]);
  572. }
  573. protected function getJournalEntriesTableRepeaterHeaders(): array
  574. {
  575. return [
  576. Header::make('type')
  577. ->width('150px')
  578. ->label('Type'),
  579. Header::make('description')
  580. ->width('320px')
  581. ->label('Description'),
  582. Header::make('account_id')
  583. ->width('320px')
  584. ->label('Account'),
  585. Header::make('amount')
  586. ->width('192px')
  587. ->label('Amount'),
  588. ];
  589. }
  590. protected function getJournalEntriesTableRepeaterSchema(): array
  591. {
  592. return [
  593. Select::make('type')
  594. ->label('Type')
  595. ->options(JournalEntryType::class)
  596. ->live()
  597. ->afterStateUpdated(function (Get $get, Set $set, $state, $old) {
  598. $this->adjustJournalEntryAmountsForTypeChange(JournalEntryType::parse($state), JournalEntryType::parse($old), $get('amount'));
  599. })
  600. ->softRequired(),
  601. TextInput::make('description')
  602. ->label('Description'),
  603. Select::make('account_id')
  604. ->label('Account')
  605. ->options(fn (?JournalEntry $journalEntry): array => $this->getChartAccountOptions(currentAccountId: $journalEntry?->account_id))
  606. ->live()
  607. ->softRequired()
  608. ->searchable(),
  609. TextInput::make('amount')
  610. ->label('Amount')
  611. ->live()
  612. ->mask(moneyMask(CurrencyAccessor::getDefaultCurrency()))
  613. ->afterStateUpdated(function (Get $get, Set $set, ?string $state, ?string $old) {
  614. $this->updateJournalEntryAmount(JournalEntryType::parse($get('type')), $state, $old);
  615. })
  616. ->softRequired(),
  617. ];
  618. }
  619. protected function buildAddJournalEntryAction(JournalEntryType $type): FormAction
  620. {
  621. $typeLabel = $type->getLabel();
  622. return FormAction::make("add{$typeLabel}Entry")
  623. ->label("Add {$typeLabel} entry")
  624. ->button()
  625. ->outlined()
  626. ->color($type->isDebit() ? 'primary' : 'gray')
  627. ->iconSize(IconSize::Small)
  628. ->iconPosition(IconPosition::Before)
  629. ->action(function (CustomTableRepeater $component) use ($type) {
  630. $state = $component->getState();
  631. $newUuid = (string) Str::uuid();
  632. $state[$newUuid] = $this->defaultEntry($type);
  633. $component->state($state);
  634. });
  635. }
  636. public function getJournalTransactionModalFooter(): View
  637. {
  638. return view(
  639. 'filament.company.components.actions.journal-entry-footer',
  640. [
  641. 'debitAmount' => $this->getFormattedDebitAmount(),
  642. 'creditAmount' => $this->getFormattedCreditAmount(),
  643. 'difference' => $this->getFormattedBalanceDifference(),
  644. 'isJournalBalanced' => $this->isJournalEntryBalanced(),
  645. ],
  646. );
  647. }
  648. /**
  649. * @throws Exception
  650. */
  651. protected function buildDateRangeFilter(string $fieldPrefix, string $label, bool $hasBottomBorder = false): Tables\Filters\Filter
  652. {
  653. return Tables\Filters\Filter::make($fieldPrefix)
  654. ->columnSpanFull()
  655. ->form([
  656. Grid::make()
  657. ->live()
  658. ->schema([
  659. DateRangeSelect::make("{$fieldPrefix}_date_range")
  660. ->label($label)
  661. ->selectablePlaceholder(false)
  662. ->placeholder('Select a date range')
  663. ->startDateField("{$fieldPrefix}_start_date")
  664. ->endDateField("{$fieldPrefix}_end_date"),
  665. DatePicker::make("{$fieldPrefix}_start_date")
  666. ->label("{$label} from")
  667. ->columnStart(1)
  668. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  669. $set("{$fieldPrefix}_date_range", 'Custom');
  670. }),
  671. DatePicker::make("{$fieldPrefix}_end_date")
  672. ->label("{$label} to")
  673. ->afterStateUpdated(static function (Set $set) use ($fieldPrefix) {
  674. $set("{$fieldPrefix}_date_range", 'Custom');
  675. }),
  676. ])
  677. ->extraAttributes($hasBottomBorder ? ['class' => 'border-b border-gray-200 dark:border-white/10 pb-8'] : []),
  678. ])
  679. ->query(function (Builder $query, array $data) use ($fieldPrefix): Builder {
  680. $query
  681. ->when($data["{$fieldPrefix}_start_date"], fn (Builder $query, $startDate) => $query->whereDate($fieldPrefix, '>=', $startDate))
  682. ->when($data["{$fieldPrefix}_end_date"], fn (Builder $query, $endDate) => $query->whereDate($fieldPrefix, '<=', $endDate));
  683. return $query;
  684. })
  685. ->indicateUsing(function (array $data) use ($fieldPrefix, $label): array {
  686. $indicators = [];
  687. $this->addIndicatorForDateRange($data, "{$fieldPrefix}_start_date", "{$fieldPrefix}_end_date", $label, $indicators);
  688. return $indicators;
  689. });
  690. }
  691. protected function addIndicatorForSingleSelection($data, $key, $label, &$indicators): void
  692. {
  693. if (filled($data[$key])) {
  694. $indicators[] = Tables\Filters\Indicator::make($label)
  695. ->removeField($key);
  696. }
  697. }
  698. protected function addMultipleSelectionIndicator($data, $key, callable $labelRetriever, $field, &$indicators): void
  699. {
  700. if (filled($data[$key])) {
  701. $labels = collect($data[$key])->map($labelRetriever);
  702. $additionalCount = $labels->count() - 1;
  703. $indicatorLabel = $additionalCount > 0 ? "{$labels->first()} + {$additionalCount}" : $labels->first();
  704. $indicators[] = Tables\Filters\Indicator::make($indicatorLabel)
  705. ->removeField($field);
  706. }
  707. }
  708. protected function addIndicatorForDateRange($data, $startKey, $endKey, $labelPrefix, &$indicators): void
  709. {
  710. $formattedStartDate = filled($data[$startKey]) ? Carbon::parse($data[$startKey])->toFormattedDateString() : null;
  711. $formattedEndDate = filled($data[$endKey]) ? Carbon::parse($data[$endKey])->toFormattedDateString() : null;
  712. if ($formattedStartDate && $formattedEndDate) {
  713. // 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
  714. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix}: {$formattedStartDate} - {$formattedEndDate}");
  715. } else {
  716. if ($formattedStartDate) {
  717. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} After: {$formattedStartDate}")
  718. ->removeField($startKey);
  719. }
  720. if ($formattedEndDate) {
  721. $indicators[] = Tables\Filters\Indicator::make("{$labelPrefix} Before: {$formattedEndDate}")
  722. ->removeField($endKey);
  723. }
  724. }
  725. }
  726. protected static function determineTransactionState(Transaction $transaction, Tables\Actions\Action $action): string
  727. {
  728. if ($transaction->reviewed) {
  729. return 'reviewed';
  730. }
  731. if ($transaction->reviewed === false && $action->isEnabled()) {
  732. return 'unreviewed';
  733. }
  734. return 'uncategorized';
  735. }
  736. protected function getBankAccountOptions(?int $excludedAccountId = null, ?int $currentBankAccountId = null): array
  737. {
  738. return BankAccount::query()
  739. ->whereHas('account', function (Builder $query) {
  740. $query->where('archived', false);
  741. })
  742. ->with(['account' => function ($query) {
  743. $query->where('archived', false);
  744. }, 'account.subtype' => function ($query) {
  745. $query->select(['id', 'name']);
  746. }])
  747. ->when($excludedAccountId, fn (Builder $query) => $query->where('account_id', '!=', $excludedAccountId))
  748. ->when($currentBankAccountId, fn (Builder $query) => $query->orWhere('id', $currentBankAccountId))
  749. ->get()
  750. ->groupBy('account.subtype.name')
  751. ->map(fn (Collection $bankAccounts, string $subtype) => $bankAccounts->pluck('account.name', 'id'))
  752. ->toArray();
  753. }
  754. protected function getBankAccountAccountOptions(?int $excludedBankAccountId = null, ?int $currentAccountId = null): array
  755. {
  756. return Account::query()
  757. ->whereHas('bankAccount', function (Builder $query) use ($excludedBankAccountId) {
  758. // Exclude the specific bank account if provided
  759. if ($excludedBankAccountId) {
  760. $query->whereNot('id', $excludedBankAccountId);
  761. }
  762. })
  763. ->where(function (Builder $query) use ($currentAccountId) {
  764. $query->where('archived', false)
  765. ->orWhere('id', $currentAccountId);
  766. })
  767. ->get()
  768. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  769. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  770. ->toArray();
  771. }
  772. protected function getChartAccountOptions(?TransactionType $type = null, ?bool $nominalAccountsOnly = null, ?int $currentAccountId = null): array
  773. {
  774. $nominalAccountsOnly ??= false;
  775. $excludedCategory = match ($type) {
  776. TransactionType::Deposit => AccountCategory::Expense,
  777. TransactionType::Withdrawal => AccountCategory::Revenue,
  778. default => null,
  779. };
  780. return Account::query()
  781. ->when($nominalAccountsOnly, fn (Builder $query) => $query->doesntHave('bankAccount'))
  782. ->when($excludedCategory, fn (Builder $query) => $query->whereNot('category', $excludedCategory))
  783. ->where(function (Builder $query) use ($currentAccountId) {
  784. $query->where('archived', false)
  785. ->orWhere('id', $currentAccountId);
  786. })
  787. ->get()
  788. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  789. ->map(fn (Collection $accounts, string $category) => $accounts->pluck('name', 'id'))
  790. ->toArray();
  791. }
  792. protected function getBalanceForAllAccounts(): string
  793. {
  794. return Accounting::getTotalBalanceForAllBankAccounts($this->fiscalYearStartDate, $this->fiscalYearEndDate)->format();
  795. }
  796. }