Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

InvoiceResource.php 34KB

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