Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Estimate.php 15KB

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