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

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