Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

InvoiceResource.php 34KB

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