Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

InvoiceResource.php 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\AdjustmentCategory;
  4. use App\Enums\Accounting\AdjustmentStatus;
  5. use App\Enums\Accounting\AdjustmentType;
  6. use App\Enums\Accounting\DocumentDiscountMethod;
  7. use App\Enums\Accounting\DocumentType;
  8. use App\Enums\Accounting\InvoiceStatus;
  9. use App\Enums\Setting\PaymentTerms;
  10. use App\Filament\Company\Resources\Sales\ClientResource\RelationManagers\InvoicesRelationManager;
  11. use App\Filament\Company\Resources\Sales\InvoiceResource\Pages;
  12. use App\Filament\Company\Resources\Sales\InvoiceResource\Widgets;
  13. use App\Filament\Forms\Components\CreateAdjustmentSelect;
  14. use App\Filament\Forms\Components\CreateClientSelect;
  15. use App\Filament\Forms\Components\CreateCurrencySelect;
  16. use App\Filament\Forms\Components\CreateOfferingSelect;
  17. use App\Filament\Forms\Components\CustomTableRepeater;
  18. use App\Filament\Forms\Components\DocumentFooterSection;
  19. use App\Filament\Forms\Components\DocumentHeaderSection;
  20. use App\Filament\Forms\Components\DocumentTotals;
  21. use App\Filament\Tables\Actions\ReplicateBulkAction;
  22. use App\Filament\Tables\Columns;
  23. use App\Filament\Tables\Filters\DateRangeFilter;
  24. use App\Models\Accounting\Adjustment;
  25. use App\Models\Accounting\DocumentLineItem;
  26. use App\Models\Accounting\Invoice;
  27. use App\Models\Common\Client;
  28. use App\Models\Common\Offering;
  29. use App\Utilities\Currency\CurrencyAccessor;
  30. use App\Utilities\Currency\CurrencyConverter;
  31. use App\Utilities\RateCalculator;
  32. use Awcodes\TableRepeater\Header;
  33. use Filament\Forms;
  34. use Filament\Forms\Form;
  35. use Filament\Notifications\Notification;
  36. use Filament\Resources\Resource;
  37. use Filament\Support\Enums\MaxWidth;
  38. use Filament\Tables;
  39. use Filament\Tables\Table;
  40. use Guava\FilamentClusters\Forms\Cluster;
  41. use Illuminate\Database\Eloquent\Builder;
  42. use Illuminate\Database\Eloquent\Collection;
  43. use Illuminate\Support\Carbon;
  44. use Illuminate\Support\Facades\Auth;
  45. class InvoiceResource extends Resource
  46. {
  47. protected static ?string $model = Invoice::class;
  48. public static function form(Form $form): Form
  49. {
  50. $company = Auth::user()->currentCompany;
  51. $settings = $company->defaultInvoice;
  52. return $form
  53. ->schema([
  54. DocumentHeaderSection::make('Invoice Header')
  55. ->defaultHeader($settings->header)
  56. ->defaultSubheader($settings->subheader),
  57. Forms\Components\Section::make('Invoice Details')
  58. ->schema([
  59. Forms\Components\Split::make([
  60. Forms\Components\Group::make([
  61. CreateClientSelect::make('client_id')
  62. ->label('Client')
  63. ->required()
  64. ->live()
  65. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  66. if (! $state) {
  67. return;
  68. }
  69. $currencyCode = Client::find($state)?->currency_code;
  70. if ($currencyCode) {
  71. $set('currency_code', $currencyCode);
  72. }
  73. }),
  74. CreateCurrencySelect::make('currency_code')
  75. ->disabled(function (?Invoice $record) {
  76. return $record?->hasPayments();
  77. }),
  78. ]),
  79. Forms\Components\Group::make([
  80. Forms\Components\TextInput::make('invoice_number')
  81. ->label('Invoice number')
  82. ->default(static fn () => Invoice::getNextDocumentNumber()),
  83. Forms\Components\TextInput::make('order_number')
  84. ->label('P.O/S.O Number'),
  85. Cluster::make([
  86. Forms\Components\DatePicker::make('date')
  87. ->label('Invoice date')
  88. ->live()
  89. ->default(now())
  90. ->disabled(function (?Invoice $record) {
  91. return $record?->hasPayments();
  92. })
  93. ->columnSpan(2)
  94. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  95. $date = $state;
  96. $dueDate = $get('due_date');
  97. if ($date && $dueDate && $date > $dueDate) {
  98. $set('due_date', $date);
  99. }
  100. // Update due date based on payment terms if selected
  101. $paymentTerms = $get('payment_terms');
  102. if ($date && $paymentTerms && $paymentTerms !== 'custom') {
  103. $terms = PaymentTerms::parse($paymentTerms);
  104. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  105. }
  106. }),
  107. Forms\Components\Select::make('payment_terms')
  108. ->label('Payment terms')
  109. ->options(function () {
  110. return collect(PaymentTerms::cases())
  111. ->mapWithKeys(function (PaymentTerms $paymentTerm) {
  112. return [$paymentTerm->value => $paymentTerm->getLabel()];
  113. })
  114. ->put('custom', 'Custom')
  115. ->toArray();
  116. })
  117. ->selectablePlaceholder(false)
  118. ->default($settings->payment_terms->value)
  119. ->live()
  120. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  121. if (! $state || $state === 'custom') {
  122. return;
  123. }
  124. $date = $get('date');
  125. if ($date) {
  126. $terms = PaymentTerms::parse($state);
  127. $set('due_date', Carbon::parse($date)->addDays($terms->getDays())->toDateString());
  128. }
  129. }),
  130. ])
  131. ->label('Invoice date')
  132. ->columns(3),
  133. Forms\Components\DatePicker::make('due_date')
  134. ->label('Payment due')
  135. ->default(function () use ($settings) {
  136. return now()->addDays($settings->payment_terms->getDays());
  137. })
  138. ->minDate(static function (Forms\Get $get) {
  139. return $get('date') ?? now();
  140. })
  141. ->live()
  142. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  143. if (! $state) {
  144. return;
  145. }
  146. $invoiceDate = $get('date');
  147. $paymentTerms = $get('payment_terms');
  148. if (! $invoiceDate || $paymentTerms === 'custom' || ! $paymentTerms) {
  149. return;
  150. }
  151. $term = PaymentTerms::parse($paymentTerms);
  152. $expectedDueDate = Carbon::parse($invoiceDate)->addDays($term->getDays());
  153. if (! Carbon::parse($state)->isSameDay($expectedDueDate)) {
  154. $set('payment_terms', 'custom');
  155. }
  156. }),
  157. Forms\Components\Select::make('discount_method')
  158. ->label('Discount method')
  159. ->options(DocumentDiscountMethod::class)
  160. ->softRequired()
  161. ->default($settings->discount_method)
  162. ->afterStateUpdated(function ($state, Forms\Set $set) {
  163. $discountMethod = DocumentDiscountMethod::parse($state);
  164. if ($discountMethod->isPerDocument()) {
  165. $set('lineItems.*.salesDiscounts', []);
  166. }
  167. })
  168. ->live(),
  169. ])->grow(true),
  170. ])->from('md'),
  171. CustomTableRepeater::make('lineItems')
  172. ->hiddenLabel()
  173. ->relationship()
  174. ->saveRelationshipsUsing(null)
  175. ->dehydrated(true)
  176. ->reorderable()
  177. ->orderColumn('line_number')
  178. ->reorderAtStart()
  179. ->cloneable()
  180. ->addActionLabel('Add an item')
  181. ->headers(function (Forms\Get $get) use ($settings) {
  182. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  183. $headers = [
  184. Header::make($settings->resolveColumnLabel('item_name', 'Items'))
  185. ->width('30%'),
  186. Header::make($settings->resolveColumnLabel('unit_name', 'Quantity'))
  187. ->width('10%'),
  188. Header::make($settings->resolveColumnLabel('price_name', 'Price'))
  189. ->width('10%'),
  190. ];
  191. if ($hasDiscounts) {
  192. $headers[] = Header::make('Adjustments')->width('30%');
  193. } else {
  194. $headers[] = Header::make('Taxes')->width('30%');
  195. }
  196. $headers[] = Header::make($settings->resolveColumnLabel('amount_name', 'Amount'))
  197. ->width('10%')
  198. ->align('right');
  199. return $headers;
  200. })
  201. ->schema([
  202. Forms\Components\Group::make([
  203. CreateOfferingSelect::make('offering_id')
  204. ->label('Item')
  205. ->hiddenLabel()
  206. ->placeholder('Select item')
  207. ->required()
  208. ->live()
  209. ->inlineSuffix()
  210. ->sellable()
  211. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state, ?DocumentLineItem $record) {
  212. $offeringId = $state;
  213. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  214. $isPerLineItem = $discountMethod->isPerLineItem();
  215. $existingTaxIds = [];
  216. $existingDiscountIds = [];
  217. if ($record) {
  218. $existingTaxIds = $record->salesTaxes()->pluck('adjustments.id')->toArray();
  219. if ($isPerLineItem) {
  220. $existingDiscountIds = $record->salesDiscounts()->pluck('adjustments.id')->toArray();
  221. }
  222. }
  223. $with = [
  224. 'salesTaxes' => static function ($query) use ($existingTaxIds) {
  225. $query->where(static function ($query) use ($existingTaxIds) {
  226. $query->where('status', AdjustmentStatus::Active)
  227. ->orWhereIn('adjustments.id', $existingTaxIds);
  228. });
  229. },
  230. ];
  231. if ($isPerLineItem) {
  232. $with['salesDiscounts'] = static function ($query) use ($existingDiscountIds) {
  233. $query->where(static function ($query) use ($existingDiscountIds) {
  234. $query->where('status', AdjustmentStatus::Active)
  235. ->orWhereIn('adjustments.id', $existingDiscountIds);
  236. });
  237. };
  238. }
  239. $offeringRecord = Offering::with($with)->find($offeringId);
  240. if (! $offeringRecord) {
  241. return;
  242. }
  243. $unitPrice = CurrencyConverter::convertCentsToFormatSimple($offeringRecord->price, 'USD');
  244. $set('description', $offeringRecord->description);
  245. $set('unit_price', $unitPrice);
  246. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  247. if ($isPerLineItem) {
  248. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  249. }
  250. }),
  251. Forms\Components\TextInput::make('description')
  252. ->placeholder('Enter item description')
  253. ->hiddenLabel(),
  254. ])->columnSpan(1),
  255. Forms\Components\TextInput::make('quantity')
  256. ->required()
  257. ->numeric()
  258. ->live()
  259. ->maxValue(9999999999.99)
  260. ->default(1),
  261. Forms\Components\TextInput::make('unit_price')
  262. ->hiddenLabel()
  263. ->money(useAffix: false)
  264. ->live()
  265. ->default(0),
  266. Forms\Components\Group::make([
  267. CreateAdjustmentSelect::make('salesTaxes')
  268. ->label('Taxes')
  269. ->hiddenLabel()
  270. ->placeholder('Select taxes')
  271. ->category(AdjustmentCategory::Tax)
  272. ->type(AdjustmentType::Sales)
  273. ->adjustmentsRelationship('salesTaxes')
  274. ->saveRelationshipsUsing(null)
  275. ->dehydrated(true)
  276. ->inlineSuffix()
  277. ->preload()
  278. ->multiple()
  279. ->live()
  280. ->searchable(),
  281. CreateAdjustmentSelect::make('salesDiscounts')
  282. ->label('Discounts')
  283. ->hiddenLabel()
  284. ->placeholder('Select discounts')
  285. ->category(AdjustmentCategory::Discount)
  286. ->type(AdjustmentType::Sales)
  287. ->adjustmentsRelationship('salesDiscounts')
  288. ->saveRelationshipsUsing(null)
  289. ->dehydrated(true)
  290. ->inlineSuffix()
  291. ->multiple()
  292. ->live()
  293. ->hidden(function (Forms\Get $get) {
  294. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  295. return $discountMethod->isPerDocument();
  296. })
  297. ->searchable(),
  298. ])->columnSpan(1),
  299. Forms\Components\Placeholder::make('total')
  300. ->hiddenLabel()
  301. ->extraAttributes(['class' => 'text-left sm:text-right'])
  302. ->content(function (Forms\Get $get) {
  303. $quantity = max((float) ($get('quantity') ?? 0), 0);
  304. $unitPrice = CurrencyConverter::isValidAmount($get('unit_price'), 'USD')
  305. ? CurrencyConverter::convertToFloat($get('unit_price'), 'USD')
  306. : 0;
  307. $salesTaxes = $get('salesTaxes') ?? [];
  308. $salesDiscounts = $get('salesDiscounts') ?? [];
  309. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  310. $subtotal = $quantity * $unitPrice;
  311. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  312. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  313. ->get()
  314. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  315. if ($adjustment->computation->isPercentage()) {
  316. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  317. } else {
  318. return $adjustment->getRawOriginal('rate');
  319. }
  320. });
  321. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  322. ->get()
  323. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  324. if ($adjustment->computation->isPercentage()) {
  325. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  326. } else {
  327. return $adjustment->getRawOriginal('rate');
  328. }
  329. });
  330. // Final total
  331. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  332. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  333. }),
  334. ]),
  335. DocumentTotals::make()
  336. ->type(DocumentType::Invoice),
  337. Forms\Components\Textarea::make('terms')
  338. ->default($settings->terms)
  339. ->columnSpanFull(),
  340. ]),
  341. DocumentFooterSection::make('Invoice Footer')
  342. ->defaultFooter($settings->footer),
  343. ]);
  344. }
  345. public static function table(Table $table): Table
  346. {
  347. return $table
  348. ->defaultSort('due_date')
  349. ->modifyQueryUsing(function (Builder $query, Tables\Contracts\HasTable $livewire) {
  350. if (property_exists($livewire, 'recurringInvoice')) {
  351. $recurringInvoiceId = $livewire->recurringInvoice;
  352. if (! empty($recurringInvoiceId)) {
  353. $query->where('recurring_invoice_id', $recurringInvoiceId);
  354. }
  355. }
  356. return $query;
  357. })
  358. ->columns([
  359. Columns::id(),
  360. Tables\Columns\TextColumn::make('status')
  361. ->badge()
  362. ->searchable(),
  363. Tables\Columns\TextColumn::make('due_date')
  364. ->label('Due')
  365. ->asRelativeDay()
  366. ->sortable()
  367. ->hideOnTabs(['draft']),
  368. Tables\Columns\TextColumn::make('date')
  369. ->date()
  370. ->sortable(),
  371. Tables\Columns\TextColumn::make('invoice_number')
  372. ->label('Number')
  373. ->searchable()
  374. ->description(function (Invoice $record) {
  375. return $record->source_type?->getLabel();
  376. })
  377. ->sortable(),
  378. Tables\Columns\TextColumn::make('client.name')
  379. ->sortable()
  380. ->searchable()
  381. ->hiddenOn(InvoicesRelationManager::class),
  382. Tables\Columns\TextColumn::make('total')
  383. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  384. ->sortable()
  385. ->toggleable()
  386. ->alignEnd(),
  387. Tables\Columns\TextColumn::make('amount_paid')
  388. ->label('Amount paid')
  389. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  390. ->sortable()
  391. ->alignEnd()
  392. ->showOnTabs(['unpaid']),
  393. Tables\Columns\TextColumn::make('amount_due')
  394. ->label('Amount due')
  395. ->currencyWithConversion(static fn (Invoice $record) => $record->currency_code)
  396. ->sortable()
  397. ->alignEnd()
  398. ->hideOnTabs(['draft']),
  399. ])
  400. ->filters([
  401. Tables\Filters\SelectFilter::make('client')
  402. ->relationship('client', 'name')
  403. ->searchable()
  404. ->preload()
  405. ->hiddenOn(InvoicesRelationManager::class),
  406. Tables\Filters\SelectFilter::make('status')
  407. ->options(InvoiceStatus::class)
  408. ->multiple(),
  409. Tables\Filters\TernaryFilter::make('has_payments')
  410. ->label('Has payments')
  411. ->queries(
  412. true: fn (Builder $query) => $query->whereHas('payments'),
  413. false: fn (Builder $query) => $query->whereDoesntHave('payments'),
  414. ),
  415. Tables\Filters\SelectFilter::make('source_type')
  416. ->label('Source type')
  417. ->options([
  418. DocumentType::Estimate->value => DocumentType::Estimate->getLabel(),
  419. DocumentType::RecurringInvoice->value => DocumentType::RecurringInvoice->getLabel(),
  420. ])
  421. ->native(false)
  422. ->query(function (Builder $query, array $data) {
  423. $sourceType = $data['value'] ?? null;
  424. return match ($sourceType) {
  425. DocumentType::Estimate->value => $query->whereNotNull('estimate_id'),
  426. DocumentType::RecurringInvoice->value => $query->whereNotNull('recurring_invoice_id'),
  427. default => $query,
  428. };
  429. }),
  430. DateRangeFilter::make('date')
  431. ->fromLabel('From date')
  432. ->untilLabel('To date')
  433. ->indicatorLabel('Date'),
  434. DateRangeFilter::make('due_date')
  435. ->fromLabel('From due date')
  436. ->untilLabel('To due date')
  437. ->indicatorLabel('Due'),
  438. ])
  439. ->actions([
  440. Tables\Actions\ActionGroup::make([
  441. Tables\Actions\ActionGroup::make([
  442. Tables\Actions\EditAction::make()
  443. ->url(static fn (Invoice $record) => Pages\EditInvoice::getUrl(['record' => $record])),
  444. Tables\Actions\ViewAction::make()
  445. ->url(static fn (Invoice $record) => Pages\ViewInvoice::getUrl(['record' => $record])),
  446. Invoice::getReplicateAction(Tables\Actions\ReplicateAction::class),
  447. Invoice::getApproveDraftAction(Tables\Actions\Action::class),
  448. Invoice::getMarkAsSentAction(Tables\Actions\Action::class),
  449. Tables\Actions\Action::make('recordPayment')
  450. ->label('Record Payment')
  451. ->icon('heroicon-m-credit-card')
  452. ->visible(function (Invoice $record) {
  453. return $record->canRecordPayment();
  454. })
  455. ->url(fn (Invoice $record) => Pages\RecordPayments::getUrl([
  456. 'tableFilters' => [
  457. 'client_id' => ['value' => $record->client_id],
  458. 'currency_code' => ['value' => $record->currency_code],
  459. ],
  460. 'invoiceId' => $record->id,
  461. ]))
  462. ->openUrlInNewTab(false),
  463. ])->dropdown(false),
  464. Tables\Actions\DeleteAction::make(),
  465. ]),
  466. ])
  467. ->bulkActions([
  468. Tables\Actions\BulkActionGroup::make([
  469. Tables\Actions\DeleteBulkAction::make(),
  470. ReplicateBulkAction::make()
  471. ->label('Replicate')
  472. ->modalWidth(MaxWidth::Large)
  473. ->modalDescription('Replicating invoices will also replicate their line items. Are you sure you want to proceed?')
  474. ->successNotificationTitle('Invoices replicated successfully')
  475. ->failureNotificationTitle('Failed to replicate invoices')
  476. ->databaseTransaction()
  477. ->excludeAttributes([
  478. 'status',
  479. 'amount_paid',
  480. 'amount_due',
  481. 'created_by',
  482. 'updated_by',
  483. 'created_at',
  484. 'updated_at',
  485. 'invoice_number',
  486. 'date',
  487. 'due_date',
  488. 'approved_at',
  489. 'paid_at',
  490. 'last_sent_at',
  491. 'last_viewed_at',
  492. ])
  493. ->beforeReplicaSaved(function (Invoice $replica) {
  494. $replica->status = InvoiceStatus::Draft;
  495. $replica->invoice_number = Invoice::getNextDocumentNumber();
  496. $replica->date = now();
  497. $replica->due_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  498. })
  499. ->withReplicatedRelationships(['lineItems'])
  500. ->withExcludedRelationshipAttributes('lineItems', [
  501. 'subtotal',
  502. 'total',
  503. 'created_by',
  504. 'updated_by',
  505. 'created_at',
  506. 'updated_at',
  507. ]),
  508. Tables\Actions\BulkAction::make('approveDrafts')
  509. ->label('Approve')
  510. ->icon('heroicon-o-check-circle')
  511. ->databaseTransaction()
  512. ->successNotificationTitle('Invoices approved')
  513. ->failureNotificationTitle('Failed to Approve Invoices')
  514. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  515. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeApproved());
  516. if ($isInvalid) {
  517. Notification::make()
  518. ->title('Approval failed')
  519. ->body('Only draft invoices can be approved. Please adjust your selection and try again.')
  520. ->persistent()
  521. ->danger()
  522. ->send();
  523. $action->cancel(true);
  524. }
  525. })
  526. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  527. $records->each(function (Invoice $record) {
  528. $record->approveDraft();
  529. });
  530. $action->success();
  531. }),
  532. Tables\Actions\BulkAction::make('markAsSent')
  533. ->label('Mark as sent')
  534. ->icon('heroicon-o-paper-airplane')
  535. ->databaseTransaction()
  536. ->successNotificationTitle('Invoices sent')
  537. ->failureNotificationTitle('Failed to Mark Invoices as Sent')
  538. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  539. $isInvalid = $records->contains(fn (Invoice $record) => ! $record->canBeMarkedAsSent());
  540. if ($isInvalid) {
  541. Notification::make()
  542. ->title('Sending failed')
  543. ->body('Only unsent invoices can be marked as sent. Please adjust your selection and try again.')
  544. ->persistent()
  545. ->danger()
  546. ->send();
  547. $action->cancel(true);
  548. }
  549. })
  550. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  551. $records->each(function (Invoice $record) {
  552. $record->markAsSent();
  553. });
  554. $action->success();
  555. }),
  556. ]),
  557. ]);
  558. }
  559. public static function getPages(): array
  560. {
  561. return [
  562. 'index' => Pages\ListInvoices::route('/'),
  563. 'record-payments' => Pages\RecordPayments::route('/record-payments'),
  564. 'create' => Pages\CreateInvoice::route('/create'),
  565. 'view' => Pages\ViewInvoice::route('/{record}'),
  566. 'edit' => Pages\EditInvoice::route('/{record}/edit'),
  567. ];
  568. }
  569. public static function getWidgets(): array
  570. {
  571. return [
  572. Widgets\InvoiceOverview::class,
  573. ];
  574. }
  575. }