- Buchung ist der einheitliche Vorgang: Eingangsart, Vorgangsart A1–A6, eingefrorenes Abwicklungsprofil, gespeicherter Verlauf (booking_events); Gast, Personen und Beträge dürfen unbekannt sein, Platzhalter-Gäste werden migriert und nicht mehr angelegt - Einstellungen in Ebenen: Vermieterstandard (So arbeite ich), Abweichung der Wohnung (Experte), Abweichung je Portal und Eingangsart; ersetzt booking_model als Steuergröße - Ein Weg für extern verbindliche Buchungen (TakeOverExternalBooking) statt RecordPortalBooking und "Akte anlegen"; Portalpreis als belegte Gesamtposition - Startseite "Zu erledigen", neue Vorgangsseite mit nächstem Schritt, Automatik-Schalter, "Beenden" mit Storno statt Statusumschaltung; Status von Hand nur im Expertenmodus - Migration übernimmt bisheriges Verhalten unverändert (abweichende Wohnungswerte bleiben als Abweichung), Bericht: php artisan process:settings-report Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
433 lines
13 KiB
PHP
433 lines
13 KiB
PHP
<?php
|
||
|
||
namespace App\Models;
|
||
|
||
use App\Documents\OfferTerms;
|
||
use App\Enums\BookingStatus;
|
||
use App\Enums\BookingTaskKind;
|
||
use App\Enums\CaseType;
|
||
use App\Enums\IntakeKind;
|
||
use App\Enums\ProcessingMode;
|
||
use App\Enums\ReferralSource;
|
||
use App\Enums\Responsibility;
|
||
use App\Models\Concerns\BelongsToTenant;
|
||
use App\Models\Concerns\HasChannelProvenance;
|
||
use App\Observers\BookingObserver;
|
||
use App\Process\CaseRecorder;
|
||
use App\Process\ProcessProfile;
|
||
use App\Process\ProcessSettings;
|
||
use Carbon\CarbonInterface;
|
||
use Database\Factories\BookingFactory;
|
||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||
use Illuminate\Database\Eloquent\Attributes\ObservedBy;
|
||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||
use Illuminate\Database\Eloquent\Builder;
|
||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||
use Illuminate\Database\Eloquent\Model;
|
||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||
use Illuminate\Support\HtmlString;
|
||
|
||
/**
|
||
* A case ("Vorgang", docs/Prozessarchitektur): one business occasion from its first arrival to its end – a request,
|
||
* a booking already binding on a portal, or an internal use. arrival is the first night, departure the day the guest
|
||
* leaves, so a departure and the next arrival on the same day do not collide. Guest, number of guests and amounts may
|
||
* be unknown (null) – unknown is never replaced by an invented value.
|
||
*/
|
||
#[ObservedBy(BookingObserver::class)]
|
||
#[Fillable([
|
||
'property_id',
|
||
'guest_id',
|
||
'status',
|
||
'source',
|
||
'intake',
|
||
'case_type',
|
||
'profile',
|
||
'processing_mode',
|
||
'import_channel_id',
|
||
'origin_channel_id',
|
||
'portal_reference',
|
||
'contact_requested_at',
|
||
'guest_confirmed_at',
|
||
'archived_at',
|
||
'referral_source',
|
||
'utm_source',
|
||
'utm_medium',
|
||
'utm_campaign',
|
||
'arrival',
|
||
'departure',
|
||
'guests',
|
||
'extras',
|
||
'promo_code',
|
||
'price_adjustment',
|
||
'price_adjustment_label',
|
||
'quote',
|
||
'total',
|
||
'deposit',
|
||
'deposit_due_on',
|
||
'balance_due_on',
|
||
'contract_path',
|
||
'hold_expires_at',
|
||
'offer_version',
|
||
'offer_sent_at',
|
||
'offer_message',
|
||
'offer_path',
|
||
'offer_terms',
|
||
'offer_hash',
|
||
'offer_pdf_sha256',
|
||
'contract_pdf_sha256',
|
||
'message',
|
||
'internal_notes',
|
||
'confirmed_at',
|
||
'accepted_at',
|
||
'confirmation_sent_at',
|
||
'confirmation_failed_at',
|
||
'acceptance',
|
||
'declined_by',
|
||
'cancelled_at',
|
||
'review_requested_at',
|
||
'deposit_reminded_at',
|
||
'balance_requested_at',
|
||
'balance_reminded_at',
|
||
'arrival_info_sent_at',
|
||
])]
|
||
class Booking extends Model
|
||
{
|
||
/** @use HasFactory<BookingFactory> */
|
||
use BelongsToTenant, HasChannelProvenance, HasFactory;
|
||
|
||
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email'];
|
||
|
||
public function isDirect(): bool
|
||
{
|
||
return $this->import_channel_id === null && $this->origin_channel_id === null && in_array($this->source, self::DIRECT_SOURCES, true);
|
||
}
|
||
|
||
protected static function booted(): void
|
||
{
|
||
static::saving(fn (Booking $booking) => CaseRecorder::freeze($booking));
|
||
static::created(function (Booking $booking): void {
|
||
$booking->forceFill(['reference' => $booking->nextReference()])->saveQuietly();
|
||
CaseRecorder::created($booking);
|
||
});
|
||
static::updated(fn (Booking $booking) => CaseRecorder::updated($booking));
|
||
}
|
||
|
||
/**
|
||
* Next booking number of this landlord in the year of creation, continuing after the highest
|
||
* number already issued. Existing numbers are never rewritten.
|
||
*/
|
||
public function nextReference(): string
|
||
{
|
||
$year = $this->created_at->format('Y');
|
||
|
||
$references = static::withoutGlobalScope('tenant')
|
||
->where('tenant_id', $this->tenant_id)
|
||
->where('reference', 'like', $year.'-%')
|
||
->whereKeyNot($this->id)
|
||
->lockForUpdate()
|
||
->pluck('reference');
|
||
|
||
$number = 1;
|
||
|
||
foreach ($references as $reference) {
|
||
if (is_string($reference) && preg_match('/-(\d+)$/', $reference, $match) === 1) {
|
||
$number = max($number, ((int) $match[1]) + 1);
|
||
}
|
||
}
|
||
|
||
return $year.'-'.str_pad((string) $number, 4, '0', STR_PAD_LEFT);
|
||
}
|
||
|
||
/**
|
||
* Get the attributes that should be cast.
|
||
*
|
||
* @return array<string, string>
|
||
*/
|
||
protected function casts(): array
|
||
{
|
||
return [
|
||
'status' => BookingStatus::class,
|
||
'intake' => IntakeKind::class,
|
||
'case_type' => CaseType::class,
|
||
'profile' => 'array',
|
||
'processing_mode' => ProcessingMode::class,
|
||
'referral_source' => ReferralSource::class,
|
||
'arrival' => 'immutable_date',
|
||
'departure' => 'immutable_date',
|
||
'extras' => 'array',
|
||
'quote' => 'array',
|
||
'deposit_due_on' => 'immutable_date',
|
||
'balance_due_on' => 'immutable_date',
|
||
'hold_expires_at' => 'immutable_datetime',
|
||
'confirmed_at' => 'immutable_datetime',
|
||
'offer_sent_at' => 'immutable_datetime',
|
||
'accepted_at' => 'immutable_datetime',
|
||
'acceptance' => 'array',
|
||
'offer_terms' => 'array',
|
||
'confirmation_sent_at' => 'immutable_datetime',
|
||
'confirmation_failed_at' => 'immutable_datetime',
|
||
'cancelled_at' => 'immutable_datetime',
|
||
'review_requested_at' => 'immutable_datetime',
|
||
'deposit_reminded_at' => 'immutable_datetime',
|
||
'balance_requested_at' => 'immutable_datetime',
|
||
'balance_reminded_at' => 'immutable_datetime',
|
||
'arrival_info_sent_at' => 'immutable_datetime',
|
||
'contact_requested_at' => 'immutable_datetime',
|
||
'guest_confirmed_at' => 'immutable_datetime',
|
||
'archived_at' => 'immutable_datetime',
|
||
];
|
||
}
|
||
|
||
/**
|
||
* @return BelongsTo<Property, $this>
|
||
*/
|
||
public function property(): BelongsTo
|
||
{
|
||
return $this->belongsTo(Property::class);
|
||
}
|
||
|
||
/**
|
||
* @return BelongsTo<Guest, $this>
|
||
*/
|
||
public function guest(): BelongsTo
|
||
{
|
||
return $this->belongsTo(Guest::class);
|
||
}
|
||
|
||
/** @return BelongsTo<Channel, $this> */
|
||
public function originChannel(): BelongsTo
|
||
{
|
||
return $this->belongsTo(Channel::class, 'origin_channel_id');
|
||
}
|
||
|
||
/** @return BelongsTo<Channel, $this> */
|
||
public function importChannel(): BelongsTo
|
||
{
|
||
return $this->belongsTo(Channel::class, 'import_channel_id');
|
||
}
|
||
|
||
/** @return HasMany<BookingEvent, $this> */
|
||
public function events(): HasMany
|
||
{
|
||
return $this->hasMany(BookingEvent::class)->orderBy('occurred_at')->orderBy('id');
|
||
}
|
||
|
||
/**
|
||
* The channel whose settings apply: the one the case was imported from, else its origin channel (owner).
|
||
*/
|
||
public function processChannel(): ?Channel
|
||
{
|
||
return $this->importChannel ?? $this->originChannel;
|
||
}
|
||
|
||
/**
|
||
* The rules of this case as frozen when it came in (resolved now for a case that has none yet).
|
||
*/
|
||
public function process(): ProcessProfile
|
||
{
|
||
return filled($this->profile) ? ProcessProfile::fromArray($this->profile) : app(ProcessSettings::class)->forBooking($this);
|
||
}
|
||
|
||
public function caseType(): CaseType
|
||
{
|
||
return $this->case_type ?? $this->process()->caseType;
|
||
}
|
||
|
||
/**
|
||
* Automatic or manual: the decision taken on this case, else the setting frozen with its profile.
|
||
*/
|
||
public function processingMode(): ProcessingMode
|
||
{
|
||
return $this->processing_mode ?? $this->process()->processing();
|
||
}
|
||
|
||
public function isBinding(): bool
|
||
{
|
||
return in_array($this->status, BookingStatus::occupying(), true);
|
||
}
|
||
|
||
public function guestName(): string
|
||
{
|
||
return $this->guest?->full_name ?? 'Gast noch nicht bekannt';
|
||
}
|
||
|
||
/** @return HasMany<BlockedPeriod, $this> */
|
||
public function channelRepresentations(): HasMany
|
||
{
|
||
return $this->hasMany(BlockedPeriod::class, 'linked_booking_id');
|
||
}
|
||
|
||
public function bookingChannelLabel(): string
|
||
{
|
||
return $this->originChannel?->name ?? $this->importChannel?->name ?? match ($this->source ?? 'website') {
|
||
'website' => 'Eigene Webseite',
|
||
'manual' => 'Manuell / direkt',
|
||
'phone' => 'Telefon',
|
||
'email' => 'E-Mail',
|
||
'direct' => 'Direkt',
|
||
default => $this->source,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* Bookings that currently occupy their dates: confirmed ones and requests/offers whose hold has not expired.
|
||
*
|
||
* @param Builder<Booking> $query
|
||
* @return Builder<Booking>
|
||
*/
|
||
#[Scope]
|
||
protected function occupying(Builder $query): Builder
|
||
{
|
||
return $query->where(fn (Builder $query) => $query
|
||
->whereIn('status', BookingStatus::occupying())
|
||
->orWhere(fn (Builder $query) => $query
|
||
->whereIn('status', BookingStatus::holding())
|
||
->where('hold_expires_at', '>', now())));
|
||
}
|
||
|
||
/**
|
||
* @param Builder<Booking> $query
|
||
* @return Builder<Booking>
|
||
*/
|
||
#[Scope]
|
||
protected function overlapping(Builder $query, CarbonInterface $from, CarbonInterface $until): Builder
|
||
{
|
||
return $query
|
||
->whereDate('arrival', '<', $until)
|
||
->whereDate('departure', '>', $from);
|
||
}
|
||
|
||
/**
|
||
* @return HasOne<Review, $this>
|
||
*/
|
||
public function review(): HasOne
|
||
{
|
||
return $this->hasOne(Review::class);
|
||
}
|
||
|
||
/**
|
||
* @return HasMany<BookingMessage, $this>
|
||
*/
|
||
public function messages(): HasMany
|
||
{
|
||
return $this->hasMany(BookingMessage::class);
|
||
}
|
||
|
||
/**
|
||
* @return HasMany<BookingTask, $this>
|
||
*/
|
||
public function tasks(): HasMany
|
||
{
|
||
return $this->hasMany(BookingTask::class);
|
||
}
|
||
|
||
/**
|
||
* @return HasMany<Payment, $this>
|
||
*/
|
||
public function payments(): HasMany
|
||
{
|
||
return $this->hasMany(Payment::class)->orderBy('paid_on');
|
||
}
|
||
|
||
/**
|
||
* Sum of all payments in cents (refunds are negative).
|
||
*/
|
||
public function paidAmount(): int
|
||
{
|
||
return (int) ($this->relationLoaded('payments') ? $this->payments->sum('amount') : $this->payments()->sum('amount'));
|
||
}
|
||
|
||
/**
|
||
* Amount still to be paid in cents; 0 while the price is unknown.
|
||
*/
|
||
public function openAmount(): int
|
||
{
|
||
return $this->total === null ? 0 : max(0, $this->total - $this->paidAmount());
|
||
}
|
||
|
||
public function openDeposit(): int
|
||
{
|
||
return $this->deposit === null ? 0 : max(0, $this->deposit - $this->paidAmount());
|
||
}
|
||
|
||
/**
|
||
* When the balance is already due at confirmation (short-term booking), the guest pays everything at once.
|
||
*/
|
||
public function requiresFullPayment(): bool
|
||
{
|
||
return $this->deposit_due_on !== null && $this->balance_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on);
|
||
}
|
||
|
||
/**
|
||
* Whether the landlord chases payments of this case: only when the guest pays us (process profile – a portal that
|
||
* collects the money needs no tasks) and the price is known.
|
||
*/
|
||
public function wantsPaymentTasks(): bool
|
||
{
|
||
return $this->process()->payments() === Responsibility::Landlord && $this->total !== null && $this->total > 0;
|
||
}
|
||
|
||
/**
|
||
* Whether the guest already asked to cancel (or cancelled) through the cancellation link.
|
||
*/
|
||
public function cancellationRequested(): bool
|
||
{
|
||
return BookingTask::query()->where('booking_id', $this->id)->where('kind', BookingTaskKind::CancellationRequest)->exists();
|
||
}
|
||
|
||
public function nights(): int
|
||
{
|
||
return (int) $this->arrival->diffInDays($this->departure);
|
||
}
|
||
|
||
/**
|
||
* Inside a transaction: locks the property (the lock every writer of bookings takes) and this booking's row
|
||
* and reloads the attributes from the locked row, so status and dates are the latest committed ones.
|
||
*/
|
||
public function lockForTransition(): void
|
||
{
|
||
Property::withoutGlobalScope('tenant')->whereKey($this->property_id)->lockForUpdate()->first();
|
||
|
||
$locked = static::withoutGlobalScope('tenant')->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
||
$this->setRawAttributes($locked->getAttributes(), sync: true);
|
||
}
|
||
|
||
/**
|
||
* A contract text of this offer version (frozen snapshot, live text for bookings without one).
|
||
*/
|
||
public function offerText(string $key): ?string
|
||
{
|
||
return OfferTerms::text($this, $key);
|
||
}
|
||
|
||
public function offerHtml(string $key): HtmlString
|
||
{
|
||
return OfferTerms::html($this, $key);
|
||
}
|
||
|
||
/**
|
||
* Whether the booking may be moved to the archive: it is over (closed, or the stay has ended) and holds nothing.
|
||
*/
|
||
public function canBeArchived(): bool
|
||
{
|
||
return in_array($this->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true)
|
||
|| ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true));
|
||
}
|
||
|
||
public function isHoldActive(): bool
|
||
{
|
||
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
|
||
}
|
||
|
||
/**
|
||
* The website this stay belongs to, regardless of which landlord is current.
|
||
*/
|
||
public function website(): ?Site
|
||
{
|
||
return $this->property()->withoutGlobalScope('tenant')->first()
|
||
?->site()->withoutGlobalScope('tenant')->first();
|
||
}
|
||
}
|