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.

Estimate.php 15KB

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\Builder;
  23. use Illuminate\Database\Eloquent\Casts\Attribute;
  24. use Illuminate\Database\Eloquent\Model;
  25. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  26. use Illuminate\Database\Eloquent\Relations\HasOne;
  27. use Illuminate\Support\Carbon;
  28. use Illuminate\Support\Facades\Storage;
  29. use Livewire\Component;
  30. #[CollectedBy(DocumentCollection::class)]
  31. #[ObservedBy(EstimateObserver::class)]
  32. class Estimate extends Document
  33. {
  34. protected $fillable = [
  35. 'company_id',
  36. 'client_id',
  37. 'logo',
  38. 'header',
  39. 'subheader',
  40. 'estimate_number',
  41. 'reference_number',
  42. 'date',
  43. 'expiration_date',
  44. 'approved_at',
  45. 'accepted_at',
  46. 'converted_at',
  47. 'declined_at',
  48. 'last_sent_at',
  49. 'last_viewed_at',
  50. 'status',
  51. 'currency_code',
  52. 'discount_method',
  53. 'discount_computation',
  54. 'discount_rate',
  55. 'subtotal',
  56. 'tax_total',
  57. 'discount_total',
  58. 'total',
  59. 'terms',
  60. 'footer',
  61. 'created_by',
  62. 'updated_by',
  63. ];
  64. protected $casts = [
  65. 'date' => 'date',
  66. 'expiration_date' => 'date',
  67. 'approved_at' => 'datetime',
  68. 'accepted_at' => 'datetime',
  69. 'declined_at' => 'datetime',
  70. 'last_sent_at' => 'datetime',
  71. 'last_viewed_at' => 'datetime',
  72. 'status' => EstimateStatus::class,
  73. 'discount_method' => DocumentDiscountMethod::class,
  74. 'discount_computation' => AdjustmentComputation::class,
  75. 'discount_rate' => RateCast::class,
  76. ];
  77. protected $appends = [
  78. 'logo_url',
  79. ];
  80. protected function logoUrl(): Attribute
  81. {
  82. return Attribute::get(static function (mixed $value, array $attributes): ?string {
  83. return $attributes['logo'] ? Storage::disk('public')->url($attributes['logo']) : null;
  84. });
  85. }
  86. public function client(): BelongsTo
  87. {
  88. return $this->belongsTo(Client::class);
  89. }
  90. public function invoice(): HasOne
  91. {
  92. return $this->hasOne(Invoice::class);
  93. }
  94. public static function documentType(): DocumentType
  95. {
  96. return DocumentType::Estimate;
  97. }
  98. public function documentNumber(): ?string
  99. {
  100. return $this->estimate_number;
  101. }
  102. public function documentDate(): ?string
  103. {
  104. return $this->date?->toDateString();
  105. }
  106. public function dueDate(): ?string
  107. {
  108. return $this->expiration_date?->toDateString();
  109. }
  110. public function referenceNumber(): ?string
  111. {
  112. return $this->reference_number;
  113. }
  114. public function amountDue(): ?string
  115. {
  116. return $this->total;
  117. }
  118. protected function isCurrentlyExpired(): Attribute
  119. {
  120. return Attribute::get(function () {
  121. return $this->expiration_date?->isBefore(today());
  122. });
  123. }
  124. public function isDraft(): bool
  125. {
  126. return $this->status === EstimateStatus::Draft;
  127. }
  128. public function wasApproved(): bool
  129. {
  130. return $this->approved_at !== null;
  131. }
  132. public function wasAccepted(): bool
  133. {
  134. return $this->accepted_at !== null;
  135. }
  136. public function wasDeclined(): bool
  137. {
  138. return $this->declined_at !== null;
  139. }
  140. public function wasConverted(): bool
  141. {
  142. return $this->converted_at !== null;
  143. }
  144. public function hasBeenSent(): bool
  145. {
  146. return $this->last_sent_at !== null;
  147. }
  148. public function hasBeenViewed(): bool
  149. {
  150. return $this->last_viewed_at !== null;
  151. }
  152. public function canBeExpired(): bool
  153. {
  154. return ! in_array($this->status, [
  155. EstimateStatus::Draft,
  156. EstimateStatus::Accepted,
  157. EstimateStatus::Declined,
  158. EstimateStatus::Converted,
  159. EstimateStatus::Expired,
  160. ]);
  161. }
  162. public function canBeApproved(): bool
  163. {
  164. return $this->isDraft() && ! $this->wasApproved();
  165. }
  166. public function canBeConverted(): bool
  167. {
  168. return $this->wasAccepted() && ! $this->wasConverted();
  169. }
  170. public function canBeMarkedAsDeclined(): bool
  171. {
  172. return $this->hasBeenSent()
  173. && ! $this->wasDeclined()
  174. && ! $this->wasConverted()
  175. && ! $this->wasAccepted();
  176. }
  177. public function canBeMarkedAsSent(): bool
  178. {
  179. return ! $this->hasBeenSent();
  180. }
  181. public function canBeMarkedAsAccepted(): bool
  182. {
  183. return $this->hasBeenSent()
  184. && ! $this->wasAccepted()
  185. && ! $this->wasDeclined()
  186. && ! $this->wasConverted();
  187. }
  188. public function scopeActive(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 ??= 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 ??= 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 ??= 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 = now();
  313. $replica->expiration_date = now()->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 ??= 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 ??= 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' => now(),
  402. 'due_date' => now()->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 ??= 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. }