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

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