Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

InvoiceResource.php 35KB

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