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

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