Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Estimate.php 16KB

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