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

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