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

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