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

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