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

Estimate.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. <?php
  2. namespace App\Models\Accounting;
  3. use App\Casts\RateCast;
  4. use App\Collections\Accounting\DocumentCollection;
  5. use App\Enums\Accounting\AdjustmentComputation;
  6. use App\Enums\Accounting\DocumentDiscountMethod;
  7. use App\Enums\Accounting\DocumentType;
  8. use App\Enums\Accounting\EstimateStatus;
  9. use App\Enums\Accounting\InvoiceStatus;
  10. use App\Filament\Company\Resources\Sales\EstimateResource;
  11. use App\Filament\Company\Resources\Sales\InvoiceResource;
  12. use App\Models\Common\Client;
  13. use App\Models\Company;
  14. use App\Models\Setting\DocumentDefault;
  15. use App\Observers\EstimateObserver;
  16. use Filament\Actions\Action;
  17. use Filament\Actions\MountableAction;
  18. use Filament\Actions\ReplicateAction;
  19. use Filament\Notifications\Notification;
  20. use Illuminate\Database\Eloquent\Attributes\CollectedBy;
  21. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  22. use Illuminate\Database\Eloquent\Attributes\Scope;
  23. use Illuminate\Database\Eloquent\Builder;
  24. use Illuminate\Database\Eloquent\Casts\Attribute;
  25. use Illuminate\Database\Eloquent\Model;
  26. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  27. use Illuminate\Database\Eloquent\Relations\HasOne;
  28. use Illuminate\Support\Carbon;
  29. use Illuminate\Support\Facades\Storage;
  30. use Livewire\Component;
  31. #[CollectedBy(DocumentCollection::class)]
  32. #[ObservedBy(EstimateObserver::class)]
  33. class Estimate extends Document
  34. {
  35. protected $fillable = [
  36. 'company_id',
  37. 'client_id',
  38. 'logo',
  39. 'header',
  40. 'subheader',
  41. 'estimate_number',
  42. 'reference_number',
  43. 'date',
  44. 'expiration_date',
  45. 'approved_at',
  46. 'accepted_at',
  47. 'converted_at',
  48. 'declined_at',
  49. 'last_sent_at',
  50. 'last_viewed_at',
  51. 'status',
  52. 'currency_code',
  53. 'discount_method',
  54. 'discount_computation',
  55. 'discount_rate',
  56. 'subtotal',
  57. 'tax_total',
  58. 'discount_total',
  59. 'total',
  60. 'terms',
  61. 'footer',
  62. 'created_by',
  63. 'updated_by',
  64. ];
  65. protected $casts = [
  66. 'date' => 'date',
  67. 'expiration_date' => 'date',
  68. 'approved_at' => 'datetime',
  69. 'accepted_at' => 'datetime',
  70. 'declined_at' => 'datetime',
  71. 'last_sent_at' => 'datetime',
  72. 'last_viewed_at' => 'datetime',
  73. 'status' => EstimateStatus::class,
  74. 'discount_method' => DocumentDiscountMethod::class,
  75. 'discount_computation' => AdjustmentComputation::class,
  76. 'discount_rate' => RateCast::class,
  77. ];
  78. protected $appends = [
  79. 'logo_url',
  80. ];
  81. protected function logoUrl(): Attribute
  82. {
  83. return Attribute::get(static function (mixed $value, array $attributes): ?string {
  84. return $attributes['logo'] ? Storage::disk('public')->url($attributes['logo']) : null;
  85. });
  86. }
  87. public function client(): BelongsTo
  88. {
  89. return $this->belongsTo(Client::class);
  90. }
  91. public function invoice(): HasOne
  92. {
  93. return $this->hasOne(Invoice::class);
  94. }
  95. public static function documentType(): DocumentType
  96. {
  97. return DocumentType::Estimate;
  98. }
  99. public function documentNumber(): ?string
  100. {
  101. return $this->estimate_number;
  102. }
  103. public function documentDate(): ?string
  104. {
  105. return $this->date?->toDateString();
  106. }
  107. public function dueDate(): ?string
  108. {
  109. return $this->expiration_date?->toDateString();
  110. }
  111. public function referenceNumber(): ?string
  112. {
  113. return $this->reference_number;
  114. }
  115. public function amountDue(): ?string
  116. {
  117. return $this->total;
  118. }
  119. public function shouldBeExpired(): bool
  120. {
  121. return $this->expiration_date?->isBefore(company_today()) && $this->canBeExpired();
  122. }
  123. public function isDraft(): bool
  124. {
  125. return $this->status === EstimateStatus::Draft;
  126. }
  127. public function wasApproved(): bool
  128. {
  129. return $this->approved_at !== null;
  130. }
  131. public function wasAccepted(): bool
  132. {
  133. return $this->accepted_at !== null;
  134. }
  135. public function wasDeclined(): bool
  136. {
  137. return $this->declined_at !== null;
  138. }
  139. public function wasConverted(): bool
  140. {
  141. return $this->converted_at !== null;
  142. }
  143. public function hasBeenSent(): bool
  144. {
  145. return $this->last_sent_at !== null;
  146. }
  147. public function hasBeenViewed(): bool
  148. {
  149. return $this->last_viewed_at !== null;
  150. }
  151. public function canBeExpired(): bool
  152. {
  153. return ! in_array($this->status, [
  154. EstimateStatus::Draft,
  155. EstimateStatus::Accepted,
  156. EstimateStatus::Declined,
  157. EstimateStatus::Converted,
  158. EstimateStatus::Expired,
  159. ]);
  160. }
  161. public function canBeApproved(): bool
  162. {
  163. return $this->isDraft() && ! $this->wasApproved();
  164. }
  165. public function canBeConverted(): bool
  166. {
  167. return $this->wasAccepted() && ! $this->wasConverted();
  168. }
  169. public function canBeMarkedAsDeclined(): bool
  170. {
  171. return $this->hasBeenSent()
  172. && ! $this->wasDeclined()
  173. && ! $this->wasConverted()
  174. && ! $this->wasAccepted();
  175. }
  176. public function canBeMarkedAsSent(): bool
  177. {
  178. return ! $this->hasBeenSent();
  179. }
  180. public function canBeMarkedAsAccepted(): bool
  181. {
  182. return $this->hasBeenSent()
  183. && ! $this->wasAccepted()
  184. && ! $this->wasDeclined()
  185. && ! $this->wasConverted();
  186. }
  187. #[Scope]
  188. protected function active(Builder $query): Builder
  189. {
  190. return $query->whereIn('status', [
  191. EstimateStatus::Unsent,
  192. EstimateStatus::Sent,
  193. EstimateStatus::Viewed,
  194. EstimateStatus::Accepted,
  195. ]);
  196. }
  197. public static function getNextDocumentNumber(?Company $company = null): string
  198. {
  199. $company ??= auth()->user()?->currentCompany;
  200. if (! $company) {
  201. throw new \RuntimeException('No current company is set for the user.');
  202. }
  203. $defaultEstimateSettings = $company->defaultEstimate;
  204. $numberPrefix = $defaultEstimateSettings->number_prefix ?? '';
  205. $latestDocument = static::query()
  206. ->whereNotNull('estimate_number')
  207. ->latest('estimate_number')
  208. ->first();
  209. $lastNumberNumericPart = $latestDocument
  210. ? (int) substr($latestDocument->estimate_number, strlen($numberPrefix))
  211. : DocumentDefault::getBaseNumber();
  212. $numberNext = $lastNumberNumericPart + 1;
  213. return $defaultEstimateSettings->getNumberNext(
  214. prefix: $numberPrefix,
  215. next: $numberNext
  216. );
  217. }
  218. public function approveDraft(?Carbon $approvedAt = null): void
  219. {
  220. if (! $this->isDraft()) {
  221. throw new \RuntimeException('Estimate is not in draft status.');
  222. }
  223. $approvedAt ??= company_now();
  224. $this->update([
  225. 'approved_at' => $approvedAt,
  226. 'status' => EstimateStatus::Unsent,
  227. ]);
  228. }
  229. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  230. {
  231. return $action::make('approveDraft')
  232. ->label('Approve')
  233. ->icon('heroicon-m-check-circle')
  234. ->visible(function (self $record) {
  235. return $record->canBeApproved();
  236. })
  237. ->requiresConfirmation()
  238. ->databaseTransaction()
  239. ->successNotificationTitle('Estimate approved')
  240. ->action(function (self $record, MountableAction $action, Component $livewire) {
  241. if ($record->hasInactiveAdjustments()) {
  242. $isViewPage = $livewire instanceof EstimateResource\Pages\ViewEstimate;
  243. if (! $isViewPage) {
  244. redirect(EstimateResource\Pages\ViewEstimate::getUrl(['record' => $record->id]));
  245. } else {
  246. Notification::make()
  247. ->warning()
  248. ->title('Cannot approve estimate')
  249. ->body('This estimate has inactive adjustments that must be addressed first.')
  250. ->persistent()
  251. ->send();
  252. }
  253. } else {
  254. $record->approveDraft();
  255. $action->success();
  256. }
  257. });
  258. }
  259. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  260. {
  261. return $action::make('markAsSent')
  262. ->label('Mark as sent')
  263. ->icon('heroicon-m-paper-airplane')
  264. ->visible(static function (self $record) {
  265. return $record->canBeMarkedAsSent();
  266. })
  267. ->successNotificationTitle('Estimate sent')
  268. ->action(function (self $record, MountableAction $action) {
  269. $record->markAsSent();
  270. $action->success();
  271. });
  272. }
  273. public function markAsSent(?Carbon $sentAt = null): void
  274. {
  275. $sentAt ??= company_now();
  276. $this->update([
  277. 'status' => EstimateStatus::Sent,
  278. 'last_sent_at' => $sentAt,
  279. ]);
  280. }
  281. public function markAsViewed(?Carbon $viewedAt = null): void
  282. {
  283. $viewedAt ??= company_now();
  284. $this->update([
  285. 'status' => EstimateStatus::Viewed,
  286. 'last_viewed_at' => $viewedAt,
  287. ]);
  288. }
  289. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  290. {
  291. return $action::make()
  292. ->excludeAttributes([
  293. 'estimate_number',
  294. 'date',
  295. 'expiration_date',
  296. 'approved_at',
  297. 'accepted_at',
  298. 'converted_at',
  299. 'declined_at',
  300. 'last_sent_at',
  301. 'last_viewed_at',
  302. 'status',
  303. 'created_by',
  304. 'updated_by',
  305. 'created_at',
  306. 'updated_at',
  307. ])
  308. ->modal(false)
  309. ->beforeReplicaSaved(function (self $original, self $replica) {
  310. $replica->status = EstimateStatus::Draft;
  311. $replica->estimate_number = self::getNextDocumentNumber();
  312. $replica->date = company_today();
  313. $replica->expiration_date = company_today()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  314. })
  315. ->databaseTransaction()
  316. ->after(function (self $original, self $replica) {
  317. $original->replicateLineItems($replica);
  318. })
  319. ->successRedirectUrl(static function (self $replica) {
  320. return EstimateResource::getUrl('edit', ['record' => $replica]);
  321. });
  322. }
  323. public static function getMarkAsAcceptedAction(string $action = Action::class): MountableAction
  324. {
  325. return $action::make('markAsAccepted')
  326. ->label('Mark as Accepted')
  327. ->icon('heroicon-m-check-badge')
  328. ->visible(static function (self $record) {
  329. return $record->canBeMarkedAsAccepted();
  330. })
  331. ->databaseTransaction()
  332. ->successNotificationTitle('Estimate accepted')
  333. ->action(function (self $record, MountableAction $action) {
  334. $record->markAsAccepted();
  335. $action->success();
  336. });
  337. }
  338. public function markAsAccepted(?Carbon $acceptedAt = null): void
  339. {
  340. $acceptedAt ??= company_now();
  341. $this->update([
  342. 'status' => EstimateStatus::Accepted,
  343. 'accepted_at' => $acceptedAt,
  344. ]);
  345. }
  346. public static function getMarkAsDeclinedAction(string $action = Action::class): MountableAction
  347. {
  348. return $action::make('markAsDeclined')
  349. ->label('Mark as Declined')
  350. ->icon('heroicon-m-x-circle')
  351. ->visible(static function (self $record) {
  352. return $record->canBeMarkedAsDeclined();
  353. })
  354. ->color('danger')
  355. ->requiresConfirmation()
  356. ->databaseTransaction()
  357. ->successNotificationTitle('Estimate declined')
  358. ->action(function (self $record, MountableAction $action) {
  359. $record->markAsDeclined();
  360. $action->success();
  361. });
  362. }
  363. public function markAsDeclined(?Carbon $declinedAt = null): void
  364. {
  365. $declinedAt ??= company_now();
  366. $this->update([
  367. 'status' => EstimateStatus::Declined,
  368. 'declined_at' => $declinedAt,
  369. ]);
  370. }
  371. public static function getConvertToInvoiceAction(string $action = Action::class): MountableAction
  372. {
  373. return $action::make('convertToInvoice')
  374. ->label('Convert to Invoice')
  375. ->icon('heroicon-m-arrow-right-on-rectangle')
  376. ->visible(static function (self $record) {
  377. return $record->canBeConverted();
  378. })
  379. ->databaseTransaction()
  380. ->successNotificationTitle('Estimate converted to invoice')
  381. ->action(function (self $record, MountableAction $action) {
  382. $record->convertToInvoice();
  383. $action->success();
  384. })
  385. ->successRedirectUrl(static function (self $record) {
  386. return InvoiceResource::getUrl('edit', ['record' => $record->refresh()->invoice]);
  387. });
  388. }
  389. public function convertToInvoice(?Carbon $convertedAt = null): void
  390. {
  391. if ($this->invoice) {
  392. throw new \RuntimeException('Estimate has already been converted to an invoice.');
  393. }
  394. $invoice = $this->invoice()->create([
  395. 'company_id' => $this->company_id,
  396. 'client_id' => $this->client_id,
  397. 'logo' => $this->logo,
  398. 'header' => $this->company->defaultInvoice->header,
  399. 'subheader' => $this->company->defaultInvoice->subheader,
  400. 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
  401. 'date' => company_today(),
  402. 'due_date' => company_today()->addDays($this->company->defaultInvoice->payment_terms->getDays()),
  403. 'status' => InvoiceStatus::Draft,
  404. 'currency_code' => $this->currency_code,
  405. 'discount_method' => $this->discount_method,
  406. 'discount_computation' => $this->discount_computation,
  407. 'discount_rate' => $this->getRawOriginal('discount_rate'),
  408. 'subtotal' => $this->subtotal,
  409. 'tax_total' => $this->tax_total,
  410. 'discount_total' => $this->discount_total,
  411. 'total' => $this->total,
  412. 'terms' => $this->terms,
  413. 'footer' => $this->footer,
  414. 'created_by' => auth()->id(),
  415. 'updated_by' => auth()->id(),
  416. ]);
  417. $this->replicateLineItems($invoice);
  418. $convertedAt ??= company_now();
  419. $this->update([
  420. 'status' => EstimateStatus::Converted,
  421. 'converted_at' => $convertedAt,
  422. ]);
  423. }
  424. public function replicateLineItems(Model $target): void
  425. {
  426. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  427. $replica = $lineItem->replicate([
  428. 'documentable_id',
  429. 'documentable_type',
  430. 'subtotal',
  431. 'total',
  432. 'created_by',
  433. 'updated_by',
  434. 'created_at',
  435. 'updated_at',
  436. ]);
  437. $replica->documentable_id = $target->id;
  438. $replica->documentable_type = $target->getMorphClass();
  439. $replica->save();
  440. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  441. });
  442. }
  443. }