選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Estimate.php 14KB

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