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

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