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 37KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  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\Tables\Actions\ReplicateBulkAction;
  10. use App\Filament\Tables\Filters\DateRangeFilter;
  11. use App\Models\Accounting\Adjustment;
  12. use App\Models\Accounting\DocumentLineItem;
  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\Database\Eloquent\Model;
  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. ])->grow(true),
  125. ])->from('md'),
  126. TableRepeater::make('lineItems')
  127. ->relationship()
  128. ->saveRelationshipsUsing(function (TableRepeater $component, Forms\Contracts\HasForms $livewire, ?array $state) {
  129. if (! is_array($state)) {
  130. $state = [];
  131. }
  132. $relationship = $component->getRelationship();
  133. $existingRecords = $component->getCachedExistingRecords();
  134. $recordsToDelete = [];
  135. foreach ($existingRecords->pluck($relationship->getRelated()->getKeyName()) as $keyToCheckForDeletion) {
  136. if (array_key_exists("record-{$keyToCheckForDeletion}", $state)) {
  137. continue;
  138. }
  139. $recordsToDelete[] = $keyToCheckForDeletion;
  140. $existingRecords->forget("record-{$keyToCheckForDeletion}");
  141. }
  142. $relationship
  143. ->whereKey($recordsToDelete)
  144. ->get()
  145. ->each(static fn (Model $record) => $record->delete());
  146. $childComponentContainers = $component->getChildComponentContainers(
  147. withHidden: $component->shouldSaveRelationshipsWhenHidden(),
  148. );
  149. $itemOrder = 1;
  150. $orderColumn = $component->getOrderColumn();
  151. $translatableContentDriver = $livewire->makeFilamentTranslatableContentDriver();
  152. foreach ($childComponentContainers as $itemKey => $item) {
  153. $itemData = $item->getState(shouldCallHooksBefore: false);
  154. if ($orderColumn) {
  155. $itemData[$orderColumn] = $itemOrder;
  156. $itemOrder++;
  157. }
  158. if ($record = ($existingRecords[$itemKey] ?? null)) {
  159. $itemData = $component->mutateRelationshipDataBeforeSave($itemData, record: $record);
  160. if ($itemData === null) {
  161. continue;
  162. }
  163. $translatableContentDriver ?
  164. $translatableContentDriver->updateRecord($record, $itemData) :
  165. $record->fill($itemData)->save();
  166. continue;
  167. }
  168. $relatedModel = $component->getRelatedModel();
  169. $itemData = $component->mutateRelationshipDataBeforeCreate($itemData);
  170. if ($itemData === null) {
  171. continue;
  172. }
  173. if ($translatableContentDriver) {
  174. $record = $translatableContentDriver->makeRecord($relatedModel, $itemData);
  175. } else {
  176. $record = new $relatedModel;
  177. $record->fill($itemData);
  178. }
  179. $record = $relationship->save($record);
  180. $item->model($record)->saveRelationships();
  181. $existingRecords->push($record);
  182. }
  183. $component->getRecord()->setRelation($component->getRelationshipName(), $existingRecords);
  184. /** @var Invoice $invoice */
  185. $invoice = $component->getRecord();
  186. // Recalculate totals for line items
  187. $invoice->lineItems()->each(function (DocumentLineItem $lineItem) {
  188. $lineItem->updateQuietly([
  189. 'tax_total' => $lineItem->calculateTaxTotal()->getAmount(),
  190. 'discount_total' => $lineItem->calculateDiscountTotal()->getAmount(),
  191. ]);
  192. });
  193. $subtotal = $invoice->lineItems()->sum('subtotal') / 100;
  194. $taxTotal = $invoice->lineItems()->sum('tax_total') / 100;
  195. $discountTotal = $invoice->lineItems()->sum('discount_total') / 100;
  196. $grandTotal = $subtotal + $taxTotal - $discountTotal;
  197. $invoice->updateQuietly([
  198. 'subtotal' => $subtotal,
  199. 'tax_total' => $taxTotal,
  200. 'discount_total' => $discountTotal,
  201. 'total' => $grandTotal,
  202. ]);
  203. if ($invoice->approved_at && $invoice->approvalTransaction) {
  204. $invoice->updateApprovalTransaction();
  205. }
  206. })
  207. ->headers([
  208. Header::make('Items')->width('15%'),
  209. Header::make('Description')->width('25%'),
  210. Header::make('Quantity')->width('10%'),
  211. Header::make('Price')->width('10%'),
  212. Header::make('Taxes')->width('15%'),
  213. Header::make('Discounts')->width('15%'),
  214. Header::make('Amount')->width('10%')->align('right'),
  215. ])
  216. ->schema([
  217. Forms\Components\Select::make('offering_id')
  218. ->relationship('sellableOffering', 'name')
  219. ->preload()
  220. ->searchable()
  221. ->required()
  222. ->live()
  223. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  224. $offeringId = $state;
  225. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  226. if ($offeringRecord) {
  227. $set('description', $offeringRecord->description);
  228. $set('unit_price', $offeringRecord->price);
  229. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  230. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  231. }
  232. }),
  233. Forms\Components\TextInput::make('description'),
  234. Forms\Components\TextInput::make('quantity')
  235. ->required()
  236. ->numeric()
  237. ->live()
  238. ->default(1),
  239. Forms\Components\TextInput::make('unit_price')
  240. ->hiddenLabel()
  241. ->numeric()
  242. ->live()
  243. ->default(0),
  244. Forms\Components\Select::make('salesTaxes')
  245. ->relationship('salesTaxes', 'name')
  246. ->preload()
  247. ->multiple()
  248. ->live()
  249. ->searchable(),
  250. Forms\Components\Select::make('salesDiscounts')
  251. ->relationship('salesDiscounts', 'name')
  252. ->preload()
  253. ->multiple()
  254. ->live()
  255. ->searchable(),
  256. Forms\Components\Placeholder::make('total')
  257. ->hiddenLabel()
  258. ->content(function (Forms\Get $get) {
  259. $quantity = max((float) ($get('quantity') ?? 0), 0);
  260. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  261. $salesTaxes = $get('salesTaxes') ?? [];
  262. $salesDiscounts = $get('salesDiscounts') ?? [];
  263. $subtotal = $quantity * $unitPrice;
  264. // Calculate tax amount based on subtotal
  265. $taxAmount = 0;
  266. if (! empty($salesTaxes)) {
  267. $taxRates = Adjustment::whereIn('id', $salesTaxes)->pluck('rate');
  268. $taxAmount = collect($taxRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  269. }
  270. // Calculate discount amount based on subtotal
  271. $discountAmount = 0;
  272. if (! empty($salesDiscounts)) {
  273. $discountRates = Adjustment::whereIn('id', $salesDiscounts)->pluck('rate');
  274. $discountAmount = collect($discountRates)->sum(fn ($rate) => $subtotal * ($rate / 100));
  275. }
  276. // Final total
  277. $total = $subtotal + ($taxAmount - $discountAmount);
  278. return CurrencyConverter::formatToMoney($total);
  279. }),
  280. ]),
  281. Forms\Components\Grid::make(6)
  282. ->schema([
  283. Forms\Components\ViewField::make('totals')
  284. ->columnStart(5)
  285. ->columnSpan(2)
  286. ->view('filament.forms.components.invoice-totals'),
  287. ]),
  288. Forms\Components\Textarea::make('terms')
  289. ->columnSpanFull(),
  290. ]),
  291. Forms\Components\Section::make('Invoice Footer')
  292. ->collapsible()
  293. ->schema([
  294. Forms\Components\Textarea::make('footer')
  295. ->columnSpanFull(),
  296. ]),
  297. ]);
  298. }
  299. public static function table(Table $table): Table
  300. {
  301. return $table
  302. ->defaultSort('due_date')
  303. ->columns([
  304. Tables\Columns\TextColumn::make('status')
  305. ->badge()
  306. ->searchable(),
  307. Tables\Columns\TextColumn::make('due_date')
  308. ->label('Due')
  309. ->asRelativeDay()
  310. ->sortable(),
  311. Tables\Columns\TextColumn::make('date')
  312. ->date()
  313. ->sortable(),
  314. Tables\Columns\TextColumn::make('invoice_number')
  315. ->label('Number')
  316. ->searchable()
  317. ->sortable(),
  318. Tables\Columns\TextColumn::make('client.name')
  319. ->sortable()
  320. ->searchable(),
  321. Tables\Columns\TextColumn::make('total')
  322. ->currency()
  323. ->sortable(),
  324. Tables\Columns\TextColumn::make('amount_paid')
  325. ->label('Amount Paid')
  326. ->currency()
  327. ->sortable(),
  328. Tables\Columns\TextColumn::make('amount_due')
  329. ->label('Amount Due')
  330. ->currency()
  331. ->sortable(),
  332. ])
  333. ->filters([
  334. Tables\Filters\SelectFilter::make('client')
  335. ->relationship('client', 'name')
  336. ->searchable()
  337. ->preload(),
  338. Tables\Filters\SelectFilter::make('status')
  339. ->options(InvoiceStatus::class)
  340. ->native(false),
  341. Tables\Filters\TernaryFilter::make('has_payments')
  342. ->label('Has Payments')
  343. ->queries(
  344. true: fn (Builder $query) => $query->whereHas('payments'),
  345. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  346. ),
  347. DateRangeFilter::make('date')
  348. ->fromLabel('From Date')
  349. ->untilLabel('To Date')
  350. ->indicatorLabel('Date'),
  351. DateRangeFilter::make('due_date')
  352. ->fromLabel('From Due Date')
  353. ->untilLabel('To Due Date')
  354. ->indicatorLabel('Due'),
  355. ])
  356. ->actions([
  357. Tables\Actions\ActionGroup::make([
  358. Tables\Actions\EditAction::make(),
  359. Tables\Actions\ViewAction::make(),
  360. Tables\Actions\DeleteAction::make(),
  361. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  362. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  363. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  364. Tables\Actions\Action::make('recordPayment')
  365. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  366. ->stickyModalHeader()
  367. ->stickyModalFooter()
  368. ->modalFooterActionsAlignment(Alignment::End)
  369. ->modalWidth(MaxWidth::TwoExtraLarge)
  370. ->icon('heroicon-o-credit-card')
  371. ->visible(function (Invoice $record) {
  372. return $record->canRecordPayment();
  373. })
  374. ->mountUsing(function (Invoice $record, Form $form) {
  375. $form->fill([
  376. 'posted_at' => now(),
  377. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  378. ]);
  379. })
  380. ->databaseTransaction()
  381. ->successNotificationTitle('Payment Recorded')
  382. ->form([
  383. Forms\Components\DatePicker::make('posted_at')
  384. ->label('Date'),
  385. Forms\Components\TextInput::make('amount')
  386. ->label('Amount')
  387. ->required()
  388. ->money()
  389. ->live(onBlur: true)
  390. ->helperText(function (Invoice $record, $state) {
  391. if (! CurrencyConverter::isValidAmount($state)) {
  392. return null;
  393. }
  394. $amountDue = $record->getRawOriginal('amount_due');
  395. $amount = CurrencyConverter::convertToCents($state);
  396. if ($amount <= 0) {
  397. return 'Please enter a valid positive amount';
  398. }
  399. if ($record->status === InvoiceStatus::Overpaid) {
  400. $newAmountDue = $amountDue + $amount;
  401. } else {
  402. $newAmountDue = $amountDue - $amount;
  403. }
  404. return match (true) {
  405. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue),
  406. $newAmountDue === 0 => 'Invoice will be fully paid',
  407. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue)),
  408. };
  409. })
  410. ->rules([
  411. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  412. if (! CurrencyConverter::isValidAmount($value)) {
  413. $fail('Please enter a valid amount');
  414. }
  415. },
  416. ]),
  417. Forms\Components\Select::make('payment_method')
  418. ->label('Payment Method')
  419. ->required()
  420. ->options(PaymentMethod::class),
  421. Forms\Components\Select::make('bank_account_id')
  422. ->label('Account')
  423. ->required()
  424. ->options(BankAccount::query()
  425. ->get()
  426. ->pluck('account.name', 'id'))
  427. ->searchable(),
  428. Forms\Components\Textarea::make('notes')
  429. ->label('Notes'),
  430. ])
  431. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  432. $record->recordPayment($data);
  433. $action->success();
  434. }),
  435. ]),
  436. ])
  437. ->bulkActions([
  438. Tables\Actions\BulkActionGroup::make([
  439. Tables\Actions\DeleteBulkAction::make(),
  440. ReplicateBulkAction::make()
  441. ->label('Replicate')
  442. ->modalWidth(MaxWidth::Large)
  443. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  444. ->successNotificationTitle('Invoices Replicated Successfully')
  445. ->failureNotificationTitle('Failed to Replicate Invoices')
  446. ->databaseTransaction()
  447. ->deselectRecordsAfterCompletion()
  448. ->excludeAttributes([
  449. 'status',
  450. 'amount_paid',
  451. 'amount_due',
  452. 'created_by',
  453. 'updated_by',
  454. 'created_at',
  455. 'updated_at',
  456. 'invoice_number',
  457. 'date',
  458. 'due_date',
  459. ])
  460. ->beforeReplicaSaved(function (Invoice $replica) {
  461. $replica->status = InvoiceStatus::Draft;
  462. $replica->invoice_number = Invoice::getNextDocumentNumber();
  463. $replica->date = now();
  464. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  465. })
  466. ->withReplicatedRelationships(['lineItems'])
  467. ->withExcludedRelationshipAttributes('lineItems', [
  468. 'subtotal',
  469. 'total',
  470. 'created_by',
  471. 'updated_by',
  472. 'created_at',
  473. 'updated_at',
  474. ]),
  475. Tables\Actions\BulkAction::make('approveDrafts')
  476. ->label('Approve')
  477. ->icon('heroicon-o-check-circle')
  478. ->databaseTransaction()
  479. ->successNotificationTitle('Invoices Approved')
  480. ->failureNotificationTitle('Failed to Approve Invoices')
  481. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  482. $containsNonDrafts = $records->contains(fn (Invoice $record) => ! $record->isDraft());
  483. if ($containsNonDrafts) {
  484. Notification::make()
  485. ->title('Approval Failed')
  486. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  487. ->persistent()
  488. ->danger()
  489. ->send();
  490. $action->cancel(true);
  491. }
  492. })
  493. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  494. $records->each(function (Invoice $record) {
  495. $record->approveDraft();
  496. });
  497. $action->success();
  498. }),
  499. Tables\Actions\BulkAction::make('markAsSent')
  500. ->label('Mark as Sent')
  501. ->icon('heroicon-o-paper-airplane')
  502. ->databaseTransaction()
  503. ->successNotificationTitle('Invoices Sent')
  504. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  505. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  506. $doesntContainUnsent = $records->contains(fn (Invoice $record) => $record->status !== InvoiceStatus::Unsent);
  507. if ($doesntContainUnsent) {
  508. Notification::make()
  509. ->title('Sending Failed')
  510. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  511. ->persistent()
  512. ->danger()
  513. ->send();
  514. $action->cancel(true);
  515. }
  516. })
  517. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  518. $records->each(function (Invoice $record) {
  519. $record->updateQuietly([
  520. 'status' => InvoiceStatus::Sent,
  521. ]);
  522. });
  523. $action->success();
  524. }),
  525. Tables\Actions\BulkAction::make('recordPayments')
  526. ->label('Record Payments')
  527. ->icon('heroicon-o-credit-card')
  528. ->stickyModalHeader()
  529. ->stickyModalFooter()
  530. ->modalFooterActionsAlignment(Alignment::End)
  531. ->modalWidth(MaxWidth::TwoExtraLarge)
  532. ->databaseTransaction()
  533. ->successNotificationTitle('Payments Recorded')
  534. ->failureNotificationTitle('Failed to Record Payments')
  535. ->deselectRecordsAfterCompletion()
  536. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  537. $cantRecordPayments = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  538. if ($cantRecordPayments) {
  539. Notification::make()
  540. ->title('Payment Recording Failed')
  541. ->body('Invoices that are either draft, paid, overpaid, or voided cannot be processed through bulk payments. Please adjust your selection and try again.')
  542. ->persistent()
  543. ->danger()
  544. ->send();
  545. $action->cancel(true);
  546. }
  547. })
  548. ->mountUsing(function (InvoiceCollection $records, Form $form) {
  549. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  550. $form->fill([
  551. 'posted_at' => now(),
  552. 'amount' => $totalAmountDue,
  553. ]);
  554. })
  555. ->form([
  556. Forms\Components\DatePicker::make('posted_at')
  557. ->label('Date'),
  558. Forms\Components\TextInput::make('amount')
  559. ->label('Amount')
  560. ->required()
  561. ->money()
  562. ->rules([
  563. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  564. if (! CurrencyConverter::isValidAmount($value)) {
  565. $fail('Please enter a valid amount');
  566. }
  567. },
  568. ]),
  569. Forms\Components\Select::make('payment_method')
  570. ->label('Payment Method')
  571. ->required()
  572. ->options(PaymentMethod::class),
  573. Forms\Components\Select::make('bank_account_id')
  574. ->label('Account')
  575. ->required()
  576. ->options(BankAccount::query()
  577. ->get()
  578. ->pluck('account.name', 'id'))
  579. ->searchable(),
  580. Forms\Components\Textarea::make('notes')
  581. ->label('Notes'),
  582. ])
  583. ->before(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  584. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  585. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  586. if ($totalPaymentAmount > $totalAmountDue) {
  587. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  588. Notification::make()
  589. ->title('Excess Payment Amount')
  590. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  591. ->persistent()
  592. ->warning()
  593. ->send();
  594. $action->halt(true);
  595. }
  596. })
  597. ->action(function (InvoiceCollection $records, Tables\Actions\BulkAction $action, array $data) {
  598. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  599. $remainingAmount = $totalPaymentAmount;
  600. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  601. $amountDue = $record->getRawOriginal('amount_due');
  602. if ($amountDue <= 0 || $remainingAmount <= 0) {
  603. return;
  604. }
  605. $paymentAmount = min($amountDue, $remainingAmount);
  606. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  607. $record->recordPayment($data);
  608. $remainingAmount -= $paymentAmount;
  609. });
  610. $action->success();
  611. }),
  612. ]),
  613. ]);
  614. }
  615. public static function getRelations(): array
  616. {
  617. return [
  618. RelationManagers\PaymentsRelationManager::class,
  619. ];
  620. }
  621. public static function getPages(): array
  622. {
  623. return [
  624. 'index' => Pages\ListInvoices::route('/'),
  625. 'create' => Pages\CreateInvoice::route('/create'),
  626. 'view' => Pages\ViewInvoice::route('/{record}'),
  627. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  628. ];
  629. }
  630. public static function getWidgets(): array
  631. {
  632. return [
  633. Widgets\InvoiceOverview::class,
  634. ];
  635. }
  636. }