Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

EstimateResource.php 26KB

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