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.

EstimateResource.php 34KB

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