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

EstimateResource.php 28KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  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\Columns;
  12. use App\Filament\Tables\Filters\DateRangeFilter;
  13. use App\Models\Accounting\Adjustment;
  14. use App\Models\Accounting\Estimate;
  15. use App\Models\Common\Client;
  16. use App\Models\Common\Offering;
  17. use App\Utilities\Currency\CurrencyAccessor;
  18. use App\Utilities\Currency\CurrencyConverter;
  19. use App\Utilities\RateCalculator;
  20. use Awcodes\TableRepeater\Components\TableRepeater;
  21. use Awcodes\TableRepeater\Header;
  22. use Filament\Forms;
  23. use Filament\Forms\Components\FileUpload;
  24. use Filament\Forms\Form;
  25. use Filament\Notifications\Notification;
  26. use Filament\Resources\Resource;
  27. use Filament\Support\Enums\MaxWidth;
  28. use Filament\Tables;
  29. use Filament\Tables\Table;
  30. use Illuminate\Database\Eloquent\Collection;
  31. use Illuminate\Support\Facades\Auth;
  32. use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
  33. class EstimateResource extends Resource
  34. {
  35. protected static ?string $model = Estimate::class;
  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. Columns::id(),
  268. Tables\Columns\TextColumn::make('status')
  269. ->badge()
  270. ->searchable(),
  271. Tables\Columns\TextColumn::make('expiration_date')
  272. ->label('Expiration Date')
  273. ->asRelativeDay()
  274. ->sortable(),
  275. Tables\Columns\TextColumn::make('date')
  276. ->date()
  277. ->sortable(),
  278. Tables\Columns\TextColumn::make('estimate_number')
  279. ->label('Number')
  280. ->searchable()
  281. ->sortable(),
  282. Tables\Columns\TextColumn::make('client.name')
  283. ->sortable()
  284. ->searchable(),
  285. Tables\Columns\TextColumn::make('total')
  286. ->currencyWithConversion(static fn (Estimate $record) => $record->currency_code)
  287. ->sortable()
  288. ->alignEnd(),
  289. ])
  290. ->filters([
  291. Tables\Filters\SelectFilter::make('client')
  292. ->relationship('client', 'name')
  293. ->searchable()
  294. ->preload(),
  295. Tables\Filters\SelectFilter::make('status')
  296. ->options(EstimateStatus::class)
  297. ->native(false),
  298. DateRangeFilter::make('date')
  299. ->fromLabel('From Date')
  300. ->untilLabel('To Date')
  301. ->indicatorLabel('Date'),
  302. DateRangeFilter::make('expiration_date')
  303. ->fromLabel('From Expiration Date')
  304. ->untilLabel('To Expiration Date')
  305. ->indicatorLabel('Due'),
  306. ])
  307. ->actions([
  308. Tables\Actions\ActionGroup::make([
  309. Tables\Actions\ActionGroup::make([
  310. Tables\Actions\EditAction::make(),
  311. Tables\Actions\ViewAction::make(),
  312. Estimate::getReplicateAction(Tables\Actions\ReplicateAction::class),
  313. Estimate::getApproveDraftAction(Tables\Actions\Action::class),
  314. Estimate::getMarkAsSentAction(Tables\Actions\Action::class),
  315. Estimate::getMarkAsAcceptedAction(Tables\Actions\Action::class),
  316. Estimate::getMarkAsDeclinedAction(Tables\Actions\Action::class),
  317. Estimate::getConvertToInvoiceAction(Tables\Actions\Action::class),
  318. ])->dropdown(false),
  319. Tables\Actions\DeleteAction::make(),
  320. ]),
  321. ])
  322. ->bulkActions([
  323. Tables\Actions\BulkActionGroup::make([
  324. Tables\Actions\DeleteBulkAction::make(),
  325. ReplicateBulkAction::make()
  326. ->label('Replicate')
  327. ->modalWidth(MaxWidth::Large)
  328. ->modalDescription('Replicating estimates will also replicate their line items. Are you sure you want to proceed?')
  329. ->successNotificationTitle('Estimates Replicated Successfully')
  330. ->failureNotificationTitle('Failed to Replicate Estimates')
  331. ->databaseTransaction()
  332. ->deselectRecordsAfterCompletion()
  333. ->excludeAttributes([
  334. 'estimate_number',
  335. 'date',
  336. 'expiration_date',
  337. 'approved_at',
  338. 'accepted_at',
  339. 'converted_at',
  340. 'declined_at',
  341. 'last_sent_at',
  342. 'last_viewed_at',
  343. 'status',
  344. 'created_by',
  345. 'updated_by',
  346. 'created_at',
  347. 'updated_at',
  348. ])
  349. ->beforeReplicaSaved(function (Estimate $replica) {
  350. $replica->status = EstimateStatus::Draft;
  351. $replica->estimate_number = Estimate::getNextDocumentNumber();
  352. $replica->date = now();
  353. $replica->expiration_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  354. })
  355. ->withReplicatedRelationships(['lineItems'])
  356. ->withExcludedRelationshipAttributes('lineItems', [
  357. 'subtotal',
  358. 'total',
  359. 'created_by',
  360. 'updated_by',
  361. 'created_at',
  362. 'updated_at',
  363. ]),
  364. Tables\Actions\BulkAction::make('approveDrafts')
  365. ->label('Approve')
  366. ->icon('heroicon-o-check-circle')
  367. ->databaseTransaction()
  368. ->successNotificationTitle('Estimates Approved')
  369. ->failureNotificationTitle('Failed to Approve Estimates')
  370. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  371. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeApproved());
  372. if ($isInvalid) {
  373. Notification::make()
  374. ->title('Approval Failed')
  375. ->body('Only draft estimates can be approved. Please adjust your selection and try again.')
  376. ->persistent()
  377. ->danger()
  378. ->send();
  379. $action->cancel(true);
  380. }
  381. })
  382. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  383. $records->each(function (Estimate $record) {
  384. $record->approveDraft();
  385. });
  386. $action->success();
  387. }),
  388. Tables\Actions\BulkAction::make('markAsSent')
  389. ->label('Mark as Sent')
  390. ->icon('heroicon-o-paper-airplane')
  391. ->databaseTransaction()
  392. ->successNotificationTitle('Estimates Sent')
  393. ->failureNotificationTitle('Failed to Mark Estimates as Sent')
  394. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  395. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsSent());
  396. if ($isInvalid) {
  397. Notification::make()
  398. ->title('Sending Failed')
  399. ->body('Only unsent estimates can be marked as sent. Please adjust your selection and try again.')
  400. ->persistent()
  401. ->danger()
  402. ->send();
  403. $action->cancel(true);
  404. }
  405. })
  406. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  407. $records->each(function (Estimate $record) {
  408. $record->markAsSent();
  409. });
  410. $action->success();
  411. }),
  412. Tables\Actions\BulkAction::make('markAsAccepted')
  413. ->label('Mark as Accepted')
  414. ->icon('heroicon-o-check-badge')
  415. ->databaseTransaction()
  416. ->successNotificationTitle('Estimates Accepted')
  417. ->failureNotificationTitle('Failed to Mark Estimates as Accepted')
  418. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  419. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsAccepted());
  420. if ($isInvalid) {
  421. Notification::make()
  422. ->title('Acceptance Failed')
  423. ->body('Only sent estimates that haven\'t been accepted can be marked as accepted. Please adjust your selection and try again.')
  424. ->persistent()
  425. ->danger()
  426. ->send();
  427. $action->cancel(true);
  428. }
  429. })
  430. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  431. $records->each(function (Estimate $record) {
  432. $record->markAsAccepted();
  433. });
  434. $action->success();
  435. }),
  436. Tables\Actions\BulkAction::make('markAsDeclined')
  437. ->label('Mark as Declined')
  438. ->icon('heroicon-o-x-circle')
  439. ->requiresConfirmation()
  440. ->databaseTransaction()
  441. ->color('danger')
  442. ->modalHeading('Mark Estimates as Declined')
  443. ->modalDescription('Are you sure you want to mark the selected estimates as declined? This action cannot be undone.')
  444. ->successNotificationTitle('Estimates Declined')
  445. ->failureNotificationTitle('Failed to Mark Estimates as Declined')
  446. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  447. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsDeclined());
  448. if ($isInvalid) {
  449. Notification::make()
  450. ->title('Declination Failed')
  451. ->body('Only sent estimates that haven\'t been declined can be marked as declined. Please adjust your selection and try again.')
  452. ->persistent()
  453. ->danger()
  454. ->send();
  455. $action->cancel(true);
  456. }
  457. })
  458. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  459. $records->each(function (Estimate $record) {
  460. $record->markAsDeclined();
  461. });
  462. $action->success();
  463. }),
  464. ]),
  465. ]);
  466. }
  467. public static function getRelations(): array
  468. {
  469. return [
  470. //
  471. ];
  472. }
  473. public static function getPages(): array
  474. {
  475. return [
  476. 'index' => Pages\ListEstimates::route('/'),
  477. 'create' => Pages\CreateEstimate::route('/create'),
  478. 'view' => Pages\ViewEstimate::route('/{record}'),
  479. 'edit' => Pages\EditEstimate::route('/{record}/edit'),
  480. ];
  481. }
  482. public static function getWidgets(): array
  483. {
  484. return [
  485. Widgets\EstimateOverview::class,
  486. ];
  487. }
  488. }