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

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