Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

InvoiceResource.php 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. return;
  157. }
  158. $unitPrice = CurrencyConverter::convertToFloat($offeringRecord->price, $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency());
  159. $set('description', $offeringRecord->description);
  160. $set('unit_price', $unitPrice);
  161. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  162. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  163. if ($discountMethod->isPerLineItem()) {
  164. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  165. }
  166. }),
  167. Forms\Components\TextInput::make('description'),
  168. Forms\Components\TextInput::make('quantity')
  169. ->required()
  170. ->numeric()
  171. ->live()
  172. ->maxValue(9999999999.99)
  173. ->default(1),
  174. Forms\Components\TextInput::make('unit_price')
  175. ->hiddenLabel()
  176. ->numeric()
  177. ->live()
  178. ->maxValue(9999999999.99)
  179. ->default(0),
  180. Forms\Components\Select::make('salesTaxes')
  181. ->relationship('salesTaxes', 'name')
  182. ->saveRelationshipsUsing(null)
  183. ->dehydrated(true)
  184. ->preload()
  185. ->multiple()
  186. ->live()
  187. ->searchable(),
  188. Forms\Components\Select::make('salesDiscounts')
  189. ->relationship('salesDiscounts', 'name')
  190. ->saveRelationshipsUsing(null)
  191. ->dehydrated(true)
  192. ->preload()
  193. ->multiple()
  194. ->live()
  195. ->hidden(function (Forms\Get $get) {
  196. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  197. return $discountMethod->isPerDocument();
  198. })
  199. ->searchable(),
  200. Forms\Components\Placeholder::make('total')
  201. ->hiddenLabel()
  202. ->extraAttributes(['class' => 'text-left sm:text-right'])
  203. ->content(function (Forms\Get $get) {
  204. $quantity = max((float) ($get('quantity') ?? 0), 0);
  205. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  206. $salesTaxes = $get('salesTaxes') ?? [];
  207. $salesDiscounts = $get('salesDiscounts') ?? [];
  208. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  209. $subtotal = $quantity * $unitPrice;
  210. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  211. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  212. ->get()
  213. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  214. if ($adjustment->computation->isPercentage()) {
  215. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  216. } else {
  217. return $adjustment->getRawOriginal('rate');
  218. }
  219. });
  220. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  221. ->get()
  222. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  223. if ($adjustment->computation->isPercentage()) {
  224. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  225. } else {
  226. return $adjustment->getRawOriginal('rate');
  227. }
  228. });
  229. // Final total
  230. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  231. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  232. }),
  233. ]),
  234. DocumentTotals::make()
  235. ->type(DocumentType::Invoice),
  236. Forms\Components\Textarea::make('terms')
  237. ->default($settings->terms)
  238. ->columnSpanFull(),
  239. ]),
  240. DocumentFooterSection::make('Invoice Footer')
  241. ->defaultFooter($settings->footer),
  242. ]);
  243. }
  244. public static function table(Table $table): Table
  245. {
  246. return $table
  247. ->defaultSort('due_date')
  248. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  249. if (property_exists($livewire, 'recurringInvoice')) {
  250. $recurringInvoiceId = $livewire->recurringInvoice;
  251. if (! empty($recurringInvoiceId)) {
  252. $query->where('recurring_invoice_id', $recurringInvoiceId);
  253. }
  254. }
  255. return $query;
  256. })
  257. ->columns([
  258. Columns::id(),
  259. Tables\Columns\TextColumn::make('status')
  260. ->badge()
  261. ->searchable(),
  262. Tables\Columns\TextColumn::make('due_date')
  263. ->label('Due')
  264. ->asRelativeDay()
  265. ->sortable()
  266. ->hideOnTabs(['draft']),
  267. Tables\Columns\TextColumn::make('date')
  268. ->date()
  269. ->sortable(),
  270. Tables\Columns\TextColumn::make('invoice_number')
  271. ->label('Number')
  272. ->searchable()
  273. ->description(function (Invoice $record) {
  274. return $record->source_type?->getLabel();
  275. })
  276. ->sortable(),
  277. Tables\Columns\TextColumn::make('client.name')
  278. ->sortable()
  279. ->searchable()
  280. ->hiddenOn(InvoicesRelationManager::class),
  281. Tables\Columns\TextColumn::make('total')
  282. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  283. ->sortable()
  284. ->toggleable()
  285. ->alignEnd(),
  286. Tables\Columns\TextColumn::make('amount_paid')
  287. ->label('Amount paid')
  288. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  289. ->sortable()
  290. ->alignEnd()
  291. ->showOnTabs(['unpaid']),
  292. Tables\Columns\TextColumn::make('amount_due')
  293. ->label('Amount due')
  294. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  295. ->sortable()
  296. ->alignEnd()
  297. ->hideOnTabs(['draft']),
  298. ])
  299. ->filters([
  300. Tables\Filters\SelectFilter::make('client')
  301. ->relationship('client', 'name')
  302. ->searchable()
  303. ->preload(),
  304. Tables\Filters\SelectFilter::make('status')
  305. ->options(InvoiceStatus::class)
  306. ->multiple(),
  307. Tables\Filters\TernaryFilter::make('has_payments')
  308. ->label('Has payments')
  309. ->queries(
  310. true: fn (Builder $query) => $query->whereHas('payments'),
  311. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  312. ),
  313. Tables\Filters\SelectFilter::make('source_type')
  314. ->label('Source type')
  315. ->options([
  316. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  317. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  318. ])
  319. ->native(false)
  320. ->query(function (Builder $query, array $data) {
  321. $sourceType = $data['value'] ?? null;
  322. return match ($sourceType) {
  323. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  324. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  325. default => $query,
  326. };
  327. }),
  328. DateRangeFilter::make('date')
  329. ->fromLabel('From date')
  330. ->untilLabel('To date')
  331. ->indicatorLabel('Date'),
  332. DateRangeFilter::make('due_date')
  333. ->fromLabel('From due date')
  334. ->untilLabel('To due date')
  335. ->indicatorLabel('Due'),
  336. ])
  337. ->actions([
  338. Tables\Actions\ActionGroup::make([
  339. Tables\Actions\ActionGroup::make([
  340. Tables\Actions\EditAction::make()
  341. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  342. Tables\Actions\ViewAction::make()
  343. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  344. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  345. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  346. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  347. Tables\Actions\Action::make('recordPayment')
  348. ->label(fn (Invoice $record) => $record->status === InvoiceStatus::Overpaid ? 'Refund Overpayment' : 'Record Payment')
  349. ->stickyModalHeader()
  350. ->stickyModalFooter()
  351. ->modalFooterActionsAlignment(Alignment::End)
  352. ->modalWidth(MaxWidth::TwoExtraLarge)
  353. ->icon('heroicon-o-credit-card')
  354. ->visible(function (Invoice $record) {
  355. return $record->canRecordPayment();
  356. })
  357. ->mountUsing(function (Invoice $record, Form $form) {
  358. $form->fill([
  359. 'posted_at' => now(),
  360. 'amount' => $record->status === InvoiceStatus::Overpaid ? ltrim($record->amount_due, '-') : $record->amount_due,
  361. ]);
  362. })
  363. ->databaseTransaction()
  364. ->successNotificationTitle('Payment recorded')
  365. ->form([
  366. Forms\Components\DatePicker::make('posted_at')
  367. ->label('Date'),
  368. Forms\Components\TextInput::make('amount')
  369. ->label('Amount')
  370. ->required()
  371. ->money(fn (Invoice $record) => $record->currency_code)
  372. ->live(onBlur: true)
  373. ->helperText(function (Invoice $record, $state) {
  374. $invoiceCurrency = $record->currency_code;
  375. if (! CurrencyConverter::isValidAmount($state, $invoiceCurrency)) {
  376. return null;
  377. }
  378. $amountDue = $record->getRawOriginal('amount_due');
  379. $amount = CurrencyConverter::convertToCents($state, $invoiceCurrency);
  380. if ($amount <= 0) {
  381. return 'Please enter a valid positive amount';
  382. }
  383. if ($record->status === InvoiceStatus::Overpaid) {
  384. $newAmountDue = $amountDue + $amount;
  385. } else {
  386. $newAmountDue = $amountDue - $amount;
  387. }
  388. return match (true) {
  389. $newAmountDue > 0 => 'Amount due after payment will be ' . CurrencyConverter::formatCentsToMoney($newAmountDue, $invoiceCurrency),
  390. $newAmountDue === 0 => 'Invoice will be fully paid',
  391. default => 'Invoice will be overpaid by ' . CurrencyConverter::formatCentsToMoney(abs($newAmountDue), $invoiceCurrency),
  392. };
  393. })
  394. ->rules([
  395. static fn (Invoice $record): Closure => static function (string $attribute, $value, Closure $fail) use ($record) {
  396. if (! CurrencyConverter::isValidAmount($value, $record->currency_code)) {
  397. $fail('Please enter a valid amount');
  398. }
  399. },
  400. ]),
  401. Forms\Components\Select::make('payment_method')
  402. ->label('Payment method')
  403. ->required()
  404. ->options(PaymentMethod::class),
  405. Forms\Components\Select::make('bank_account_id')
  406. ->label('Account')
  407. ->required()
  408. ->options(BankAccount::query()
  409. ->get()
  410. ->pluck('account.name', 'id'))
  411. ->searchable(),
  412. Forms\Components\Textarea::make('notes')
  413. ->label('Notes'),
  414. ])
  415. ->action(function (Invoice $record, Tables\Actions\Action $action, array $data) {
  416. $record->recordPayment($data);
  417. $action->success();
  418. }),
  419. ])->dropdown(false),
  420. Tables\Actions\DeleteAction::make(),
  421. ]),
  422. ])
  423. ->bulkActions([
  424. Tables\Actions\BulkActionGroup::make([
  425. Tables\Actions\DeleteBulkAction::make(),
  426. ReplicateBulkAction::make()
  427. ->label('Replicate')
  428. ->modalWidth(MaxWidth::Large)
  429. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  430. ->successNotificationTitle('Invoices replicated successfully')
  431. ->failureNotificationTitle('Failed to replicate invoices')
  432. ->databaseTransaction()
  433. ->deselectRecordsAfterCompletion()
  434. ->excludeAttributes([
  435. 'status',
  436. 'amount_paid',
  437. 'amount_due',
  438. 'created_by',
  439. 'updated_by',
  440. 'created_at',
  441. 'updated_at',
  442. 'invoice_number',
  443. 'date',
  444. 'due_date',
  445. 'approved_at',
  446. 'paid_at',
  447. 'last_sent_at',
  448. 'last_viewed_at',
  449. ])
  450. ->beforeReplicaSaved(function (Invoice $replica) {
  451. $replica->status = InvoiceStatus::Draft;
  452. $replica->invoice_number = Invoice::getNextDocumentNumber();
  453. $replica->date = now();
  454. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  455. })
  456. ->withReplicatedRelationships(['lineItems'])
  457. ->withExcludedRelationshipAttributes('lineItems', [
  458. 'subtotal',
  459. 'total',
  460. 'created_by',
  461. 'updated_by',
  462. 'created_at',
  463. 'updated_at',
  464. ]),
  465. Tables\Actions\BulkAction::make('approveDrafts')
  466. ->label('Approve')
  467. ->icon('heroicon-o-check-circle')
  468. ->databaseTransaction()
  469. ->successNotificationTitle('Invoices approved')
  470. ->failureNotificationTitle('Failed to Approve Invoices')
  471. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  472. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  473. if ($isInvalid) {
  474. Notification::make()
  475. ->title('Approval failed')
  476. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  477. ->persistent()
  478. ->danger()
  479. ->send();
  480. $action->cancel(true);
  481. }
  482. })
  483. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  484. $records->each(function (Invoice $record) {
  485. $record->approveDraft();
  486. });
  487. $action->success();
  488. }),
  489. Tables\Actions\BulkAction::make('markAsSent')
  490. ->label('Mark as sent')
  491. ->icon('heroicon-o-paper-airplane')
  492. ->databaseTransaction()
  493. ->successNotificationTitle('Invoices sent')
  494. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  495. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  496. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  497. if ($isInvalid) {
  498. Notification::make()
  499. ->title('Sending failed')
  500. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  501. ->persistent()
  502. ->danger()
  503. ->send();
  504. $action->cancel(true);
  505. }
  506. })
  507. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  508. $records->each(function (Invoice $record) {
  509. $record->markAsSent();
  510. });
  511. $action->success();
  512. }),
  513. Tables\Actions\BulkAction::make('recordPayments')
  514. ->label('Record payments')
  515. ->icon('heroicon-o-credit-card')
  516. ->stickyModalHeader()
  517. ->stickyModalFooter()
  518. ->modalFooterActionsAlignment(Alignment::End)
  519. ->modalWidth(MaxWidth::TwoExtraLarge)
  520. ->databaseTransaction()
  521. ->successNotificationTitle('Payments recorded')
  522. ->failureNotificationTitle('Failed to Record Payments')
  523. ->deselectRecordsAfterCompletion()
  524. ->beforeFormFilled(function (Collection $records, Tables\Actions\BulkAction $action) {
  525. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBulkRecordPayment());
  526. if ($isInvalid) {
  527. Notification::make()
  528. ->title('Payment recording failed')
  529. ->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.')
  530. ->persistent()
  531. ->danger()
  532. ->send();
  533. $action->cancel(true);
  534. }
  535. })
  536. ->mountUsing(function (DocumentCollection $records, Form $form) {
  537. $totalAmountDue = $records->sumMoneyFormattedSimple('amount_due');
  538. $form->fill([
  539. 'posted_at' => now(),
  540. 'amount' => $totalAmountDue,
  541. ]);
  542. })
  543. ->form([
  544. Forms\Components\DatePicker::make('posted_at')
  545. ->label('Date'),
  546. Forms\Components\TextInput::make('amount')
  547. ->label('Amount')
  548. ->required()
  549. ->money()
  550. ->rules([
  551. static fn (): Closure => static function (string $attribute, $value, Closure $fail) {
  552. if (! CurrencyConverter::isValidAmount($value)) {
  553. $fail('Please enter a valid amount');
  554. }
  555. },
  556. ]),
  557. Forms\Components\Select::make('payment_method')
  558. ->label('Payment method')
  559. ->required()
  560. ->options(PaymentMethod::class),
  561. Forms\Components\Select::make('bank_account_id')
  562. ->label('Account')
  563. ->required()
  564. ->options(BankAccount::query()
  565. ->get()
  566. ->pluck('account.name', 'id'))
  567. ->searchable(),
  568. Forms\Components\Textarea::make('notes')
  569. ->label('Notes'),
  570. ])
  571. ->before(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  572. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  573. $totalAmountDue = $records->sumMoneyInCents('amount_due');
  574. if ($totalPaymentAmount > $totalAmountDue) {
  575. $formattedTotalAmountDue = CurrencyConverter::formatCentsToMoney($totalAmountDue);
  576. Notification::make()
  577. ->title('Excess payment amount')
  578. ->body("The payment amount exceeds the total amount due of {$formattedTotalAmountDue}. Please adjust the payment amount and try again.")
  579. ->persistent()
  580. ->warning()
  581. ->send();
  582. $action->halt(true);
  583. }
  584. })
  585. ->action(function (DocumentCollection $records, Tables\Actions\BulkAction $action, array $data) {
  586. $totalPaymentAmount = CurrencyConverter::convertToCents($data['amount']);
  587. $remainingAmount = $totalPaymentAmount;
  588. $records->each(function (Invoice $record) use (&$remainingAmount, $data) {
  589. $amountDue = $record->getRawOriginal('amount_due');
  590. if ($amountDue <= 0 || $remainingAmount <= 0) {
  591. return;
  592. }
  593. $paymentAmount = min($amountDue, $remainingAmount);
  594. $data['amount'] = CurrencyConverter::convertCentsToFormatSimple($paymentAmount);
  595. $record->recordPayment($data);
  596. $remainingAmount -= $paymentAmount;
  597. });
  598. $action->success();
  599. }),
  600. ]),
  601. ]);
  602. }
  603. public static function getRelations(): array
  604. {
  605. return [
  606. RelationManagers\PaymentsRelationManager::class,
  607. ];
  608. }
  609. public static function getPages(): array
  610. {
  611. return [
  612. 'index' => Pages\ListInvoices::route('/'),
  613. 'create' => Pages\CreateInvoice::route('/create'),
  614. 'view' => Pages\ViewInvoice::route('/{record}'),
  615. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  616. ];
  617. }
  618. public static function getWidgets(): array
  619. {
  620. return [
  621. Widgets\InvoiceOverview::class,
  622. ];
  623. }
  624. }