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 16KB

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