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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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 isApproved(): bool
  111. {
  112. return $this->approved_at !== null;
  113. }
  114. public function isAccepted(): bool
  115. {
  116. return $this->accepted_at !== null;
  117. }
  118. public function isDeclined(): bool
  119. {
  120. return $this->declined_at !== null;
  121. }
  122. public function isSent(): bool
  123. {
  124. return $this->last_sent_at !== null;
  125. }
  126. public function canBeExpired(): bool
  127. {
  128. return ! in_array($this->status, [
  129. EstimateStatus::Draft,
  130. EstimateStatus::Accepted,
  131. EstimateStatus::Declined,
  132. EstimateStatus::Converted,
  133. ]);
  134. }
  135. public function scopeActive(Builder $query): Builder
  136. {
  137. return $query->whereIn('status', [
  138. EstimateStatus::Unsent,
  139. EstimateStatus::Sent,
  140. EstimateStatus::Viewed,
  141. EstimateStatus::Accepted,
  142. ]);
  143. }
  144. public static function getNextDocumentNumber(): string
  145. {
  146. $company = auth()->user()->currentCompany;
  147. if (! $company) {
  148. throw new \RuntimeException('No current company is set for the user.');
  149. }
  150. $defaultEstimateSettings = $company->defaultInvoice;
  151. $numberPrefix = 'EST-';
  152. $numberDigits = $defaultEstimateSettings->number_digits;
  153. $latestDocument = static::query()
  154. ->whereNotNull('estimate_number')
  155. ->latest('estimate_number')
  156. ->first();
  157. $lastNumberNumericPart = $latestDocument
  158. ? (int) substr($latestDocument->estimate_number, strlen($numberPrefix))
  159. : 0;
  160. $numberNext = $lastNumberNumericPart + 1;
  161. return $defaultEstimateSettings->getNumberNext(
  162. padded: true,
  163. format: true,
  164. prefix: $numberPrefix,
  165. digits: $numberDigits,
  166. next: $numberNext
  167. );
  168. }
  169. public function approveDraft(?Carbon $approvedAt = null): void
  170. {
  171. if (! $this->isDraft()) {
  172. throw new \RuntimeException('Estimate is not in draft status.');
  173. }
  174. $approvedAt ??= now();
  175. $this->update([
  176. 'approved_at' => $approvedAt,
  177. 'status' => EstimateStatus::Unsent,
  178. ]);
  179. }
  180. public static function getApproveDraftAction(string $action = Action::class): MountableAction
  181. {
  182. return $action::make('approveDraft')
  183. ->label('Approve')
  184. ->icon('heroicon-o-check-circle')
  185. ->visible(function (self $record) {
  186. return $record->isDraft();
  187. })
  188. ->databaseTransaction()
  189. ->successNotificationTitle('Estimate Approved')
  190. ->action(function (self $record, MountableAction $action) {
  191. $record->approveDraft();
  192. $action->success();
  193. });
  194. }
  195. public static function getMarkAsSentAction(string $action = Action::class): MountableAction
  196. {
  197. return $action::make('markAsSent')
  198. ->label('Mark as Sent')
  199. ->icon('heroicon-o-paper-airplane')
  200. ->visible(static function (self $record) {
  201. return ! $record->isSent();
  202. })
  203. ->successNotificationTitle('Estimate Sent')
  204. ->action(function (self $record, MountableAction $action) {
  205. $record->markAsSent();
  206. $action->success();
  207. });
  208. }
  209. public function markAsSent(?Carbon $sentAt = null): void
  210. {
  211. $sentAt ??= now();
  212. $this->update([
  213. 'status' => EstimateStatus::Sent,
  214. 'last_sent_at' => $sentAt,
  215. ]);
  216. }
  217. public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
  218. {
  219. return $action::make()
  220. ->excludeAttributes([
  221. 'estimate_number',
  222. 'date',
  223. 'expiration_date',
  224. 'approved_at',
  225. 'accepted_at',
  226. 'declined_at',
  227. 'last_sent_at',
  228. 'last_viewed_at',
  229. 'status',
  230. 'created_by',
  231. 'updated_by',
  232. 'created_at',
  233. 'updated_at',
  234. ])
  235. ->modal(false)
  236. ->beforeReplicaSaved(function (self $original, self $replica) {
  237. $replica->status = EstimateStatus::Draft;
  238. $replica->estimate_number = self::getNextDocumentNumber();
  239. $replica->date = now();
  240. $replica->expiration_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
  241. })
  242. ->databaseTransaction()
  243. ->after(function (self $original, self $replica) {
  244. $original->replicateLineItems($replica);
  245. })
  246. ->successRedirectUrl(static function (self $replica) {
  247. return EstimateResource::getUrl('edit', ['record' => $replica]);
  248. });
  249. }
  250. public static function getMarkAsAcceptedAction(string $action = Action::class): MountableAction
  251. {
  252. return $action::make('markAsAccepted')
  253. ->label('Mark as Accepted')
  254. ->icon('heroicon-o-check-badge')
  255. ->visible(static function (self $record) {
  256. return $record->isSent() && ! $record->isAccepted();
  257. })
  258. ->databaseTransaction()
  259. ->successNotificationTitle('Estimate Accepted')
  260. ->action(function (self $record, MountableAction $action) {
  261. $record->markAsAccepted();
  262. $action->success();
  263. });
  264. }
  265. public function markAsAccepted(?Carbon $acceptedAt = null): void
  266. {
  267. $acceptedAt ??= now();
  268. $this->update([
  269. 'status' => EstimateStatus::Accepted,
  270. 'accepted_at' => $acceptedAt,
  271. ]);
  272. }
  273. public static function getMarkAsDeclinedAction(string $action = Action::class): MountableAction
  274. {
  275. return $action::make('markAsDeclined')
  276. ->label('Mark as Declined')
  277. ->icon('heroicon-o-x-circle')
  278. ->visible(static function (self $record) {
  279. return $record->isSent() && ! $record->isDeclined();
  280. })
  281. ->color('danger')
  282. ->requiresConfirmation()
  283. ->databaseTransaction()
  284. ->successNotificationTitle('Estimate Declined')
  285. ->action(function (self $record, MountableAction $action) {
  286. $record->markAsDeclined();
  287. $action->success();
  288. });
  289. }
  290. public function markAsDeclined(?Carbon $declinedAt = null): void
  291. {
  292. $declinedAt ??= now();
  293. $this->update([
  294. 'status' => EstimateStatus::Declined,
  295. 'declined_at' => $declinedAt,
  296. ]);
  297. }
  298. public static function getConvertToInvoiceAction(string $action = Action::class): MountableAction
  299. {
  300. return $action::make('convertToInvoice')
  301. ->label('Convert to Invoice')
  302. ->icon('heroicon-o-arrow-right-on-rectangle')
  303. ->visible(static function (self $record) {
  304. return $record->status === EstimateStatus::Accepted && ! $record->invoice;
  305. })
  306. ->databaseTransaction()
  307. ->successNotificationTitle('Estimate Converted to Invoice')
  308. ->action(function (self $record, MountableAction $action) {
  309. $record->convertToInvoice();
  310. $action->success();
  311. })
  312. ->successRedirectUrl(static function (self $record) {
  313. return InvoiceResource::getUrl('edit', ['record' => $record->refresh()->invoice]);
  314. });
  315. }
  316. public function convertToInvoice(?Carbon $convertedAt = null): void
  317. {
  318. if ($this->invoice) {
  319. throw new \RuntimeException('Estimate has already been converted to an invoice.');
  320. }
  321. $invoice = $this->invoice()->create([
  322. 'company_id' => $this->company_id,
  323. 'client_id' => $this->client_id,
  324. 'logo' => $this->logo,
  325. 'header' => $this->company->defaultInvoice->header,
  326. 'subheader' => $this->company->defaultInvoice->subheader,
  327. 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
  328. 'date' => now(),
  329. 'due_date' => now()->addDays($this->company->defaultInvoice->payment_terms->getDays()),
  330. 'status' => InvoiceStatus::Draft,
  331. 'currency_code' => $this->currency_code,
  332. 'discount_method' => $this->discount_method,
  333. 'discount_computation' => $this->discount_computation,
  334. 'discount_rate' => $this->discount_rate,
  335. 'subtotal' => $this->subtotal,
  336. 'tax_total' => $this->tax_total,
  337. 'discount_total' => $this->discount_total,
  338. 'total' => $this->total,
  339. 'terms' => $this->terms,
  340. 'footer' => $this->footer,
  341. 'created_by' => auth()->id(),
  342. 'updated_by' => auth()->id(),
  343. ]);
  344. $this->replicateLineItems($invoice);
  345. $convertedAt ??= now();
  346. $this->update([
  347. 'status' => EstimateStatus::Converted,
  348. 'converted_at' => $convertedAt,
  349. ]);
  350. }
  351. public function replicateLineItems(Model $target): void
  352. {
  353. $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
  354. $replica = $lineItem->replicate([
  355. 'documentable_id',
  356. 'documentable_type',
  357. 'subtotal',
  358. 'total',
  359. 'created_by',
  360. 'updated_by',
  361. 'created_at',
  362. 'updated_at',
  363. ]);
  364. $replica->documentable_id = $target->id;
  365. $replica->documentable_type = $target->getMorphClass();
  366. $replica->save();
  367. $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
  368. });
  369. }
  370. }