您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

InvoiceResource.php 36KB

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