Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

Estimate.php 14KB

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