Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

InvoiceResource.php 37KB

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