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

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