Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

EstimateResource.php 28KB

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