選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

InvoiceResource.php 33KB

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