You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

InvoiceResource.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Collections\Accounting\DocumentCollection;
  4. use App\Enums\Accounting\DocumentDiscountMethod;
  5. use App\Enums\Accounting\DocumentType;
  6. use App\Enums\Accounting\InvoiceStatus;
  7. use App\Enums\Accounting\PaymentMethod;
  8. use App\Filament\Company\Resources\Sales\ClientResource\RelationManagers\InvoicesRelationManager;
  9. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  10. use App\Filament\Company\Resources\Sales\InvoiceResource\RelationManagers;
  11. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  12. use App\Filament\Forms\Components\CreateCurrencySelect;
  13. use App\Filament\Forms\Components\DocumentFooterSection;
  14. use App\Filament\Forms\Components\DocumentHeaderSection;
  15. use App\Filament\Forms\Components\DocumentTotals;
  16. use App\Filament\Tables\Actions\ReplicateBulkAction;
  17. use App\Filament\Tables\Columns;
  18. use App\Filament\Tables\Filters\DateRangeFilter;
  19. use App\Models\Accounting\Adjustment;
  20. use App\Models\Accounting\Invoice;
  21. use App\Models\Banking\BankAccount;
  22. use App\Models\Common\Client;
  23. use App\Models\Common\Offering;
  24. use App\Utilities\Currency\CurrencyAccessor;
  25. use App\Utilities\Currency\CurrencyConverter;
  26. use App\Utilities\RateCalculator;
  27. use Awcodes\TableRepeater\Components\TableRepeater;
  28. use Awcodes\TableRepeater\Header;
  29. use Closure;
  30. use Filament\Forms;
  31. use Filament\Forms\Form;
  32. use Filament\Notifications\Notification;
  33. use Filament\Resources\Resource;
  34. use Filament\Support\Enums\Alignment;
  35. use Filament\Support\Enums\MaxWidth;
  36. use Filament\Tables;
  37. use Filament\Tables\Table;
  38. use Illuminate\Database\Eloquent\Builder;
  39. use Illuminate\Database\Eloquent\Collection;
  40. use Illuminate\Support\Facades\Auth;
  41. class InvoiceResource extends Resource
  42. {
  43. protected static ?string $model = Invoice::class;
  44. public static function form(Form $form): Form
  45. {
  46. $company = Auth::user()->currentCompany;
  47. $settings = $company->defaultInvoice;
  48. return $form
  49. ->schema([
  50. DocumentHeaderSection::make('Invoice Header')
  51. ->defaultHeader($settings->header)
  52. ->defaultSubheader($settings->subheader),
  53. Forms\Components\Section::make('Invoice Details')
  54. ->schema([
  55. Forms\Components\Split::make([
  56. Forms\Components\Group::make([
  57. Forms\Components\Select::make('client_id')
  58. ->relationship('client', 'name')
  59. ->preload()
  60. ->searchable()
  61. ->required()
  62. ->live()
  63. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  64. if (! $state) {
  65. return;
  66. }
  67. $currencyCode = Client::find($state)?->currency_code;
  68. if ($currencyCode) {
  69. $set('currency_code', $currencyCode);
  70. }
  71. }),
  72. CreateCurrencySelect::make('currency_code')
  73. ->disabled(function (?Invoice $record) {
  74. return $record?->hasPayments();
  75. }),
  76. ]),
  77. Forms\Components\Group::make([
  78. Forms\Components\TextInput::make('invoice_number')
  79. ->label('Invoice number')
  80. ->default(static fn () => Invoice::getNextDocumentNumber()),
  81. Forms\Components\TextInput::make('order_number')
  82. ->label('P.O/S.O Number'),
  83. Forms\Components\DatePicker::make('date')
  84. ->label('Invoice date')
  85. ->live()
  86. ->default(now())
  87. ->disabled(function (?Invoice $record) {
  88. return $record?->hasPayments();
  89. })
  90. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  91. $date = $state;
  92. $dueDate = $get('due_date');
  93. if ($date && $dueDate && $date > $dueDate) {
  94. $set('due_date', $date);
  95. }
  96. }),
  97. Forms\Components\DatePicker::make('due_date')
  98. ->label('Payment due')
  99. ->default(function () use ($settings) {
  100. return now()->addDays($settings->payment_terms->getDays());
  101. })
  102. ->minDate(static function (Forms\Get $get) {
  103. return $get('date') ?? now();
  104. }),
  105. Forms\Components\Select::make('discount_method')
  106. ->label('Discount method')
  107. ->options(DocumentDiscountMethod::class)
  108. ->selectablePlaceholder(false)
  109. ->default(DocumentDiscountMethod::PerLineItem)
  110. ->afterStateUpdated(function ($state, Forms\Set $set) {
  111. $discountMethod = DocumentDiscountMethod::parse($state);
  112. if ($discountMethod->isPerDocument()) {
  113. $set('lineItems.*.salesDiscounts', []);
  114. }
  115. })
  116. ->live(),
  117. ])->grow(true),
  118. ])->from('md'),
  119. TableRepeater::make('lineItems')
  120. ->relationship()
  121. ->saveRelationshipsUsing(null)
  122. ->dehydrated(true)
  123. ->headers(function (Forms\Get $get) use ($settings) {
  124. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  125. $headers = [
  126. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  127. ->width($hasDiscounts ? '15%' : '20%'),
  128. Header::make('Description')
  129. ->width($hasDiscounts ? '25%' : '30%'),
  130. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  131. ->width('10%'),
  132. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  133. ->width('10%'),
  134. Header::make('Taxes')
  135. ->width($hasDiscounts ? '15%' : '20%'),
  136. ];
  137. if ($hasDiscounts) {
  138. $headers[] = Header::make('Discounts')->width('15%');
  139. }
  140. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  141. ->width('10%')
  142. ->align('right');
  143. return $headers;
  144. })
  145. ->schema([
  146. Forms\Components\Select::make('offering_id')
  147. ->relationship('sellableOffering', 'name')
  148. ->preload()
  149. ->searchable()
  150. ->required()
  151. ->live()
  152. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  153. $offeringId = $state;
  154. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  155. if (! $offeringRecord) {
  156. return;
  157. }
  158. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  159. $set('description', $offeringRecord->description);
  160. $set('unit_price', $unitPrice);
  161. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  162. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  163. if ($discountMethod->isPerLineItem()) {
  164. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  165. }
  166. }),
  167. Forms\Components\TextInput::make('description'),
  168. Forms\Components\TextInput::make('quantity')
  169. ->required()
  170. ->numeric()
  171. ->live()
  172. ->maxValue(9999999999.99)
  173. ->default(1),
  174. Forms\Components\TextInput::make('unit_price')
  175. ->hiddenLabel()
  176. ->numeric()
  177. ->live()
  178. ->maxValue(9999999999.99)
  179. ->default(0),
  180. Forms\Components\Select::make('salesTaxes')
  181. ->relationship('salesTaxes', 'name')
  182. ->saveRelationshipsUsing(null)
  183. ->dehydrated(true)
  184. ->preload()
  185. ->multiple()
  186. ->live()
  187. ->searchable(),
  188. Forms\Components\Select::make('salesDiscounts')
  189. ->relationship('salesDiscounts', 'name')
  190. ->saveRelationshipsUsing(null)
  191. ->dehydrated(true)
  192. ->preload()
  193. ->multiple()
  194. ->live()
  195. ->hidden(function (Forms\Get $get) {
  196. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  197. return $discountMethod->isPerDocument();
  198. })
  199. ->searchable(),
  200. Forms\Components\Placeholder::make('total')
  201. ->hiddenLabel()
  202. ->extraAttributes(['class' => 'text-left sm:text-right'])
  203. ->content(function (Forms\Get $get) {
  204. $quantity = max((float) ($get('quantity') ?? 0), 0);
  205. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  206. $salesTaxes = $get('salesTaxes') ?? [];
  207. $salesDiscounts = $get('salesDiscounts') ?? [];
  208. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  209. $subtotal = $quantity * $unitPrice;
  210. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  211. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  212. ->get()
  213. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  214. if ($adjustment->computation->isPercentage()) {
  215. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  216. } else {
  217. return $adjustment->getRawOriginal('rate');
  218. }
  219. });
  220. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  221. ->get()
  222. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  223. if ($adjustment->computation->isPercentage()) {
  224. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  225. } else {
  226. return $adjustment->getRawOriginal('rate');
  227. }
  228. });
  229. // Final total
  230. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  231. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  232. }),
  233. ]),
  234. DocumentTotals::make()
  235. ->type(DocumentType::Invoice),
  236. Forms\Components\Textarea::make('terms')
  237. ->default($settings->terms)
  238. ->columnSpanFull(),
  239. ]),
  240. DocumentFooterSection::make('Invoice Footer')
  241. ->defaultFooter($settings->footer),
  242. ]);
  243. }
  244. public static function table(Table $table): Table
  245. {
  246. return $table
  247. ->defaultSort('due_date')
  248. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  249. if (property_exists($livewire, 'recurringInvoice')) {
  250. $recurringInvoiceId = $livewire->recurringInvoice;
  251. if (! empty($recurringInvoiceId)) {
  252. $query->where('recurring_invoice_id', $recurringInvoiceId);
  253. }
  254. }
  255. return $query;
  256. })
  257. ->columns([
  258. Columns::id(),
  259. Tables\Columns\TextColumn::make('status')
  260. ->badge()
  261. ->searchable(),
  262. Tables\Columns\TextColumn::make('due_date')
  263. ->label('Due')
  264. ->asRelativeDay()
  265. ->sortable()
  266. ->hideOnTabs(['draft']),
  267. Tables\Columns\TextColumn::make('date')
  268. ->date()
  269. ->sortable(),
  270. Tables\Columns\TextColumn::make('invoice_number')
  271. ->label('Number')
  272. ->searchable()
  273. ->description(function (Invoice $record) {
  274. return $record->source_type?->getLabel();
  275. })
  276. ->sortable(),
  277. Tables\Columns\TextColumn::make('client.name')
  278. ->sortable()
  279. ->searchable()
  280. ->hiddenOn(InvoicesRelationManager::class),
  281. Tables\Columns\TextColumn::make('total')
  282. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  283. ->sortable()
  284. ->toggleable()
  285. ->alignEnd(),
  286. Tables\Columns\TextColumn::make('amount_paid')
  287. ->label('Amount paid')
  288. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  289. ->sortable()
  290. ->alignEnd()
  291. ->showOnTabs(['unpaid']),
  292. Tables\Columns\TextColumn::make('amount_due')
  293. ->label('Amount due')
  294. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  295. ->sortable()
  296. ->alignEnd()
  297. ->hideOnTabs(['draft']),
  298. ])
  299. ->filters([
  300. Tables\Filters\SelectFilter::make('client')
  301. ->relationship('client', 'name')
  302. ->searchable()
  303. ->preload()
  304. ->hiddenOn(InvoicesRelationManager::class),
  305. Tables\Filters\SelectFilter::make('status')
  306. ->options(InvoiceStatus::class)
  307. ->multiple(),
  308. Tables\Filters\TernaryFilter::make('has_payments')
  309. ->label('Has payments')
  310. ->queries(
  311. true: fn (Builder $query) => $query->whereHas('payments'),
  312. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  313. ),
  314. Tables\Filters\SelectFilter::make('source_type')
  315. ->label('Source type')
  316. ->options([
  317. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  318. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  319. ])
  320. ->native(false)
  321. ->query(function (Builder $query, array $data) {
  322. $sourceType = $data['value'] ?? null;
  323. return match ($sourceType) {
  324. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  325. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  326. default => $query,
  327. };
  328. }),
  329. DateRangeFilter::make('date')
  330. ->fromLabel('From date')
  331. ->untilLabel('To date')
  332. ->indicatorLabel('Date'),
  333. DateRangeFilter::make('due_date')
  334. ->fromLabel('From due date')
  335. ->untilLabel('To due date')
  336. ->indicatorLabel('Due'),
  337. ])
  338. ->actions([
  339. Tables\Actions\ActionGroup::make([
  340. Tables\Actions\ActionGroup::make([
  341. Tables\Actions\EditAction::make()
  342. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  343. Tables\Actions\ViewAction::make()
  344. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  345. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  346. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  347. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  348. Tables\Actions\Action::make('recordPayment')
  349. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  350. ->stickyModalHeader()
  351. ->stickyModalFooter()
  352. ->modalFooterActionsAlignment(Alignment::End)
  353. ->modalWidth(MaxWidth::TwoExtraLarge)
  354. ->icon('heroicon-o-credit-card')
  355. ->visible(function (Invoice $record) {
  356. return $record->canRecordPayment();
  357. })
  358. ->mountUsing(function (Invoice $record, Form $form) {
  359. $form->fill([
  360. 'posted_at' => now(),
  361. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  362. ]);
  363. })
  364. ->databaseTransaction()
  365. ->successNotificationTitle('Payment recorded')
  366. ->form([
  367. Forms\Components\DatePicker::make('posted_at')
  368. ->label('Date'),
  369. Forms\Components\TextInput::make('amount')
  370. ->label('Amount')
  371. ->required()
  372. ->money(fn (Invoice $record) => $record->currency_code)
  373. ->live(onBlur: true)
  374. ->helperText(function (Invoice $record, $state) {
  375. $invoiceCurrency = $record->currency_code;
  376. if (! CurrencyConverter::isValidAmount($state, $invoiceCurrency)) {
  377. return null;
  378. }
  379. $amountDue = $record->getRawOriginal('amount_due');
  380. $amount = CurrencyConverter::convertToCents($state, $invoiceCurrency);
  381. if ($amount <= 0) {
  382. return 'Please enter a valid positive amount';
  383. }
  384. if ($record->status === InvoiceStatus::Overpaid) {
  385. $newAmountDue = $amountDue + $amount;
  386. } else {
  387. $newAmountDue = $amountDue - $amount;
  388. }
  389. return match (true) {
  390. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  391. $newAmountDue === 0 => 'Invoice will be fully paid',
  392. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  393. };
  394. })
  395. ->rules([
  396. static fn (Invoice $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  397. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  398. $fail('Please enter a valid amount');
  399. }
  400. },
  401. ]),
  402. Forms\Components\Select::make('payment_method')
  403. ->label('Payment method')
  404. ->required()
  405. ->options(PaymentMethod::class),
  406. Forms\Components\Select::make('bank_account_id')
  407. ->label('Account')
  408. ->required()
  409. ->options(BankAccount::query()
  410. ->get()
  411. ->pluck('account.name', 'id'))
  412. ->searchable(),
  413. Forms\Components\Textarea::make('notes')
  414. ->label('Notes'),
  415. ])
  416. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  417. $record->recordPayment($data);
  418. $action->success();
  419. }),
  420. ])->dropdown(false),
  421. Tables\Actions\DeleteAction::make(),
  422. ]),
  423. ])
  424. ->bulkActions([
  425. Tables\Actions\BulkActionGroup::make([
  426. Tables\Actions\DeleteBulkAction::make(),
  427. ReplicateBulkAction::make()
  428. ->label('Replicate')
  429. ->modalWidth(MaxWidth::Large)
  430. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  431. ->successNotificationTitle('Invoices replicated successfully')
  432. ->failureNotificationTitle('Failed to replicate invoices')
  433. ->databaseTransaction()
  434. ->deselectRecordsAfterCompletion()
  435. ->excludeAttributes([
  436. 'status',
  437. 'amount_paid',
  438. 'amount_due',
  439. 'created_by',
  440. 'updated_by',
  441. 'created_at',
  442. 'updated_at',
  443. 'invoice_number',
  444. 'date',
  445. 'due_date',
  446. 'approved_at',
  447. 'paid_at',
  448. 'last_sent_at',
  449. 'last_viewed_at',
  450. ])
  451. ->beforeReplicaSaved(function (Invoice $replica) {
  452. $replica->status = InvoiceStatus::Draft;
  453. $replica->invoice_number = Invoice::getNextDocumentNumber();
  454. $replica->date = now();
  455. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  456. })
  457. ->withReplicatedRelationships(['lineItems'])
  458. ->withExcludedRelationshipAttributes('lineItems', [
  459. 'subtotal',
  460. 'total',
  461. 'created_by',
  462. 'updated_by',
  463. 'created_at',
  464. 'updated_at',
  465. ]),
  466. Tables\Actions\BulkAction::make('approveDrafts')
  467. ->label('Approve')
  468. ->icon('heroicon-o-check-circle')
  469. ->databaseTransaction()
  470. ->successNotificationTitle('Invoices approved')
  471. ->failureNotificationTitle('Failed to Approve Invoices')
  472. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  473. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  474. if ($isInvalid) {
  475. Notification::make()
  476. ->title('Approval failed')
  477. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  478. ->persistent()
  479. ->danger()
  480. ->send();
  481. $action->cancel(true);
  482. }
  483. })
  484. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  485. $records->each(function (Invoice $record) {
  486. $record->approveDraft();
  487. });
  488. $action->success();
  489. }),
  490. Tables\Actions\BulkAction::make('markAsSent')
  491. ->label('Mark as sent')
  492. ->icon('heroicon-o-paper-airplane')
  493. ->databaseTransaction()
  494. ->successNotificationTitle('Invoices sent')
  495. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  496. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  497. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  498. if ($isInvalid) {
  499. Notification::make()
  500. ->title('Sending failed')
  501. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  502. ->persistent()
  503. ->danger()
  504. ->send();
  505. $action->cancel(true);
  506. }
  507. })
  508. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  509. $records->each(function (Invoice $record) {
  510. $record->markAsSent();
  511. });
  512. $action->success();
  513. }),
  514. Tables\Actions\BulkAction::make('recordPayments')
  515. ->label('Record payments')
  516. ->icon('heroicon-o-credit-card')
  517. ->stickyModalHeader()
  518. ->stickyModalFooter()
  519. ->modalFooterActionsAlignment(Alignment::End)
  520. ->modalWidth(MaxWidth::TwoExtraLarge)
  521. ->databaseTransaction()
  522. ->successNotificationTitle('Payments recorded')
  523. ->failureNotificationTitle('Failed to Record Payments')
  524. ->deselectRecordsAfterCompletion()
  525. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  526. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  527. if ($isInvalid) {
  528. Notification::make()
  529. ->title('Payment recording failed')
  530. ->body('Invoices that are either draft, paid, overpaid, voided, or are in a foreign currency cannot be processed through bulk payments. Please adjust your selection and try again.')
  531. ->persistent()
  532. ->danger()
  533. ->send();
  534. $action->cancel(true);
  535. }
  536. })
  537. ->mountUsing(function (DocumentCollection $records, Form $form) {
  538. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  539. $form->fill([
  540. 'posted_at' => now(),
  541. 'amount' => $totalAmountDue,
  542. ]);
  543. })
  544. ->form([
  545. Forms\Components\DatePicker::make('posted_at')
  546. ->label('Date'),
  547. Forms\Components\TextInput::make('amount')
  548. ->label('Amount')
  549. ->required()
  550. ->money()
  551. ->rules([
  552. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  553. if (! CurrencyConverter::isValidAmount($value)) {
  554. $fail('Please enter a valid amount');
  555. }
  556. },
  557. ]),
  558. Forms\Components\Select::make('payment_method')
  559. ->label('Payment method')
  560. ->required()
  561. ->options(PaymentMethod::class),
  562. Forms\Components\Select::make('bank_account_id')
  563. ->label('Account')
  564. ->required()
  565. ->options(BankAccount::query()
  566. ->get()
  567. ->pluck('account.name', 'id'))
  568. ->searchable(),
  569. Forms\Components\Textarea::make('notes')
  570. ->label('Notes'),
  571. ])
  572. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  573. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  574. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  575. if ($totalPaymentAmount > $totalAmountDue) {
  576. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  577. Notification::make()
  578. ->title('Excess payment amount')
  579. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  580. ->persistent()
  581. ->warning()
  582. ->send();
  583. $action->halt(true);
  584. }
  585. })
  586. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  587. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  588. $remainingAmount = $totalPaymentAmount;
  589. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  590. $amountDue = $record->getRawOriginal('amount_due');
  591. if ($amountDue <= 0 || $remainingAmount <= 0) {
  592. return;
  593. }
  594. $paymentAmount = min($amountDue, $remainingAmount);
  595. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  596. $record->recordPayment($data);
  597. $remainingAmount -= $paymentAmount;
  598. });
  599. $action->success();
  600. }),
  601. ]),
  602. ]);
  603. }
  604. public static function getRelations(): array
  605. {
  606. return [
  607. RelationManagers\PaymentsRelationManager::class,
  608. ];
  609. }
  610. public static function getPages(): array
  611. {
  612. return [
  613. 'index' => Pages\ListInvoices::route('/'),
  614. 'create' => Pages\CreateInvoice::route('/create'),
  615. 'view' => Pages\ViewInvoice::route('/{record}'),
  616. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  617. ];
  618. }
  619. public static function getWidgets(): array
  620. {
  621. return [
  622. Widgets\InvoiceOverview::class,
  623. ];
  624. }
  625. }