Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

EstimateResource.php 25KB

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