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

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