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

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