Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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