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

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