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

InvoiceResource.php 33KB

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