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

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