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

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