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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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. ->default(1),
  157. Forms\Components\TextInput::make('unit_price')
  158. ->hiddenLabel()
  159. ->numeric()
  160. ->live()
  161. ->default(0),
  162. Forms\Components\Select::make('salesTaxes')
  163. ->relationship('salesTaxes', 'name')
  164. ->saveRelationshipsUsing(null)
  165. ->dehydrated(true)
  166. ->preload()
  167. ->multiple()
  168. ->live()
  169. ->searchable(),
  170. Forms\Components\Select::make('salesDiscounts')
  171. ->relationship('salesDiscounts', 'name')
  172. ->saveRelationshipsUsing(null)
  173. ->dehydrated(true)
  174. ->preload()
  175. ->multiple()
  176. ->live()
  177. ->hidden(function (Forms\Get $get) {
  178. $discountMethod = DocumentDiscountMethod::parse($get('../../discount_method'));
  179. return $discountMethod->isPerDocument();
  180. })
  181. ->searchable(),
  182. Forms\Components\Placeholder::make('total')
  183. ->hiddenLabel()
  184. ->extraAttributes(['class' => 'text-left sm:text-right'])
  185. ->content(function (Forms\Get $get) {
  186. $quantity = max((float) ($get('quantity') ?? 0), 0);
  187. $unitPrice = max((float) ($get('unit_price') ?? 0), 0);
  188. $salesTaxes = $get('salesTaxes') ?? [];
  189. $salesDiscounts = $get('salesDiscounts') ?? [];
  190. $currencyCode = $get('../../currency_code') ?? CurrencyAccessor::getDefaultCurrency();
  191. $subtotal = $quantity * $unitPrice;
  192. $subtotalInCents = CurrencyConverter::convertToCents($subtotal, $currencyCode);
  193. $taxAmountInCents = Adjustment::whereIn('id', $salesTaxes)
  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. $discountAmountInCents = Adjustment::whereIn('id', $salesDiscounts)
  203. ->get()
  204. ->sum(function (Adjustment $adjustment) use ($subtotalInCents) {
  205. if ($adjustment->computation->isPercentage()) {
  206. return RateCalculator::calculatePercentage($subtotalInCents, $adjustment->getRawOriginal('rate'));
  207. } else {
  208. return $adjustment->getRawOriginal('rate');
  209. }
  210. });
  211. // Final total
  212. $totalInCents = $subtotalInCents + ($taxAmountInCents - $discountAmountInCents);
  213. return CurrencyConverter::formatCentsToMoney($totalInCents, $currencyCode);
  214. }),
  215. ]),
  216. DocumentTotals::make()
  217. ->type(DocumentType::Estimate),
  218. Forms\Components\Textarea::make('terms')
  219. ->default($settings->terms)
  220. ->columnSpanFull(),
  221. ]),
  222. DocumentFooterSection::make('Estimate Footer')
  223. ->defaultFooter($settings->footer),
  224. ]);
  225. }
  226. public static function table(Table $table): Table
  227. {
  228. return $table
  229. ->defaultSort('expiration_date')
  230. ->columns([
  231. Columns::id(),
  232. Tables\Columns\TextColumn::make('status')
  233. ->badge()
  234. ->searchable(),
  235. Tables\Columns\TextColumn::make('expiration_date')
  236. ->label('Expiration date')
  237. ->asRelativeDay()
  238. ->sortable(),
  239. Tables\Columns\TextColumn::make('date')
  240. ->date()
  241. ->sortable(),
  242. Tables\Columns\TextColumn::make('estimate_number')
  243. ->label('Number')
  244. ->searchable()
  245. ->sortable(),
  246. Tables\Columns\TextColumn::make('client.name')
  247. ->sortable()
  248. ->searchable(),
  249. Tables\Columns\TextColumn::make('total')
  250. ->currencyWithConversion(static fn (Estimate $record) => $record->currency_code)
  251. ->sortable()
  252. ->alignEnd(),
  253. ])
  254. ->filters([
  255. Tables\Filters\SelectFilter::make('client')
  256. ->relationship('client', 'name')
  257. ->searchable()
  258. ->preload(),
  259. Tables\Filters\SelectFilter::make('status')
  260. ->options(EstimateStatus::class)
  261. ->native(false),
  262. DateRangeFilter::make('date')
  263. ->fromLabel('From date')
  264. ->untilLabel('To date')
  265. ->indicatorLabel('Date'),
  266. DateRangeFilter::make('expiration_date')
  267. ->fromLabel('From expiration date')
  268. ->untilLabel('To expiration date')
  269. ->indicatorLabel('Due'),
  270. ])
  271. ->actions([
  272. Tables\Actions\ActionGroup::make([
  273. Tables\Actions\ActionGroup::make([
  274. Tables\Actions\EditAction::make(),
  275. Tables\Actions\ViewAction::make(),
  276. Estimate::getReplicateAction(Tables\Actions\ReplicateAction::class),
  277. Estimate::getApproveDraftAction(Tables\Actions\Action::class),
  278. Estimate::getMarkAsSentAction(Tables\Actions\Action::class),
  279. Estimate::getMarkAsAcceptedAction(Tables\Actions\Action::class),
  280. Estimate::getMarkAsDeclinedAction(Tables\Actions\Action::class),
  281. Estimate::getConvertToInvoiceAction(Tables\Actions\Action::class),
  282. ])->dropdown(false),
  283. Tables\Actions\DeleteAction::make(),
  284. ]),
  285. ])
  286. ->bulkActions([
  287. Tables\Actions\BulkActionGroup::make([
  288. Tables\Actions\DeleteBulkAction::make(),
  289. ReplicateBulkAction::make()
  290. ->label('Replicate')
  291. ->modalWidth(MaxWidth::Large)
  292. ->modalDescription('Replicating estimates will also replicate their line items. Are you sure you want to proceed?')
  293. ->successNotificationTitle('Estimates replicated successfully')
  294. ->failureNotificationTitle('Failed to replicate estimates')
  295. ->databaseTransaction()
  296. ->deselectRecordsAfterCompletion()
  297. ->excludeAttributes([
  298. 'estimate_number',
  299. 'date',
  300. 'expiration_date',
  301. 'approved_at',
  302. 'accepted_at',
  303. 'converted_at',
  304. 'declined_at',
  305. 'last_sent_at',
  306. 'last_viewed_at',
  307. 'status',
  308. 'created_by',
  309. 'updated_by',
  310. 'created_at',
  311. 'updated_at',
  312. ])
  313. ->beforeReplicaSaved(function (Estimate $replica) {
  314. $replica->status = EstimateStatus::Draft;
  315. $replica->estimate_number = Estimate::getNextDocumentNumber();
  316. $replica->date = now();
  317. $replica->expiration_date = now()->addDays($replica->company->defaultInvoice->payment_terms->getDays());
  318. })
  319. ->withReplicatedRelationships(['lineItems'])
  320. ->withExcludedRelationshipAttributes('lineItems', [
  321. 'subtotal',
  322. 'total',
  323. 'created_by',
  324. 'updated_by',
  325. 'created_at',
  326. 'updated_at',
  327. ]),
  328. Tables\Actions\BulkAction::make('approveDrafts')
  329. ->label('Approve')
  330. ->icon('heroicon-o-check-circle')
  331. ->databaseTransaction()
  332. ->successNotificationTitle('Estimates approved')
  333. ->failureNotificationTitle('Failed to approve estimates')
  334. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  335. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeApproved());
  336. if ($isInvalid) {
  337. Notification::make()
  338. ->title('Approval failed')
  339. ->body('Only draft estimates can be approved. Please adjust your selection and try again.')
  340. ->persistent()
  341. ->danger()
  342. ->send();
  343. $action->cancel(true);
  344. }
  345. })
  346. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  347. $records->each(function (Estimate $record) {
  348. $record->approveDraft();
  349. });
  350. $action->success();
  351. }),
  352. Tables\Actions\BulkAction::make('markAsSent')
  353. ->label('Mark as sent')
  354. ->icon('heroicon-o-paper-airplane')
  355. ->databaseTransaction()
  356. ->successNotificationTitle('Estimates sent')
  357. ->failureNotificationTitle('Failed to mark estimates as sent')
  358. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  359. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsSent());
  360. if ($isInvalid) {
  361. Notification::make()
  362. ->title('Sending failed')
  363. ->body('Only unsent estimates can be marked as sent. Please adjust your selection and try again.')
  364. ->persistent()
  365. ->danger()
  366. ->send();
  367. $action->cancel(true);
  368. }
  369. })
  370. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  371. $records->each(function (Estimate $record) {
  372. $record->markAsSent();
  373. });
  374. $action->success();
  375. }),
  376. Tables\Actions\BulkAction::make('markAsAccepted')
  377. ->label('Mark as accepted')
  378. ->icon('heroicon-o-check-badge')
  379. ->databaseTransaction()
  380. ->successNotificationTitle('Estimates accepted')
  381. ->failureNotificationTitle('Failed to mark estimates as accepted')
  382. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  383. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsAccepted());
  384. if ($isInvalid) {
  385. Notification::make()
  386. ->title('Acceptance failed')
  387. ->body('Only sent estimates that haven\'t been accepted can be marked as accepted. Please adjust your selection and try again.')
  388. ->persistent()
  389. ->danger()
  390. ->send();
  391. $action->cancel(true);
  392. }
  393. })
  394. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  395. $records->each(function (Estimate $record) {
  396. $record->markAsAccepted();
  397. });
  398. $action->success();
  399. }),
  400. Tables\Actions\BulkAction::make('markAsDeclined')
  401. ->label('Mark as declined')
  402. ->icon('heroicon-o-x-circle')
  403. ->requiresConfirmation()
  404. ->databaseTransaction()
  405. ->color('danger')
  406. ->modalHeading('Mark Estimates as Declined')
  407. ->modalDescription('Are you sure you want to mark the selected estimates as declined? This action cannot be undone.')
  408. ->successNotificationTitle('Estimates declined')
  409. ->failureNotificationTitle('Failed to mark estimates as declined')
  410. ->before(function (Collection $records, Tables\Actions\BulkAction $action) {
  411. $isInvalid = $records->contains(fn (Estimate $record) => ! $record->canBeMarkedAsDeclined());
  412. if ($isInvalid) {
  413. Notification::make()
  414. ->title('Declination failed')
  415. ->body('Only sent estimates that haven\'t been declined can be marked as declined. Please adjust your selection and try again.')
  416. ->persistent()
  417. ->danger()
  418. ->send();
  419. $action->cancel(true);
  420. }
  421. })
  422. ->action(function (Collection $records, Tables\Actions\BulkAction $action) {
  423. $records->each(function (Estimate $record) {
  424. $record->markAsDeclined();
  425. });
  426. $action->success();
  427. }),
  428. ]),
  429. ]);
  430. }
  431. public static function getRelations(): array
  432. {
  433. return [
  434. //
  435. ];
  436. }
  437. public static function getPages(): array
  438. {
  439. return [
  440. 'index' => Pages\ListEstimates::route('/'),
  441. 'create' => Pages\CreateEstimate::route('/create'),
  442. 'view' => Pages\ViewEstimate::route('/{record}'),
  443. 'edit' => Pages\EditEstimate::route('/{record}/edit'),
  444. ];
  445. }
  446. public static function getWidgets(): array
  447. {
  448. return [
  449. Widgets\EstimateOverview::class,
  450. ];
  451. }
  452. }