123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423 |
- <?php
-
- namespace App\Models\Accounting;
-
- use App\Casts\MoneyCast;
- use App\Casts\RateCast;
- use App\Collections\Accounting\DocumentCollection;
- use App\Concerns\Blamable;
- use App\Concerns\CompanyOwned;
- use App\Enums\Accounting\AdjustmentComputation;
- use App\Enums\Accounting\DocumentDiscountMethod;
- use App\Enums\Accounting\EstimateStatus;
- use App\Enums\Accounting\InvoiceStatus;
- use App\Filament\Company\Resources\Sales\EstimateResource;
- use App\Filament\Company\Resources\Sales\InvoiceResource;
- use App\Models\Common\Client;
- use App\Models\Setting\Currency;
- use App\Observers\EstimateObserver;
- use Filament\Actions\Action;
- use Filament\Actions\MountableAction;
- use Filament\Actions\ReplicateAction;
- use Illuminate\Database\Eloquent\Attributes\CollectedBy;
- use Illuminate\Database\Eloquent\Attributes\ObservedBy;
- use Illuminate\Database\Eloquent\Builder;
- use Illuminate\Database\Eloquent\Casts\Attribute;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\HasOne;
- use Illuminate\Database\Eloquent\Relations\MorphMany;
- use Illuminate\Support\Carbon;
-
- #[CollectedBy(DocumentCollection::class)]
- #[ObservedBy(EstimateObserver::class)]
- class Estimate extends Model
- {
- use Blamable;
- use CompanyOwned;
- use HasFactory;
-
- protected $fillable = [
- 'company_id',
- 'client_id',
- 'logo',
- 'header',
- 'subheader',
- 'estimate_number',
- 'reference_number',
- 'date',
- 'expiration_date',
- 'approved_at',
- 'accepted_at',
- 'converted_at',
- 'declined_at',
- 'last_sent_at',
- 'last_viewed_at',
- 'status',
- 'currency_code',
- 'discount_method',
- 'discount_computation',
- 'discount_rate',
- 'subtotal',
- 'tax_total',
- 'discount_total',
- 'total',
- 'terms',
- 'footer',
- 'created_by',
- 'updated_by',
- ];
-
- protected $casts = [
- 'date' => 'date',
- 'expiration_date' => 'date',
- 'approved_at' => 'datetime',
- 'accepted_at' => 'datetime',
- 'declined_at' => 'datetime',
- 'last_sent_at' => 'datetime',
- 'last_viewed_at' => 'datetime',
- 'status' => EstimateStatus::class,
- 'discount_method' => DocumentDiscountMethod::class,
- 'discount_computation' => AdjustmentComputation::class,
- 'discount_rate' => RateCast::class,
- 'subtotal' => MoneyCast::class,
- 'tax_total' => MoneyCast::class,
- 'discount_total' => MoneyCast::class,
- 'total' => MoneyCast::class,
- ];
-
- public function client(): BelongsTo
- {
- return $this->belongsTo(Client::class);
- }
-
- public function currency(): BelongsTo
- {
- return $this->belongsTo(Currency::class, 'currency_code', 'code');
- }
-
- public function invoice(): HasOne
- {
- return $this->hasOne(Invoice::class);
- }
-
- public function lineItems(): MorphMany
- {
- return $this->morphMany(DocumentLineItem::class, 'documentable');
- }
-
- protected function isCurrentlyExpired(): Attribute
- {
- return Attribute::get(function () {
- return $this->expiration_date?->isBefore(today()) && $this->canBeExpired();
- });
- }
-
- public function isDraft(): bool
- {
- return $this->status === EstimateStatus::Draft;
- }
-
- public function isApproved(): bool
- {
- return $this->approved_at !== null;
- }
-
- public function isAccepted(): bool
- {
- return $this->accepted_at !== null;
- }
-
- public function isDeclined(): bool
- {
- return $this->declined_at !== null;
- }
-
- public function isSent(): bool
- {
- return $this->last_sent_at !== null;
- }
-
- public function canBeExpired(): bool
- {
- return ! in_array($this->status, [
- EstimateStatus::Draft,
- EstimateStatus::Accepted,
- EstimateStatus::Declined,
- EstimateStatus::Converted,
- ]);
- }
-
- public function scopeActive(Builder $query): Builder
- {
- return $query->whereIn('status', [
- EstimateStatus::Unsent,
- EstimateStatus::Sent,
- EstimateStatus::Viewed,
- EstimateStatus::Accepted,
- ]);
- }
-
- public static function getNextDocumentNumber(): string
- {
- $company = auth()->user()->currentCompany;
-
- if (! $company) {
- throw new \RuntimeException('No current company is set for the user.');
- }
-
- $defaultEstimateSettings = $company->defaultInvoice;
-
- $numberPrefix = 'EST-';
- $numberDigits = $defaultEstimateSettings->number_digits;
-
- $latestDocument = static::query()
- ->whereNotNull('estimate_number')
- ->latest('estimate_number')
- ->first();
-
- $lastNumberNumericPart = $latestDocument
- ? (int) substr($latestDocument->estimate_number, strlen($numberPrefix))
- : 0;
-
- $numberNext = $lastNumberNumericPart + 1;
-
- return $defaultEstimateSettings->getNumberNext(
- padded: true,
- format: true,
- prefix: $numberPrefix,
- digits: $numberDigits,
- next: $numberNext
- );
- }
-
- public function approveDraft(?Carbon $approvedAt = null): void
- {
- if (! $this->isDraft()) {
- throw new \RuntimeException('Estimate is not in draft status.');
- }
-
- $approvedAt ??= now();
-
- $this->update([
- 'approved_at' => $approvedAt,
- 'status' => EstimateStatus::Unsent,
- ]);
- }
-
- public static function getApproveDraftAction(string $action = Action::class): MountableAction
- {
- return $action::make('approveDraft')
- ->label('Approve')
- ->icon('heroicon-o-check-circle')
- ->visible(function (self $record) {
- return $record->isDraft();
- })
- ->databaseTransaction()
- ->successNotificationTitle('Estimate Approved')
- ->action(function (self $record, MountableAction $action) {
- $record->approveDraft();
-
- $action->success();
- });
- }
-
- public static function getMarkAsSentAction(string $action = Action::class): MountableAction
- {
- return $action::make('markAsSent')
- ->label('Mark as Sent')
- ->icon('heroicon-o-paper-airplane')
- ->visible(static function (self $record) {
- return ! $record->isSent();
- })
- ->successNotificationTitle('Estimate Sent')
- ->action(function (self $record, MountableAction $action) {
- $record->markAsSent();
-
- $action->success();
- });
- }
-
- public function markAsSent(?Carbon $sentAt = null): void
- {
- $sentAt ??= now();
-
- $this->update([
- 'status' => EstimateStatus::Sent,
- 'last_sent_at' => $sentAt,
- ]);
- }
-
- public static function getReplicateAction(string $action = ReplicateAction::class): MountableAction
- {
- return $action::make()
- ->excludeAttributes([
- 'estimate_number',
- 'date',
- 'expiration_date',
- 'approved_at',
- 'accepted_at',
- 'declined_at',
- 'last_sent_at',
- 'last_viewed_at',
- 'status',
- 'created_by',
- 'updated_by',
- 'created_at',
- 'updated_at',
- ])
- ->modal(false)
- ->beforeReplicaSaved(function (self $original, self $replica) {
- $replica->status = EstimateStatus::Draft;
- $replica->estimate_number = self::getNextDocumentNumber();
- $replica->date = now();
- $replica->expiration_date = now()->addDays($original->company->defaultInvoice->payment_terms->getDays());
- })
- ->databaseTransaction()
- ->after(function (self $original, self $replica) {
- $original->replicateLineItems($replica);
- })
- ->successRedirectUrl(static function (self $replica) {
- return EstimateResource::getUrl('edit', ['record' => $replica]);
- });
- }
-
- public static function getMarkAsAcceptedAction(string $action = Action::class): MountableAction
- {
- return $action::make('markAsAccepted')
- ->label('Mark as Accepted')
- ->icon('heroicon-o-check-badge')
- ->visible(static function (self $record) {
- return $record->isSent() && ! $record->isAccepted();
- })
- ->databaseTransaction()
- ->successNotificationTitle('Estimate Accepted')
- ->action(function (self $record, MountableAction $action) {
- $record->markAsAccepted();
-
- $action->success();
- });
- }
-
- public function markAsAccepted(?Carbon $acceptedAt = null): void
- {
- $acceptedAt ??= now();
-
- $this->update([
- 'status' => EstimateStatus::Accepted,
- 'accepted_at' => $acceptedAt,
- ]);
- }
-
- public static function getMarkAsDeclinedAction(string $action = Action::class): MountableAction
- {
- return $action::make('markAsDeclined')
- ->label('Mark as Declined')
- ->icon('heroicon-o-x-circle')
- ->visible(static function (self $record) {
- return $record->isSent() && ! $record->isDeclined();
- })
- ->color('danger')
- ->requiresConfirmation()
- ->databaseTransaction()
- ->successNotificationTitle('Estimate Declined')
- ->action(function (self $record, MountableAction $action) {
- $record->markAsDeclined();
-
- $action->success();
- });
- }
-
- public function markAsDeclined(?Carbon $declinedAt = null): void
- {
- $declinedAt ??= now();
-
- $this->update([
- 'status' => EstimateStatus::Declined,
- 'declined_at' => $declinedAt,
- ]);
- }
-
- public static function getConvertToInvoiceAction(string $action = Action::class): MountableAction
- {
- return $action::make('convertToInvoice')
- ->label('Convert to Invoice')
- ->icon('heroicon-o-arrow-right-on-rectangle')
- ->visible(static function (self $record) {
- return $record->status === EstimateStatus::Accepted && ! $record->invoice;
- })
- ->databaseTransaction()
- ->successNotificationTitle('Estimate Converted to Invoice')
- ->action(function (self $record, MountableAction $action) {
- $record->convertToInvoice();
-
- $action->success();
- })
- ->successRedirectUrl(static function (self $record) {
- return InvoiceResource::getUrl('edit', ['record' => $record->refresh()->invoice]);
- });
- }
-
- public function convertToInvoice(?Carbon $convertedAt = null): void
- {
- if ($this->invoice) {
- throw new \RuntimeException('Estimate has already been converted to an invoice.');
- }
-
- $invoice = $this->invoice()->create([
- 'company_id' => $this->company_id,
- 'client_id' => $this->client_id,
- 'logo' => $this->logo,
- 'header' => $this->company->defaultInvoice->header,
- 'subheader' => $this->company->defaultInvoice->subheader,
- 'invoice_number' => Invoice::getNextDocumentNumber($this->company),
- 'date' => now(),
- 'due_date' => now()->addDays($this->company->defaultInvoice->payment_terms->getDays()),
- 'status' => InvoiceStatus::Draft,
- 'currency_code' => $this->currency_code,
- 'discount_method' => $this->discount_method,
- 'discount_computation' => $this->discount_computation,
- 'discount_rate' => $this->discount_rate,
- 'subtotal' => $this->subtotal,
- 'tax_total' => $this->tax_total,
- 'discount_total' => $this->discount_total,
- 'total' => $this->total,
- 'terms' => $this->terms,
- 'footer' => $this->footer,
- 'created_by' => auth()->id(),
- 'updated_by' => auth()->id(),
- ]);
-
- $this->replicateLineItems($invoice);
-
- $convertedAt ??= now();
-
- $this->update([
- 'status' => EstimateStatus::Converted,
- 'converted_at' => $convertedAt,
- ]);
- }
-
- public function replicateLineItems(Model $target): void
- {
- $this->lineItems->each(function (DocumentLineItem $lineItem) use ($target) {
- $replica = $lineItem->replicate([
- 'documentable_id',
- 'documentable_type',
- 'subtotal',
- 'total',
- 'created_by',
- 'updated_by',
- 'created_at',
- 'updated_at',
- ]);
-
- $replica->documentable_id = $target->id;
- $replica->documentable_type = $target->getMorphClass();
- $replica->save();
-
- $replica->adjustments()->sync($lineItem->adjustments->pluck('id'));
- });
- }
- }
|