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 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. namespace App\Filament\Company\Resources\Sales;
  3. use App\Enums\Accounting\DocumentDiscountMethod;
  4. use App\Enums\Accounting\DocumentType;
  5. use App\Enums\Accounting\EstimateStatus;
  6. use App\Filament\Company\Resources\Sales\EstimateResource\Pages;
  7. use App\Filament\Company\Resources\Sales\EstimateResource\Widgets;
  8. use App\Filament\Forms\Components\CreateCurrencySelect;
  9. use App\Filament\Forms\Components\DocumentTotals;
  10. use App\Filament\Tables\Actions\ReplicateBulkAction;
  11. use App\Filament\Tables\Filters\DateRangeFilter;
  12. use App\Models\Accounting\Adjustment;
  13. use App\Models\Accounting\Estimate;
  14. use App\Models\Common\Client;
  15. use App\Models\Common\Offering;
  16. use App\Utilities\Currency\CurrencyAccessor;
  17. use App\Utilities\Currency\CurrencyConverter;
  18. use App\Utilities\RateCalculator;
  19. use Awcodes\TableRepeater\Components\TableRepeater;
  20. use Awcodes\TableRepeater\Header;
  21. use Filament\Forms;
  22. use Filament\Forms\Components\FileUpload;
  23. use Filament\Forms\Form;
  24. use Filament\Notifications\Notification;
  25. use Filament\Resources\Resource;
  26. use Filament\Support\Enums\MaxWidth;
  27. use Filament\Tables;
  28. use Filament\Tables\Table;
  29. use Illuminate\Database\Eloquent\Collection;
  30. use Illuminate\Support\Facades\Auth;
  31. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  32. class EstimateResource extends Resource
  33. {
  34. protected static ?string $model = Estimate::class;
  35. protected static ?string $navigationIcon = 'heroicon-o-rectangle-stack';
  36. public static function form(Form $form): Form
  37. {
  38. $company = Auth::user()->currentCompany;
  39. return $form
  40. ->schema([
  41. Forms\Components\Section::make('Estimate Header')
  42. ->collapsible()
  43. ->collapsed()
  44. ->schema([
  45. Forms\Components\Split::make([
  46. Forms\Components\Group::make([
  47. FileUpload::make('logo')
  48. ->openable()
  49. ->maxSize(1024)
  50. ->localizeLabel()
  51. ->visibility('public')
  52. ->disk('public')
  53. ->directory('logos/document')
  54. ->imageResizeMode('contain')
  55. ->imageCropAspectRatio('3:2')
  56. ->panelAspectRatio('3:2')
  57. ->maxWidth(MaxWidth::ExtraSmall)
  58. ->panelLayout('integrated')
  59. ->removeUploadedFileButtonPosition('center bottom')
  60. ->uploadButtonPosition('center bottom')
  61. ->uploadProgressIndicatorPosition('center bottom')
  62. ->getUploadedFileNameForStorageUsing(
  63. static fn (TemporaryUploadedFile $file): string => (string) str($file->getClientOriginalName())
  64. ->prepend(Auth::user()->currentCompany->id . '_'),
  65. )
  66. ->acceptedFileTypes(['image/png', 'image/jpeg', 'image/gif']),
  67. ]),
  68. Forms\Components\Group::make([
  69. Forms\Components\TextInput::make('header')
  70. ->default('Estimate'),
  71. Forms\Components\TextInput::make('subheader'),
  72. Forms\Components\View::make('filament.forms.components.company-info')
  73. ->viewData([
  74. 'company_name' => $company->name,
  75. 'company_address' => $company->profile->address,
  76. 'company_city' => $company->profile->city?->name,
  77. 'company_state' => $company->profile->state?->name,
  78. 'company_zip' => $company->profile->zip_code,
  79. 'company_country' => $company->profile->state?->country->name,
  80. ]),
  81. ])->grow(true),
  82. ])->from('md'),
  83. ]),
  84. Forms\Components\Section::make('Estimate Details')
  85. ->schema([
  86. Forms\Components\Split::make([
  87. Forms\Components\Group::make([
  88. Forms\Components\Select::make('client_id')
  89. ->relationship('client', 'name')
  90. ->preload()
  91. ->searchable()
  92. ->required()
  93. ->live()
  94. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  95. if (! $state) {
  96. return;
  97. }
  98. $currencyCode = Client::find($state)?->currency_code;
  99. if ($currencyCode) {
  100. $set('currency_code', $currencyCode);
  101. }
  102. }),
  103. CreateCurrencySelect::make('currency_code'),
  104. ]),
  105. Forms\Components\Group::make([
  106. Forms\Components\TextInput::make('estimate_number')
  107. ->label('Estimate Number')
  108. ->default(fn () => Estimate::getNextDocumentNumber()),
  109. Forms\Components\TextInput::make('reference_number')
  110. ->label('Reference Number'),
  111. Forms\Components\DatePicker::make('date')
  112. ->label('Estimate Date')
  113. ->live()
  114. ->default(now())
  115. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  116. $date = $state;
  117. $expirationDate = $get('expiration_date');
  118. if ($date && $expirationDate && $date > $expirationDate) {
  119. $set('expiration_date', $date);
  120. }
  121. }),
  122. Forms\Components\DatePicker::make('expiration_date')
  123. ->label('Expiration Date')
  124. ->default(function () use ($company) {
  125. return now()->addDays($company->defaultInvoice->payment_terms->getDays());
  126. })
  127. ->minDate(static function (Forms\Get $get) {
  128. return $get('date') ?? now();
  129. }),
  130. Forms\Components\Select::make('discount_method')
  131. ->label('Discount Method')
  132. ->options(DocumentDiscountMethod::class)
  133. ->selectablePlaceholder(false)
  134. ->default(DocumentDiscountMethod::PerLineItem)
  135. ->afterStateUpdated(function ($state, Forms\Set $set) {
  136. $discountMethod = DocumentDiscountMethod::parse($state);
  137. if ($discountMethod->isPerDocument()) {
  138. $set('lineItems.*.salesDiscounts', []);
  139. }
  140. })
  141. ->live(),
  142. ])->grow(true),
  143. ])->from('md'),
  144. TableRepeater::make('lineItems')
  145. ->relationship()
  146. ->saveRelationshipsUsing(null)
  147. ->dehydrated(true)
  148. ->headers(function (Forms\Get $get) {
  149. $hasDiscounts = DocumentDiscountMethod::parse($get('discount_method'))->isPerLineItem();
  150. $headers = [
  151. Header::make('Items')->width($hasDiscounts ? '15%' : '20%'),
  152. Header::make('Description')->width($hasDiscounts ? '25%' : '30%'), // Increase when no discounts
  153. Header::make('Quantity')->width('10%'),
  154. Header::make('Price')->width('10%'),
  155. Header::make('Taxes')->width($hasDiscounts ? '15%' : '20%'), // Increase when no discounts
  156. ];
  157. if ($hasDiscounts) {
  158. $headers[] = Header::make('Discounts')->width('15%');
  159. }
  160. $headers[] = Header::make('Amount')->width('10%')->align('right');
  161. return $headers;
  162. })
  163. ->schema([
  164. Forms\Components\Select::make('offering_id')
  165. ->relationship('sellableOffering', 'name')
  166. ->preload()
  167. ->searchable()
  168. ->required()
  169. ->live()
  170. ->afterStateUpdated(function (Forms\Set $set, Forms\Get $get, $state) {
  171. $offeringId = $state;
  172. $offeringRecord = Offering::with(['salesTaxes', 'salesDiscounts'])->find($offeringId);
  173. if ($offeringRecord) {
  174. $set('description', $offeringRecord->description);
  175. $set('unit_price', $offeringRecord->price);
  176. $set('salesTaxes', $offeringRecord->salesTaxes->pluck('id')->toArray());
  177. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  178. if ($discountMethod->isPerLineItem()) {
  179. $set('salesDiscounts', $offeringRecord->salesDiscounts->pluck('id')->toArray());
  180. }
  181. }
  182. }),
  183. Forms\Components\TextInput::make('description'),
  184. Forms\Components\TextInput::make('quantity')
  185. ->required()
  186. ->numeric()
  187. ->live()
  188. ->default(1),
  189. Forms\Components\TextInput::make('unit_price')
  190. ->hiddenLabel()
  191. ->numeric()
  192. ->live()
  193. ->default(0),
  194. Forms\Components\Select::make('salesTaxes')
  195. ->relationship('salesTaxes', 'name')
  196. ->saveRelationshipsUsing(null)
  197. ->dehydrated(true)
  198. ->preload()
  199. ->multiple()
  200. ->live()
  201. ->searchable(),
  202. Forms\Components\Select::make('salesDiscounts')
  203. ->relationship('salesDiscounts', 'name')
  204. ->saveRelationshipsUsing(null)
  205. ->dehydrated(true)
  206. ->preload()
  207. ->multiple()
  208. ->live()
  209. ->hidden(function (Forms\Get $get) {
  210. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  211. return $discountMethod->isPerDocument();
  212. })
  213. ->searchable(),
  214. Forms\Components\Placeholder::make('total')
  215. ->hiddenLabel()
  216. ->extraAttributes(['class' => 'text-left sm:text-right'])
  217. ->content(function (Forms\Get $get) {
  218. $quantity = max((float) ($get('quantity') ?? 0), 0);
  219. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  220. $salesTaxes = $get('salesTaxes') ?? [];
  221. $salesDiscounts = $get('salesDiscounts') ?? [];
  222. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  223. $subtotal = $quantity * $unitPrice;
  224. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  225. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  226. ->get()
  227. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  228. if ($adjustment->computation->isPercentage()) {
  229. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  230. } else {
  231. return $adjustment->getRawOriginal('rate');
  232. }
  233. });
  234. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  235. ->get()
  236. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  237. if ($adjustment->computation->isPercentage()) {
  238. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  239. } else {
  240. return $adjustment->getRawOriginal('rate');
  241. }
  242. });
  243. // Final total
  244. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  245. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  246. }),
  247. ]),
  248. DocumentTotals::make()
  249. ->type(DocumentType::Estimate),
  250. Forms\Components\Textarea::make('terms')
  251. ->columnSpanFull(),
  252. ]),
  253. Forms\Components\Section::make('Estimate Footer')
  254. ->collapsible()
  255. ->collapsed()
  256. ->schema([
  257. Forms\Components\Textarea::make('footer')
  258. ->columnSpanFull(),
  259. ]),
  260. ]);
  261. }
  262. public static function table(Table $table): Table
  263. {
  264. return $table
  265. ->defaultSort('expiration_date')
  266. ->columns([
  267. Tables\Columns\TextColumn::make('id')
  268. ->label('ID')
  269. ->sortable()
  270. ->toggleable(isToggledHiddenByDefault: true)
  271. ->searchable(),
  272. Tables\Columns\TextColumn::make('status')
  273. ->badge()
  274. ->searchable(),
  275. Tables\Columns\TextColumn::make('expiration_date')
  276. ->label('Expiration Date')
  277. ->asRelativeDay()
  278. ->sortable(),
  279. Tables\Columns\TextColumn::make('date')
  280. ->date()
  281. ->sortable(),
  282. Tables\Columns\TextColumn::make('estimate_number')
  283. ->label('Number')
  284. ->searchable()
  285. ->sortable(),
  286. Tables\Columns\TextColumn::make('client.name')
  287. ->sortable()
  288. ->searchable(),
  289. Tables\Columns\TextColumn::make('total')
  290. ->currencyWithConversion(static fn (Estimate $record) => $record->currency_code)
  291. ->sortable()
  292. ->toggleable(),
  293. ])
  294. ->filters([
  295. Tables\Filters\SelectFilter::make('client')
  296. ->relationship('client', 'name')
  297. ->searchable()
  298. ->preload(),
  299. Tables\Filters\SelectFilter::make('status')
  300. ->options(EstimateStatus::class)
  301. ->native(false),
  302. DateRangeFilter::make('date')
  303. ->fromLabel('From Date')
  304. ->untilLabel('To Date')
  305. ->indicatorLabel('Date'),
  306. DateRangeFilter::make('expiration_date')
  307. ->fromLabel('From Expiration Date')
  308. ->untilLabel('To Expiration Date')
  309. ->indicatorLabel('Due'),
  310. ])
  311. ->actions([
  312. Tables\Actions\ActionGroup::make([
  313. Tables\Actions\EditAction::make(),
  314. Tables\Actions\ViewAction::make(),
  315. Tables\Actions\DeleteAction::make(),
  316. Estimate::getReplicateAction(Tables\Actions\ReplicateAction::class),
  317. Estimate::getApproveDraftAction(Tables\Actions\Action::class),
  318. Estimate::getMarkAsSentAction(Tables\Actions\Action::class),
  319. Estimate::getMarkAsAcceptedAction(Tables\Actions\Action::class),
  320. Estimate::getMarkAsDeclinedAction(Tables\Actions\Action::class),
  321. Estimate::getConvertToInvoiceAction(Tables\Actions\Action::class),
  322. ]),
  323. ])
  324. ->bulkActions([
  325. Tables\Actions\BulkActionGroup::make([
  326. Tables\Actions\DeleteBulkAction::make(),
  327. ReplicateBulkAction::make()
  328. ->label('Replicate')
  329. ->modalWidth(MaxWidth::Large)
  330. ->modalDescription('Replicating estimates will also replicate their line items. Are you sure you want to proceed?')
  331. ->successNotificationTitle('Estimates Replicated Successfully')
  332. ->failureNotificationTitle('Failed to Replicate Estimates')
  333. ->databaseTransaction()
  334. ->deselectRecordsAfterCompletion()
  335. ->excludeAttributes([
  336. 'estimate_number',
  337. 'date',
  338. 'expiration_date',
  339. 'approved_at',
  340. 'accepted_at',
  341. 'declined_at',
  342. 'last_sent_at',
  343. 'last_viewed_at',
  344. 'status',
  345. 'created_by',
  346. 'updated_by',
  347. 'created_at',
  348. 'updated_at',
  349. ])
  350. ->beforeReplicaSaved(function (Estimate $replica) {
  351. $replica->status = EstimateStatus::Draft;
  352. $replica->estimate_number = Estimate::getNextDocumentNumber();
  353. $replica->date = now();
  354. $replica->expiration_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  355. })
  356. ->withReplicatedRelationships(['lineItems'])
  357. ->withExcludedRelationshipAttributes('lineItems', [
  358. 'subtotal',
  359. 'total',
  360. 'created_by',
  361. 'updated_by',
  362. 'created_at',
  363. 'updated_at',
  364. ]),
  365. Tables\Actions\BulkAction::make('approveDrafts')
  366. ->label('Approve')
  367. ->icon('heroicon-o-check-circle')
  368. ->databaseTransaction()
  369. ->successNotificationTitle('Estimates Approved')
  370. ->failureNotificationTitle('Failed to Approve Estimates')
  371. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  372. $containsNonDrafts = $records->contains(fn (Estimate $record) => ! $record->isDraft());
  373. if ($containsNonDrafts) {
  374. Notification::make()
  375. ->title('Approval Failed')
  376. ->body('Only draft estimates can be approved. Please adjust your selection and try again.')
  377. ->persistent()
  378. ->danger()
  379. ->send();
  380. $action->cancel(true);
  381. }
  382. })
  383. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  384. $records->each(function (Estimate $record) {
  385. $record->approveDraft();
  386. });
  387. $action->success();
  388. }),
  389. Tables\Actions\BulkAction::make('markAsSent')
  390. ->label('Mark as Sent')
  391. ->icon('heroicon-o-paper-airplane')
  392. ->databaseTransaction()
  393. ->successNotificationTitle('Estimates Sent')
  394. ->failureNotificationTitle('Failed to Mark Estimates as Sent')
  395. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  396. $doesntContainUnsent = $records->contains(fn (Estimate $record) => $record->status !== EstimateStatus::Unsent);
  397. if ($doesntContainUnsent) {
  398. Notification::make()
  399. ->title('Sending Failed')
  400. ->body('Only unsent estimates can be marked as sent. Please adjust your selection and try again.')
  401. ->persistent()
  402. ->danger()
  403. ->send();
  404. $action->cancel(true);
  405. }
  406. })
  407. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  408. $records->each(function (Estimate $record) {
  409. $record->updateQuietly([
  410. 'status' => EstimateStatus::Sent,
  411. ]);
  412. });
  413. $action->success();
  414. }),
  415. Tables\Actions\BulkAction::make('markAsAccepted')
  416. ->label('Mark as Accepted')
  417. ->icon('heroicon-o-check-badge')
  418. ->databaseTransaction()
  419. ->successNotificationTitle('Estimates Accepted')
  420. ->failureNotificationTitle('Failed to Mark Estimates as Accepted')
  421. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  422. $doesntContainSent = $records->contains(fn (Estimate $record) => $record->status !== EstimateStatus::Sent || $record->isAccepted());
  423. if ($doesntContainSent) {
  424. Notification::make()
  425. ->title('Acceptance Failed')
  426. ->body('Only sent estimates that haven\'t been accepted can be marked as accepted. Please adjust your selection and try again.')
  427. ->persistent()
  428. ->danger()
  429. ->send();
  430. $action->cancel(true);
  431. }
  432. })
  433. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  434. $records->each(function (Estimate $record) {
  435. $record->markAsAccepted();
  436. });
  437. $action->success();
  438. }),
  439. Tables\Actions\BulkAction::make('markAsDeclined')
  440. ->label('Mark as Declined')
  441. ->icon('heroicon-o-x-circle')
  442. ->requiresConfirmation()
  443. ->databaseTransaction()
  444. ->color('danger')
  445. ->modalHeading('Mark Estimates as Declined')
  446. ->modalDescription('Are you sure you want to mark the selected estimates as declined? This action cannot be undone.')
  447. ->successNotificationTitle('Estimates Declined')
  448. ->failureNotificationTitle('Failed to Mark Estimates as Declined')
  449. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  450. $doesntContainSent = $records->contains(fn (Estimate $record) => $record->status !== EstimateStatus::Sent || $record->isDeclined());
  451. if ($doesntContainSent) {
  452. Notification::make()
  453. ->title('Declination Failed')
  454. ->body('Only sent estimates that haven\'t been declined can be marked as declined. Please adjust your selection and try again.')
  455. ->persistent()
  456. ->danger()
  457. ->send();
  458. $action->cancel(true);
  459. }
  460. })
  461. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  462. $records->each(function (Estimate $record) {
  463. $record->markAsDeclined();
  464. });
  465. $action->success();
  466. }),
  467. ]),
  468. ]);
  469. }
  470. public static function getRelations(): array
  471. {
  472. return [
  473. //
  474. ];
  475. }
  476. public static function getPages(): array
  477. {
  478. return [
  479. 'index' => Pages\ListEstimates::route('/'),
  480. 'create' => Pages\CreateEstimate::route('/create'),
  481. 'view' => Pages\ViewEstimate::route('/{record}'),
  482. 'edit' => Pages\EditEstimate::route('/{record}/edit'),
  483. ];
  484. }
  485. public static function getWidgets(): array
  486. {
  487. return [
  488. Widgets\EstimateOverview::class,
  489. ];
  490. }
  491. }