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

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