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

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