From 0c4187edaf6332e4a17301a56637281cc9acca01 Mon Sep 17 00:00:00 2001 From: Lars Date: Fri, 30 Oct 2026 16:32:48 +0100 Subject: [PATCH] Stornoregeln mit automatischer Kostenberechnung, Storno-Verwaltung, Vertragsanlagen - Stornoregel (Stufen nach Tagen vor Anreise, Mietpreis oder Gesamtpreis, Ersatzmieter-Gebuehr), je Vertragsvorlage, beim Angebot eingefroren, als Platzhalter im Vertrag - Stornierung (Gast-Link oder Verwaltung) berechnet die Kosten, legt einen Stornofall an; Verwaltung Stornierungen mit Vorschlag, Festlegung, Saldo, Abrechnung und Erlass; Gast sieht die Kosten vorab auf der Storno-Seite - Vertragsanlagen als eigene versionierte Dokumente mit Bedingung (immer, Zusatzleistung, Portal, von Hand), je Angebot ausgewaehlt und eingefroren; Zusatzleistungen in der Buchung erfassbar - FeWo-direkt-Installation legt die Stornoregel aus Paragraf 13 an Co-Authored-By: Claude Sonnet 5.5 --- app/Actions/CancelBooking.php | 10 +- app/Actions/CancelBookingByGuest.php | 6 +- app/Actions/RecordCancellation.php | 35 ++++ app/Actions/SendOffer.php | 4 +- .../Commands/InstallFewoDirektContract.php | 9 + app/Documents/ContractPlaceholders.php | 16 +- app/Documents/OfferTerms.php | 26 ++- app/Enums/AdminMode.php | 2 + .../Resources/Bookings/Pages/ViewBooking.php | 37 +++- .../CancellationPolicyResource.php | 93 +++++++++ .../Pages/CreateCancellationPolicy.php | 23 +++ .../Pages/EditCancellationPolicy.php | 29 +++ .../Pages/ListCancellationPolicies.php | 17 ++ .../Cancellations/CancellationResource.php | 119 ++++++++++++ .../Cancellations/Pages/ListCancellations.php | 21 ++ .../ContractAnnexes/ContractAnnexResource.php | 135 +++++++++++++ .../Pages/CreateContractAnnex.php | 22 +++ .../Pages/EditContractAnnex.php | 17 ++ .../Pages/ListContractAnnexes.php | 17 ++ .../Schemas/ContractTemplateForm.php | 13 ++ .../Controllers/SelfServiceController.php | 2 + app/Models/Cancellation.php | 58 ++++++ app/Models/CancellationPolicy.php | 106 +++++++++++ app/Models/ContractAnnex.php | 76 ++++++++ app/Models/ContractTemplate.php | 26 ++- app/Support/BookingProgress.php | 16 +- app/Support/CancellationCost.php | 53 ++++++ ...ancellation_policies_and_cancellations.php | 63 ++++++ ...6_10_30_171500_create_contract_annexes.php | 44 +++++ .../views/filament/booking-contract.blade.php | 6 + .../mail/cancellation-requested.blade.php | 5 + resources/views/offer.blade.php | 4 + .../views/pdf/contract-document.blade.php | 6 + resources/views/pdf/contract.blade.php | 5 + resources/views/self-service/cancel.blade.php | 4 + tests/Feature/CancellationPolicyTest.php | 179 ++++++++++++++++++ tests/Feature/ContractAnnexTest.php | 146 ++++++++++++++ 37 files changed, 1440 insertions(+), 10 deletions(-) create mode 100644 app/Actions/RecordCancellation.php create mode 100644 app/Filament/Resources/CancellationPolicies/CancellationPolicyResource.php create mode 100644 app/Filament/Resources/CancellationPolicies/Pages/CreateCancellationPolicy.php create mode 100644 app/Filament/Resources/CancellationPolicies/Pages/EditCancellationPolicy.php create mode 100644 app/Filament/Resources/CancellationPolicies/Pages/ListCancellationPolicies.php create mode 100644 app/Filament/Resources/Cancellations/CancellationResource.php create mode 100644 app/Filament/Resources/Cancellations/Pages/ListCancellations.php create mode 100644 app/Filament/Resources/ContractAnnexes/ContractAnnexResource.php create mode 100644 app/Filament/Resources/ContractAnnexes/Pages/CreateContractAnnex.php create mode 100644 app/Filament/Resources/ContractAnnexes/Pages/EditContractAnnex.php create mode 100644 app/Filament/Resources/ContractAnnexes/Pages/ListContractAnnexes.php create mode 100644 app/Models/Cancellation.php create mode 100644 app/Models/CancellationPolicy.php create mode 100644 app/Models/ContractAnnex.php create mode 100644 app/Support/CancellationCost.php create mode 100644 database/migrations/2026_10_30_170000_create_cancellation_policies_and_cancellations.php create mode 100644 database/migrations/2026_10_30_171500_create_contract_annexes.php create mode 100644 tests/Feature/CancellationPolicyTest.php create mode 100644 tests/Feature/ContractAnnexTest.php diff --git a/app/Actions/CancelBooking.php b/app/Actions/CancelBooking.php index b692ba5..07b89b8 100644 --- a/app/Actions/CancelBooking.php +++ b/app/Actions/CancelBooking.php @@ -10,6 +10,8 @@ use App\Mail\CancellationRequested; use App\Models\Booking; use App\Models\BookingTask; +use App\Support\CancellationCost; +use App\Support\Money; use App\Support\Settings; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; @@ -42,12 +44,18 @@ public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTa } $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); + app(RecordCancellation::class)->handle($booking, 'landlord'); BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open) ->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]); if ($costsTask) { - BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], ['status' => BookingTaskStatus::Open, 'due_on' => today()]); + $cost = CancellationCost::calculate($booking); + BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [ + 'status' => BookingTaskStatus::Open, + 'due_on' => today(), + 'note' => $cost ? 'Vorschlag nach Stornoregel „'.$cost['policy'].'“: '.Money::format($cost['fee']).' ('.$cost['tier_text'].')' : 'Keine Stornoregel hinterlegt – Kosten von Hand festlegen.', + ]); } }); diff --git a/app/Actions/CancelBookingByGuest.php b/app/Actions/CancelBookingByGuest.php index 3e2fb9b..398b17e 100644 --- a/app/Actions/CancelBookingByGuest.php +++ b/app/Actions/CancelBookingByGuest.php @@ -11,6 +11,7 @@ use App\Mail\CancellationRequested; use App\Models\Booking; use App\Models\BookingTask; +use App\Support\CancellationCost; use App\Support\Settings; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; @@ -34,7 +35,9 @@ public function modeFor(Booking $booking): CancellationMode return match ($property->cancellation_mode) { CancellationMode::Instant => CancellationMode::Instant, - CancellationMode::InstantWhenFree => today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request, + CancellationMode::InstantWhenFree => ($cost = CancellationCost::calculate($booking)) !== null + ? ($cost['free'] ? CancellationMode::Instant : CancellationMode::Request) + : (today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request), default => CancellationMode::Request, }; } @@ -60,6 +63,7 @@ public function handle(Booking $booking, ?string $message = null): ?Cancellation $mode = $this->modeFor($booking); if ($mode === CancellationMode::Instant) { $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); + app(RecordCancellation::class)->handle($booking, 'guest'); } BookingTask::query()->create([ 'booking_id' => $booking->id, diff --git a/app/Actions/RecordCancellation.php b/app/Actions/RecordCancellation.php new file mode 100644 index 0000000..ac83898 --- /dev/null +++ b/app/Actions/RecordCancellation.php @@ -0,0 +1,35 @@ +firstOrCreate( + ['booking_id' => $booking->id], + [ + 'cancelled_on' => today(), + 'initiated_by' => $initiatedBy, + 'has_policy' => $cost !== null, + 'policy_name' => $cost['policy'] ?? null, + 'days_before' => $cost['days_before'] ?? null, + 'percent' => $cost['percent'] ?? null, + 'base_amount' => $cost['base_amount'] ?? null, + 'calculated_fee' => $cost['fee'] ?? null, + 'paid_amount' => $booking->paidAmount(), + 'status' => Cancellation::OPEN, + ], + ); + } +} diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index 4fce5f9..51381a9 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -42,7 +42,7 @@ public function __construct( ) {} /** - * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, guest?: array} $changes + * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list, guest?: array} $changes * * @throws QuoteException * @throws ReservationException @@ -97,7 +97,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t 'offer_version' => $booking->offer_version + 1, 'offer_sent_at' => now(), 'offer_message' => $changes['offer_message'] ?? null, - 'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking), + 'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null), ]); $booking->refresh(); $booking->update(['offer_hash' => OfferTerms::hash($booking)]); diff --git a/app/Console/Commands/InstallFewoDirektContract.php b/app/Console/Commands/InstallFewoDirektContract.php index 6cf9dd9..5711e7c 100644 --- a/app/Console/Commands/InstallFewoDirektContract.php +++ b/app/Console/Commands/InstallFewoDirektContract.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use App\Models\CancellationPolicy; use App\Models\ContractTemplate; use App\Models\Property; use App\Models\Tenant; @@ -45,6 +46,14 @@ public function handle(TenantRunner $runner): int $this->info("{$tenant->name}: Vorlage „".self::NAME.'“ angelegt.'); } + $policy = CancellationPolicy::query()->firstOrCreate(['name' => 'Direktbuchung Standard'], [ + 'base' => CancellationPolicy::BASE_RENT, + 'tiers' => [['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]], + 'replacement_fee' => 3500, + 'notes' => 'Staffel und Ersatzmieter-Gebühr aus § 13 des FeWo-direkt-Vertrags, berechnet vom Mietpreis. Bitte prüfen.', + ]); + ContractTemplate::query()->where('name', self::NAME)->whereNull('cancellation_policy_id')->update(['cancellation_policy_id' => $policy->id]); + if ($data !== []) { $property = Property::query()->first(); if ($property !== null) { diff --git a/app/Documents/ContractPlaceholders.php b/app/Documents/ContractPlaceholders.php index 01f370e..905bdc9 100644 --- a/app/Documents/ContractPlaceholders.php +++ b/app/Documents/ContractPlaceholders.php @@ -3,6 +3,7 @@ namespace App\Documents; use App\Models\Booking; +use App\Models\CancellationPolicy; use App\Support\Money; /** @@ -12,6 +13,9 @@ */ class ContractPlaceholders { + /** Placeholders whose value is already safe HTML. */ + private const RAW = ['storno_regel']; + private const PATTERN = '/\{\{\s*([a-z][a-z0-9_]*(?:\.[a-z0-9_]+)?)\s*\}\}/i'; /** @@ -44,6 +48,7 @@ public static function catalog(): array 'checkin' => 'Anreisezeit (Uhr)', 'checkout' => 'Abreisezeit (Uhr)', 'portal' => 'Name des Portals (leer bei eigener Buchung)', + 'storno_regel' => 'Die Stornoregel dieser Vorlage als Aufzählung (Stufen und Prozent)', 'wohnung.' => 'Eigene Wohnungsdaten (Wohnung bearbeiten › Vertragsdaten), z. B. wohnung.wlan_passwort', ]; } @@ -58,7 +63,11 @@ public static function render(string $html, Booking $booking, array $propertyDat return (string) preg_replace_callback(self::PATTERN, function (array $match) use ($values): string { $key = strtolower($match[1]); - return array_key_exists($key, $values) && $values[$key] !== null ? e((string) $values[$key]) : '['.e($key).'?]'; + if (! array_key_exists($key, $values) || $values[$key] === null) { + return '['.e($key).'?]'; + } + + return in_array($key, self::RAW, true) ? (string) $values[$key] : e((string) $values[$key]); }, $html); } @@ -113,6 +122,11 @@ private static function values(Booking $booking, array $propertyData): array 'portal' => ($booking->importChannel ?? $booking->originChannel)?->name ?? '', ]; + $policy = $booking->offer_terms['cancellation_policy'] ?? null; + if (is_array($policy) && ! empty($policy['tiers'])) { + $values['storno_regel'] = '
    '.collect(CancellationPolicy::describe($policy))->map(fn (string $line): string => '
  • '.e($line).'
  • ')->implode('').'
'; + } + foreach ($propertyData as $name => $value) { $values['wohnung.'.strtolower((string) $name)] = is_scalar($value) ? (string) $value : null; } diff --git a/app/Documents/OfferTerms.php b/app/Documents/OfferTerms.php index ea14d65..3a09cd7 100644 --- a/app/Documents/OfferTerms.php +++ b/app/Documents/OfferTerms.php @@ -4,6 +4,7 @@ use App\Enums\ChannelBookingModel; use App\Models\Booking; +use App\Models\ContractAnnex; use App\Models\ContractTemplate; use App\Support\Content; use Filament\Forms\Components\RichEditor\RichContentRenderer; @@ -32,14 +33,20 @@ class OfferTerms /** * @return array{captured_at: string, template: ?array{id: int, name: string, version: int}, texts: array, deposit_due_days: int, owner: array, bank: array} */ - public static function capture(?ContractTemplate $template = null, ?Booking $booking = null): array + public static function capture(?ContractTemplate $template = null, ?Booking $booking = null, ?array $annexIds = null): array { $overrides = $template?->overrides() ?? []; + $annexes = $annexIds !== null + ? ContractAnnex::query()->whereIn('id', $annexIds)->orderBy('name')->get() + : ($template !== null && $booking !== null ? $template->annexesFor($booking) : collect()); return [ 'captured_at' => now()->toIso8601String(), 'template' => $template ? ['id' => $template->id, 'name' => $template->name, 'version' => $template->version] : null, 'document' => $template?->hasDocument() ? ['body' => $template->body, 'annex_title' => $template->annex_title, 'annex_body' => $template->annex_body] : null, + 'annex_ids' => $annexes->pluck('id')->all(), + 'annexes' => $annexes->map(fn (ContractAnnex $annex): array => ['id' => $annex->id, 'name' => $annex->name, 'version' => $annex->version, 'title' => $annex->title, 'body' => $annex->body])->values()->all(), + 'cancellation_policy' => $template?->cancellationPolicy?->snapshot(), 'property_data' => (array) ($booking?->property?->contract_data ?? []), 'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => $overrides[$key] ?? Content::get($key)])->all(), 'deposit_due_days' => (int) config('fewo.deposit_due_days'), @@ -81,6 +88,23 @@ public static function document(Booking $booking): ?array return ['body' => (string) $render($document['body']), 'annex_title' => $document['annex_title'] ?? null, 'annex' => $render($document['annex_body'] ?? null)]; } + /** + * The annexes frozen in the offer, with placeholders filled. + * + * @return list + */ + public static function annexes(Booking $booking): array + { + $data = (array) ($booking->offer_terms['property_data'] ?? []); + + return collect((array) ($booking->offer_terms['annexes'] ?? []))->map(fn (array $annex): array => [ + 'title' => (string) $annex['title'], + 'name' => (string) $annex['name'], + 'version' => (int) $annex['version'], + 'html' => (string) RichContentRenderer::make(ContractPlaceholders::render((string) $annex['body'], $booking, $data))->toHtml(), + ])->values()->all(); + } + public static function text(Booking $booking, string $key): ?string { $texts = $booking->offer_terms['texts'] ?? null; diff --git a/app/Enums/AdminMode.php b/app/Enums/AdminMode.php index 1b46276..50c421e 100644 --- a/app/Enums/AdminMode.php +++ b/app/Enums/AdminMode.php @@ -7,6 +7,7 @@ use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource; use App\Filament\Resources\Bookings\BookingResource; use App\Filament\Resources\BookingTasks\BookingTaskResource; +use App\Filament\Resources\Cancellations\CancellationResource; use App\Filament\Resources\Channels\ChannelResource; use App\Filament\Resources\ChannelTasks\ChannelTaskResource; use App\Filament\Resources\Guests\GuestResource; @@ -39,6 +40,7 @@ enum AdminMode: string implements HasDescription, HasLabel GuestResource::class, ChannelTaskResource::class, BookingTaskResource::class, + CancellationResource::class, ChannelResource::class, ReviewResource::class, PhotoResource::class, diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index 1ffa36b..b68e555 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -6,13 +6,16 @@ use App\Actions\ConfirmBooking; use App\Actions\DeclineBooking; use App\Actions\SendOffer; +use App\Documents\OfferTerms; use App\Documents\RentalContract; use App\Enums\BookingStatus; use App\Exceptions\ReservationException; use App\Filament\Actions\AssignGuestAction; use App\Filament\Resources\Bookings\BookingResource; use App\Models\Booking; +use App\Models\ContractAnnex; use App\Models\ContractTemplate; +use App\Models\Extra; use App\Pricing\PriceCalculator; use App\Pricing\QuoteException; use App\Pricing\StayRequest; @@ -22,6 +25,7 @@ use Filament\Actions\ActionGroup; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DateTimePicker; +use Filament\Forms\Components\Repeater; use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; @@ -88,7 +92,13 @@ protected function getHeaderActions(): array TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80), Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(), ]), - Section::make('Vertragsvorlage')->schema([ + Section::make('Vertragsvorlage und Anlagen')->schema([ + Select::make('annex_ids') + ->label('Anlagen') + ->multiple() + ->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()) + ->default(fn (): array => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []) + ->helperText('Vorausgewählt: Anlagen der Vorlage, deren Bedingung zu dieser Buchung passt (z. B. gebuchtes Wäschepaket). Sie können Anlagen hinzufügen oder entfernen.'), Select::make('contract_template_id') ->label('Vorlage für dieses Angebot') ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) @@ -190,6 +200,31 @@ protected function getHeaderActions(): array $notification = Notification::make()->title($sent ? 'Bestätigung gesendet' : 'Versand fehlgeschlagen'); ($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send(); }), + Action::make('services') + ->label('Zusatzleistungen erfassen') + ->icon(Heroicon::OutlinedPlusCircle) + ->color('gray') + ->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) + ->modalDescription('Gebuchte Zusatzleistungen (kostenpflichtig oder kostenlos), z. B. aus einer Portalbuchung oder per E-Mail erfragt. Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis der Buchung wird dadurch nicht verändert.') + ->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()]) + ->schema([ + Repeater::make('items') + ->label('Leistungen') + ->schema([ + Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->orderBy('name')->get()->mapWithKeys(fn (Extra $extra): array => [$extra->id => $extra->name.($extra->price > 0 ? ' ('.Money::format($extra->price).')' : ' (kostenlos)')])->all())->required(), + TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(), + ]) + ->columns(2) + ->addActionLabel('Leistung hinzufügen'), + ]) + ->action(function (array $data): void { + $extras = []; + foreach ((array) ($data['items'] ?? []) as $item) { + $extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) $item['quantity']); + } + $this->record->update(['extras' => $extras]); + Notification::make()->title('Zusatzleistungen gespeichert')->success()->send(); + }), Action::make('contractText') ->label('Vertragstext ansehen') ->icon(Heroicon::OutlinedDocumentMagnifyingGlass) diff --git a/app/Filament/Resources/CancellationPolicies/CancellationPolicyResource.php b/app/Filament/Resources/CancellationPolicies/CancellationPolicyResource.php new file mode 100644 index 0000000..405f622 --- /dev/null +++ b/app/Filament/Resources/CancellationPolicies/CancellationPolicyResource.php @@ -0,0 +1,93 @@ +components([ + TextInput::make('name')->label('Name')->required()->maxLength(120)->helperText('z. B. „Direktbuchung“ oder „FeWo-direkt“.'), + Select::make('base') + ->label('Berechnungsgrundlage') + ->options([CancellationPolicy::BASE_RENT => 'Mietpreis (ohne Endreinigung, Service und Kurtaxe)', CancellationPolicy::BASE_TOTAL => 'Gesamtpreis']) + ->default(CancellationPolicy::BASE_RENT) + ->required(), + Repeater::make('tiers') + ->label('Stufen') + ->helperText('Jede Stufe gilt, wenn bis zur Anreise mindestens so viele Tage bleiben. Beispiel: ab 60 Tagen 0 %, ab 30 Tagen 50 %, ab 0 Tagen 100 %. Die letzte Stufe (0 Tage) gilt für alles danach.') + ->schema([ + TextInput::make('min_days')->label('Ab Tagen vor Anreise')->integer()->minValue(0)->required(), + TextInput::make('percent')->label('Entschädigung')->integer()->minValue(0)->maxValue(100)->suffix('%')->required(), + ]) + ->columns(2) + ->default([['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]]) + ->minItems(1) + ->required() + ->columnSpanFull(), + EuroInput::make('replacement_fee')->label('Gebühr bei Ersatzmieter (optional)'), + Text::make(fn (?CancellationPolicy $record): HtmlString => new HtmlString($record ? 'So steht es im Vertrag ({{ storno_regel }}):
    '.collect(CancellationPolicy::describe($record->snapshot()))->map(fn (string $line): string => '
  • '.e($line).'
  • ')->implode('').'
' : ''))->columnSpanFull(), + Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->defaultSort('name') + ->columns([ + TextColumn::make('name')->label('Regel')->weight('medium')->searchable(), + TextColumn::make('base')->label('Grundlage')->formatStateUsing(fn (string $state): string => $state === CancellationPolicy::BASE_TOTAL ? 'Gesamtpreis' : 'Mietpreis'), + TextColumn::make('steps')->label('Stufen')->state(fn (CancellationPolicy $record): string => collect(CancellationPolicy::normalise((array) $record->tiers))->map(fn (array $tier): string => 'ab '.$tier['min_days'].' T: '.$tier['percent'].' %')->implode(' · ')), + ]) + ->recordActions([EditAction::make(), DeleteAction::make()]); + } + + public static function getPages(): array + { + return [ + 'index' => ListCancellationPolicies::route('/'), + 'create' => CreateCancellationPolicy::route('/create'), + 'edit' => EditCancellationPolicy::route('/{record}/edit'), + ]; + } +} diff --git a/app/Filament/Resources/CancellationPolicies/Pages/CreateCancellationPolicy.php b/app/Filament/Resources/CancellationPolicies/Pages/CreateCancellationPolicy.php new file mode 100644 index 0000000..f663927 --- /dev/null +++ b/app/Filament/Resources/CancellationPolicies/Pages/CreateCancellationPolicy.php @@ -0,0 +1,23 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeCreate(array $data): array + { + $data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? [])); + + return $data; + } +} diff --git a/app/Filament/Resources/CancellationPolicies/Pages/EditCancellationPolicy.php b/app/Filament/Resources/CancellationPolicies/Pages/EditCancellationPolicy.php new file mode 100644 index 0000000..9658f42 --- /dev/null +++ b/app/Filament/Resources/CancellationPolicies/Pages/EditCancellationPolicy.php @@ -0,0 +1,29 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeSave(array $data): array + { + $data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? [])); + + return $data; + } +} diff --git a/app/Filament/Resources/CancellationPolicies/Pages/ListCancellationPolicies.php b/app/Filament/Resources/CancellationPolicies/Pages/ListCancellationPolicies.php new file mode 100644 index 0000000..b6ca881 --- /dev/null +++ b/app/Filament/Resources/CancellationPolicies/Pages/ListCancellationPolicies.php @@ -0,0 +1,17 @@ +defaultSort('cancelled_on', 'desc') + ->description('Storno-Verwaltung: Kosten werden nach der Stornoregel der Vertragsvorlage vorgeschlagen. Sie legen den Betrag endgültig fest, rechnen ab oder erlassen ihn. Gäste erhalten hierzu keine automatische Mail.') + ->columns([ + TextColumn::make('booking.reference')->label('Buchung')->weight('medium')->description(fn (Cancellation $record): string => $record->booking->guest?->full_name ?? ''), + TextColumn::make('cancelled_on')->label('Storniert am')->date('d.m.Y')->description(fn (Cancellation $record): string => $record->initiated_by === 'guest' ? 'durch den Gast' : 'durch die Verwaltung'), + TextColumn::make('days_before')->label('Tage vor Anreise')->placeholder('–'), + TextColumn::make('policy_name')->label('Stornoregel')->placeholder('Keine Regel')->description(fn (Cancellation $record): ?string => $record->percent !== null ? $record->percent.' % von '.Money::format((int) $record->base_amount) : null), + TextColumn::make('calculated_fee')->label('Vorschlag')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)), + TextColumn::make('final_fee')->label('Festgelegt')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)), + TextColumn::make('paid_amount')->label('Bezahlt')->formatStateUsing(fn (int $state): string => Money::format($state)), + TextColumn::make('balance')->label('Saldo')->state(fn (Cancellation $record): string => $record->balance() > 0 ? Money::format($record->balance()).' einzufordern' : ($record->balance() < 0 ? Money::format(-$record->balance()).' zu erstatten' : 'ausgeglichen')), + TextColumn::make('status')->label('Status')->badge()->formatStateUsing(fn (string $state): string => match ($state) { + Cancellation::SETTLED => 'Abgerechnet', + Cancellation::WAIVED => 'Erlassen', + default => 'Offen', + })->color(fn (string $state): string => $state === Cancellation::OPEN ? 'warning' : 'success'), + ]) + ->filters([ + SelectFilter::make('status')->label('Status')->options([Cancellation::OPEN => 'Offen', Cancellation::SETTLED => 'Abgerechnet', Cancellation::WAIVED => 'Erlassen'])->default(Cancellation::OPEN), + ]) + ->recordActions([ + Action::make('booking')->label('Buchung')->icon(Heroicon::OutlinedArrowTopRightOnSquare)->color('gray') + ->url(fn (Cancellation $record): string => BookingResource::getUrl('view', ['record' => $record->booking])), + Action::make('decide') + ->label('Kosten festlegen') + ->icon(Heroicon::OutlinedPencilSquare) + ->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN) + ->fillForm(fn (Cancellation $record): array => ['final_fee' => $record->final_fee ?? $record->calculated_fee, 'note' => $record->note]) + ->schema([ + EuroInput::make('final_fee')->label('Endgültige Stornokosten')->required(), + Textarea::make('note')->label('Begründung / Notiz')->rows(2), + ]) + ->action(fn (array $data, Cancellation $record) => $record->update(['final_fee' => $data['final_fee'], 'note' => $data['note']])), + Action::make('settle') + ->label('Abgerechnet') + ->icon(Heroicon::OutlinedCheck) + ->color('success') + ->requiresConfirmation() + ->modalDescription('Die Stornokosten sind beglichen bzw. Rückzahlung und Forderung sind erledigt.') + ->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN) + ->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::SETTLED, 'settled_at' => now()])), + Action::make('waive') + ->label('Erlassen') + ->icon(Heroicon::OutlinedXMark) + ->color('gray') + ->requiresConfirmation() + ->modalDescription('Es werden keine Stornokosten berechnet.') + ->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN) + ->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::WAIVED, 'settled_at' => now()])), + ]); + } + + public static function canCreate(): bool + { + return false; + } + + public static function getNavigationBadge(): ?string + { + $open = Cancellation::query()->where('status', Cancellation::OPEN)->count(); + + return $open > 0 ? (string) $open : null; + } + + public static function getNavigationBadgeColor(): string + { + return 'warning'; + } + + public static function getPages(): array + { + return [ + 'index' => ListCancellations::route('/'), + ]; + } +} diff --git a/app/Filament/Resources/Cancellations/Pages/ListCancellations.php b/app/Filament/Resources/Cancellations/Pages/ListCancellations.php new file mode 100644 index 0000000..3394a07 --- /dev/null +++ b/app/Filament/Resources/Cancellations/Pages/ListCancellations.php @@ -0,0 +1,21 @@ +whereHas('booking', fn (Builder $booking) => $booking->where('property_id', $property->id)); + } +} diff --git a/app/Filament/Resources/ContractAnnexes/ContractAnnexResource.php b/app/Filament/Resources/ContractAnnexes/ContractAnnexResource.php new file mode 100644 index 0000000..c72ace0 --- /dev/null +++ b/app/Filament/Resources/ContractAnnexes/ContractAnnexResource.php @@ -0,0 +1,135 @@ +components([ + TextInput::make('name')->label('Name (intern)')->required()->maxLength(120)->helperText('z. B. „WLAN“, „Wäschepaket“, „Key Pickup“. Versionen haben denselben Namen.'), + TextInput::make('title')->label('Überschrift im Vertrag')->required()->maxLength(200), + Select::make('condition_type') + ->label('Wann wird die Anlage angehängt?') + ->options([ + ContractAnnex::ALWAYS => 'Immer, wenn die Vorlage sie enthält', + ContractAnnex::EXTRA => 'Wenn eine bestimmte Zusatzleistung gebucht ist', + ContractAnnex::CHANNEL => 'Nur bei Buchungen über ein bestimmtes Portal', + ContractAnnex::MANUAL => 'Nur von Hand (im Angebot auswählen)', + ]) + ->default(ContractAnnex::ALWAYS) + ->required() + ->live(), + Select::make('condition_id') + ->label('Zusatzleistung / Portal') + ->options(fn (Get $get): array => match ($get('condition_type')) { + ContractAnnex::EXTRA => Extra::query()->orderBy('name')->pluck('name', 'id')->all(), + ContractAnnex::CHANNEL => Channel::query()->orderBy('name')->pluck('name', 'id')->all(), + default => [], + }) + ->visible(fn (Get $get): bool => in_array($get('condition_type'), [ContractAnnex::EXTRA, ContractAnnex::CHANNEL], true)) + ->required(fn (Get $get): bool => in_array($get('condition_type'), [ContractAnnex::EXTRA, ContractAnnex::CHANNEL], true)), + RichEditor::make('body') + ->label('Text der Anlage (mit Platzhaltern wie {{ mieter }}, {{ wohnung.wlan_passwort }})') + ->toolbarButtons([['bold', 'italic', 'underline', 'link'], ['h2', 'h3'], ['bulletList', 'orderedList'], ['undo', 'redo']]) + ->required() + ->columnSpanFull(), + Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(), + ]); + } + + public static function table(Table $table): Table + { + return $table + ->defaultSort('name') + ->columns([ + TextColumn::make('name')->label('Anlage')->weight('medium')->searchable(), + TextColumn::make('version')->label('Version')->badge(), + TextColumn::make('condition')->label('Bedingung')->state(fn (ContractAnnex $record): string => match ($record->condition_type) { + ContractAnnex::EXTRA => 'Zusatzleistung: '.(Extra::query()->find($record->condition_id)?->name ?? '?'), + ContractAnnex::CHANNEL => 'Portal: '.(Channel::query()->find($record->condition_id)?->name ?? '?'), + ContractAnnex::MANUAL => 'Nur von Hand', + default => 'Immer', + }), + IconColumn::make('used')->label('In Angeboten')->boolean()->state(fn (ContractAnnex $record): bool => $record->isUsed()), + ]) + ->recordActions([ + EditAction::make(), + Action::make('newVersion') + ->label('Neue Version') + ->icon(Heroicon::OutlinedDocumentDuplicate) + ->requiresConfirmation() + ->modalDescription('Es wird eine Kopie mit der nächsten Versionsnummer angelegt. Die bisherige Version bleibt unverändert.') + ->action(function (ContractAnnex $record): void { + Notification::make()->title('Version '.$record->newVersion()->version.' angelegt')->success()->send(); + }), + DeleteAction::make(), + ]); + } + + /** + * A version used in an offer is a document of record and is never edited; a new version is made instead. + */ + public static function canEdit(Model $record): bool + { + return ! $record->isUsed(); + } + + public static function canDelete(Model $record): bool + { + return ! $record->isUsed(); + } + + public static function getPages(): array + { + return [ + 'index' => ListContractAnnexes::route('/'), + 'create' => CreateContractAnnex::route('/create'), + 'edit' => EditContractAnnex::route('/{record}/edit'), + ]; + } +} diff --git a/app/Filament/Resources/ContractAnnexes/Pages/CreateContractAnnex.php b/app/Filament/Resources/ContractAnnexes/Pages/CreateContractAnnex.php new file mode 100644 index 0000000..e186e58 --- /dev/null +++ b/app/Filament/Resources/ContractAnnexes/Pages/CreateContractAnnex.php @@ -0,0 +1,22 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeCreate(array $data): array + { + $data['version'] = 1; + + return $data; + } +} diff --git a/app/Filament/Resources/ContractAnnexes/Pages/EditContractAnnex.php b/app/Filament/Resources/ContractAnnexes/Pages/EditContractAnnex.php new file mode 100644 index 0000000..01d0ae4 --- /dev/null +++ b/app/Filament/Resources/ContractAnnexes/Pages/EditContractAnnex.php @@ -0,0 +1,17 @@ +helperText('z. B. „Direktbuchung“ oder „Portal XY“. Versionen derselben Vorlage haben denselben Namen.'), TextInput::make('version')->label('Version')->integer()->default(1)->disabled()->dehydrated(false) ->helperText('Neue Versionen entstehen über „Neue Version“ in der Liste. Eine Vorlage, die in einem Angebot verwendet wurde, kann nicht mehr geändert werden.'), + Select::make('cancellation_policy_id') + ->label('Stornoregel') + ->options(fn (): array => CancellationPolicy::query()->orderBy('name')->pluck('name', 'id')->all()) + ->placeholder('Keine – Stornokosten von Hand') + ->helperText('Stufen und Berechnungsgrundlage für die automatische Berechnung der Stornokosten. Im Vertragstext mit {{ storno_regel }} einfügbar.'), + Select::make('annex_ids') + ->label('Mögliche Anlagen dieser Vorlage') + ->multiple() + ->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()) + ->helperText('Welche davon einem Angebot angehängt werden, entscheidet die Bedingung der Anlage (z. B. gebuchte Zusatzleistung). Im Angebot lässt sich die Auswahl ändern.'), Section::make('Vertragsdokument') ->description('Der ganze Vertrag als ein Text mit Platzhaltern (siehe unten). Ist hier etwas eingetragen, wird dieser Text als Mietvertrag verwendet – mit Briefkopf, Anrede, Paragrafen und optionaler Anlage. Leer lassen, um nur die Textbausteine darunter zu verwenden.') ->columnSpanFull() diff --git a/app/Http/Controllers/SelfServiceController.php b/app/Http/Controllers/SelfServiceController.php index 4d0ca39..9e9eee8 100644 --- a/app/Http/Controllers/SelfServiceController.php +++ b/app/Http/Controllers/SelfServiceController.php @@ -8,6 +8,7 @@ use App\Enums\CancellationMode; use App\Exceptions\ReservationException; use App\Models\Booking; +use App\Support\CancellationCost; use DateTimeInterface; use Illuminate\Contracts\View\View; use Illuminate\Http\RedirectResponse; @@ -54,6 +55,7 @@ public function showCancel(Booking $booking, CancelBookingByGuest $cancel): View 'canCancel' => $open && ! $booking->cancellationRequested(), 'alreadyAsked' => $booking->status === BookingStatus::Cancelled || $booking->cancellationRequested(), 'instant' => $cancel->modeFor($booking) === CancellationMode::Instant, + 'cost' => CancellationCost::calculate($booking), 'action' => $this->signed('bookings.cancel.confirm', $booking, now()->addHour()), 'title' => 'Buchung stornieren', ]); diff --git a/app/Models/Cancellation.php b/app/Models/Cancellation.php new file mode 100644 index 0000000..0c8c8e3 --- /dev/null +++ b/app/Models/Cancellation.php @@ -0,0 +1,58 @@ + + */ + protected function casts(): array + { + return ['cancelled_on' => 'immutable_date', 'has_policy' => 'boolean', 'settled_at' => 'immutable_datetime']; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } + + /** + * What the guest owes: the final fee, else the proposal; nothing when waived. + */ + public function fee(): int + { + return $this->status === self::WAIVED ? 0 : (int) ($this->final_fee ?? $this->calculated_fee ?? 0); + } + + /** + * Positive: the guest still has to pay; negative: the landlord has to refund. + */ + public function balance(): int + { + return $this->fee() - $this->paid_amount; + } +} diff --git a/app/Models/CancellationPolicy.php b/app/Models/CancellationPolicy.php new file mode 100644 index 0000000..caae5d6 --- /dev/null +++ b/app/Models/CancellationPolicy.php @@ -0,0 +1,106 @@ + + */ + protected function casts(): array + { + return ['tiers' => 'array', 'replacement_fee' => 'integer']; + } + + /** + * The frozen form stored in an offer. + * + * @return array{name: string, base: string, tiers: list, replacement_fee: ?int} + */ + public function snapshot(): array + { + return [ + 'name' => $this->name, + 'base' => $this->base, + 'tiers' => self::normalise((array) $this->tiers), + 'replacement_fee' => $this->replacement_fee, + ]; + } + + /** + * Tiers sorted from the earliest to the latest cancellation: "from N days before arrival: P %". + * + * @param array> $tiers + * @return list + */ + public static function normalise(array $tiers): array + { + $clean = array_map(fn (array $tier): array => ['min_days' => max(0, (int) ($tier['min_days'] ?? 0)), 'percent' => min(100, max(0, (int) ($tier['percent'] ?? 0)))], $tiers); + usort($clean, fn (array $a, array $b): int => $b['min_days'] <=> $a['min_days']); + + return array_values($clean); + } + + /** + * The tier that applies when cancelling this many days before arrival (the last tier covers everything later). + * + * @param array{tiers: list} $policy + * @return array{min_days: int, percent: int} + */ + public static function tierFor(array $policy, int $daysBefore): array + { + foreach ($policy['tiers'] as $tier) { + if ($daysBefore >= $tier['min_days']) { + return $tier; + } + } + + return $policy['tiers'][array_key_last($policy['tiers'])] ?? ['min_days' => 0, 'percent' => 100]; + } + + /** + * The rule as readable lines for contracts and pages, e.g. "Rücktritt bis 60 Tage vor Mietbeginn: 0 % …". + * + * @param array{base: string, tiers: list, replacement_fee: ?int} $policy + * @return list + */ + public static function describe(array $policy): array + { + $base = $policy['base'] === self::BASE_TOTAL ? 'des Gesamtpreises' : 'des Mietpreises'; + $lines = []; + $tiers = $policy['tiers']; + foreach ($tiers as $index => $tier) { + $next = $tiers[$index + 1] ?? null; + $when = match (true) { + $index === 0 => 'Rücktritt bis '.$tier['min_days'].' Tage vor Mietbeginn', + $next === null => 'Rücktritt ab '.($tiers[$index - 1]['min_days'] - 1).' Tage vor Mietbeginn bis Mietbeginn', + default => 'Rücktritt '.($tiers[$index - 1]['min_days'] - 1).' bis '.$tier['min_days'].' Tage vor Mietbeginn', + }; + $lines[] = $when.': '.$tier['percent'].' % '.$base; + } + if (($policy['replacement_fee'] ?? null) !== null) { + $lines[] = 'Stellung eines Ersatzmieters: Bearbeitungsgebühr '.Money::format((int) $policy['replacement_fee']); + } + + return $lines; + } +} diff --git a/app/Models/ContractAnnex.php b/app/Models/ContractAnnex.php new file mode 100644 index 0000000..13a9779 --- /dev/null +++ b/app/Models/ContractAnnex.php @@ -0,0 +1,76 @@ + + */ + protected function casts(): array + { + return ['version' => 'integer', 'condition_id' => 'integer']; + } + + public function label(): string + { + return $this->name.' (Version '.$this->version.')'; + } + + /** + * Whether this annex belongs to the booking by its condition (manual annexes are only added by hand). + */ + public function appliesTo(Booking $booking): bool + { + $channelId = $booking->import_channel_id ?? $booking->origin_channel_id; + + return match ($this->condition_type) { + self::ALWAYS => true, + self::EXTRA => $this->condition_id !== null && (int) ($booking->extras[$this->condition_id] ?? 0) > 0, + self::CHANNEL => $this->condition_id !== null && (int) $channelId === $this->condition_id, + default => false, + }; + } + + public function isUsed(): bool + { + return Booking::query()->whereJsonContains('offer_terms->annex_ids', $this->id)->exists(); + } + + public function newVersion(): self + { + $latest = static::query()->where('name', $this->name)->max('version'); + + return static::query()->create([ + 'name' => $this->name, + 'version' => $latest + 1, + 'title' => $this->title, + 'body' => $this->body, + 'condition_type' => $this->condition_type, + 'condition_id' => $this->condition_id, + 'notes' => $this->notes, + ]); + } +} diff --git a/app/Models/ContractTemplate.php b/app/Models/ContractTemplate.php index 08407b0..154f6b4 100644 --- a/app/Models/ContractTemplate.php +++ b/app/Models/ContractTemplate.php @@ -5,13 +5,15 @@ use App\Models\Concerns\BelongsToTenant; use Illuminate\Database\Eloquent\Attributes\Fillable; use Illuminate\Database\Eloquent\Model; +use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Support\Collection; /** * A version of contract texts for offers (e.g. conditions demanded by a portal). The texts replace the website * texts of the same meaning when an offer is made; the offer then freezes a copy. A version that has been used in * an offer is never edited – a new version is created instead. */ -#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'notes'])] +#[Fillable(['name', 'version', 'texts', 'body', 'annex_title', 'annex_body', 'cancellation_policy_id', 'annex_ids', 'notes'])] class ContractTemplate extends Model { use BelongsToTenant; @@ -33,7 +35,7 @@ class ContractTemplate extends Model */ protected function casts(): array { - return ['texts' => 'array', 'version' => 'integer']; + return ['texts' => 'array', 'version' => 'integer', 'annex_ids' => 'array']; } /** @@ -44,6 +46,24 @@ public function hasDocument(): bool return filled($this->body) && trim(strip_tags((string) $this->body)) !== ''; } + /** + * @return BelongsTo + */ + public function cancellationPolicy(): BelongsTo + { + return $this->belongsTo(CancellationPolicy::class); + } + + /** + * The annexes of this template whose condition fits the booking. + * + * @return Collection + */ + public function annexesFor(Booking $booking): Collection + { + return ContractAnnex::query()->whereIn('id', (array) ($this->annex_ids ?? []))->orderBy('name')->get()->filter(fn (ContractAnnex $annex): bool => $annex->appliesTo($booking))->values(); + } + public function label(): string { return $this->name.' (Version '.$this->version.')'; @@ -83,6 +103,8 @@ public function newVersion(): self 'body' => $this->body, 'annex_title' => $this->annex_title, 'annex_body' => $this->annex_body, + 'cancellation_policy_id' => $this->cancellation_policy_id, + 'annex_ids' => $this->annex_ids, 'notes' => $this->notes, ]); } diff --git a/app/Support/BookingProgress.php b/app/Support/BookingProgress.php index 26f5b95..55dcad3 100644 --- a/app/Support/BookingProgress.php +++ b/app/Support/BookingProgress.php @@ -8,6 +8,7 @@ use App\Enums\ChannelBookingModel; use App\Models\Booking; use App\Models\BookingTask; +use App\Models\Cancellation; use Carbon\CarbonImmutable; /** @@ -91,6 +92,19 @@ public static function steps(Booking $booking): array return $steps; } + private static function cancelledText(Booking $booking, bool $open): string + { + $cancellation = Cancellation::query()->where('booking_id', $booking->id)->first(); + if ($cancellation === null) { + return $open ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.'; + } + + $balance = $cancellation->balance(); + $text = 'Storniert am '.$cancellation->cancelled_on->format('d.m.Y').' ('.($cancellation->days_before ?? '?').' Tage vor Anreise). Stornokosten '.Money::format($cancellation->fee()).', bezahlt '.Money::format($cancellation->paid_amount).'.'; + + return $text.($cancellation->status === Cancellation::OPEN ? ($balance > 0 ? ' Noch einzufordern: '.Money::format($balance).'.' : ($balance < 0 ? ' Zu erstatten: '.Money::format(-$balance).'.' : ' Ausgeglichen – bitte als abgerechnet markieren.')) : ' Erledigt.'); + } + /** * @return array{title: string, text: string, color: string} */ @@ -109,7 +123,7 @@ public static function next(Booking $booking): array } return match (true) { - $booking->status === BookingStatus::Cancelled => ['title' => 'Storniert', 'text' => $costs !== null || $wish !== null ? 'Stornokosten bzw. Rückzahlung sind noch zu klären (siehe Aufgaben).' : 'Nichts mehr zu tun. Die Buchung bleibt zur Historie erhalten.', 'color' => $costs !== null ? 'warning' : 'gray'], + $booking->status === BookingStatus::Cancelled => ['title' => 'Storniert', 'text' => self::cancelledText($booking, $costs !== null || $wish !== null), 'color' => $costs !== null ? 'warning' : 'gray'], $booking->status === BookingStatus::Declined => ['title' => 'Abgelehnt', 'text' => 'Der Zeitraum ist wieder frei.', 'color' => 'gray'], $booking->status === BookingStatus::Expired => ['title' => 'Abgelaufen', 'text' => 'Die Haltefrist ist verstrichen. Sie können die Anfrage trotzdem noch bestätigen, solange der Zeitraum frei ist.', 'color' => 'gray'], $booking->status === BookingStatus::Reserved => ['title' => 'Anfrage prüfen', 'text' => $kind === self::PORTAL_BOOKING diff --git a/app/Support/CancellationCost.php b/app/Support/CancellationCost.php new file mode 100644 index 0000000..f45770e --- /dev/null +++ b/app/Support/CancellationCost.php @@ -0,0 +1,53 @@ +offer_terms['cancellation_policy'] ?? null; + if (! is_array($policy) || empty($policy['tiers'])) { + return null; + } + + $on ??= today(); + $daysBefore = max(0, (int) $on->copy()->startOfDay()->diffInDays($booking->arrival, false)); + $tier = CancellationPolicy::tierFor($policy, $daysBefore); + $baseAmount = $policy['base'] === CancellationPolicy::BASE_TOTAL ? (int) $booking->total : self::rent($booking); + $fee = (int) round($baseAmount * $tier['percent'] / 100); + + return [ + 'policy' => (string) $policy['name'], + 'base' => (string) $policy['base'], + 'days_before' => $daysBefore, + 'percent' => $tier['percent'], + 'base_amount' => $baseAmount, + 'fee' => $fee, + 'free' => $fee === 0, + 'tier_text' => $tier['percent'].' % '.($policy['base'] === CancellationPolicy::BASE_TOTAL ? 'des Gesamtpreises' : 'des Mietpreises').' ('.$daysBefore.' Tage vor Anreise)', + ]; + } + + /** + * The rent: accommodation, extra guests, discounts and manual adjustments – without cleaning, services and extras. + */ + public static function rent(Booking $booking): int + { + $rentTypes = [QuoteLineType::Accommodation->value, QuoteLineType::ExtraGuest->value, QuoteLineType::Discount->value, QuoteLineType::Adjustment->value]; + + return (int) collect($booking->quote['lines'] ?? [])->filter(fn (array $line): bool => in_array($line['type'] ?? null, $rentTypes, true))->sum('amount'); + } +} diff --git a/database/migrations/2026_10_30_170000_create_cancellation_policies_and_cancellations.php b/database/migrations/2026_10_30_170000_create_cancellation_policies_and_cancellations.php new file mode 100644 index 0000000..41fc862 --- /dev/null +++ b/database/migrations/2026_10_30_170000_create_cancellation_policies_and_cancellations.php @@ -0,0 +1,63 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->string('base', 10)->default('rent'); + $table->json('tiers'); + $table->unsignedInteger('replacement_fee')->nullable(); + $table->text('notes')->nullable(); + $table->timestamps(); + }); + + Schema::table('contract_templates', function (Blueprint $table) { + $table->foreignId('cancellation_policy_id')->nullable()->after('annex_body')->constrained('cancellation_policies')->nullOnDelete(); + }); + + Schema::create('cancellations', function (Blueprint $table) { + $table->id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->date('cancelled_on'); + $table->string('initiated_by', 12)->default('landlord'); + $table->boolean('has_policy')->default(false); + $table->string('policy_name')->nullable(); + $table->unsignedSmallInteger('days_before')->nullable(); + $table->unsignedSmallInteger('percent')->nullable(); + $table->integer('base_amount')->nullable(); + $table->integer('calculated_fee')->nullable(); + $table->integer('final_fee')->nullable(); + $table->integer('paid_amount')->default(0); + $table->string('status', 12)->default('open'); + $table->text('note')->nullable(); + $table->timestamp('settled_at')->nullable(); + $table->timestamps(); + $table->unique('booking_id'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('cancellations'); + Schema::table('contract_templates', function (Blueprint $table) { + $table->dropConstrainedForeignId('cancellation_policy_id'); + }); + Schema::dropIfExists('cancellation_policies'); + } +}; diff --git a/database/migrations/2026_10_30_171500_create_contract_annexes.php b/database/migrations/2026_10_30_171500_create_contract_annexes.php new file mode 100644 index 0000000..bf83679 --- /dev/null +++ b/database/migrations/2026_10_30_171500_create_contract_annexes.php @@ -0,0 +1,44 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->unsignedInteger('version')->default(1); + $table->string('title'); + $table->longText('body'); + $table->string('condition_type', 12)->default('always'); + $table->unsignedBigInteger('condition_id')->nullable(); + $table->text('notes')->nullable(); + $table->timestamps(); + $table->unique(['tenant_id', 'name', 'version']); + }); + + Schema::table('contract_templates', function (Blueprint $table) { + $table->json('annex_ids')->nullable()->after('cancellation_policy_id'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('contract_templates', function (Blueprint $table) { + $table->dropColumn('annex_ids'); + }); + Schema::dropIfExists('contract_annexes'); + } +}; diff --git a/resources/views/filament/booking-contract.blade.php b/resources/views/filament/booking-contract.blade.php index c543e2b..eb05cd1 100644 --- a/resources/views/filament/booking-contract.blade.php +++ b/resources/views/filament/booking-contract.blade.php @@ -19,4 +19,10 @@
{{ $booking->offerHtml('stay.cancellation') }}
@endif @endif + + @foreach (\App\Documents\OfferTerms::annexes($booking) as $extraAnnex) +
+

Anlage: {{ $extraAnnex['title'] }} (Version {{ $extraAnnex['version'] }})

+
{!! $extraAnnex['html'] !!}
+ @endforeach diff --git a/resources/views/mail/cancellation-requested.blade.php b/resources/views/mail/cancellation-requested.blade.php index feee037..c5e638d 100644 --- a/resources/views/mail/cancellation-requested.blade.php +++ b/resources/views/mail/cancellation-requested.blade.php @@ -5,6 +5,11 @@ **Zeitraum:** {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}
**Gesamtpreis:** {{ \App\Support\Money::format($booking->total) }}, bezahlt {{ \App\Support\Money::format($booking->paidAmount()) }} +@php($cost = \App\Support\CancellationCost::calculate($booking, $booking->cancelled_at ?? now())) +@if ($cost) +**Stornoregel „{{ $cost['policy'] }}“:** {{ $cost['tier_text'] }} → Vorschlag **{{ \App\Support\Money::format($cost['fee']) }}** (Basis {{ \App\Support\Money::format($cost['base_amount']) }}). +@endif + @if ($cancelled) Die Buchung wurde sofort storniert und der Zeitraum ist frei. **Stornokosten und eine mögliche Rückzahlung bitte von Hand prüfen** (Aufgabe unter „Zahlungen & Wünsche“). @else diff --git a/resources/views/offer.blade.php b/resources/views/offer.blade.php index 694be97..2f4e044 100644 --- a/resources/views/offer.blade.php +++ b/resources/views/offer.blade.php @@ -77,6 +77,10 @@
{{ $booking->offerHtml('stay.cancellation') }}
@endif @endif + @foreach (\App\Documents\OfferTerms::annexes($booking) as $extraAnnex) +

Anlage: {{ $extraAnnex['title'] }}

+
{!! $extraAnnex['html'] !!}
+ @endforeach

Den vollständigen Vertragsentwurf finden Sie als PDF im Anhang unserer E-Mail.

diff --git a/resources/views/pdf/contract-document.blade.php b/resources/views/pdf/contract-document.blade.php index 3dcd9a5..fbe66fb 100644 --- a/resources/views/pdf/contract-document.blade.php +++ b/resources/views/pdf/contract-document.blade.php @@ -42,5 +42,11 @@ {!! $document['annex'] !!} @endif + @foreach (\App\Documents\OfferTerms::annexes($booking) as $extraAnnex) +
+

{{ $extraAnnex['title'] }}

+ {!! $extraAnnex['html'] !!} +
+ @endforeach diff --git a/resources/views/pdf/contract.blade.php b/resources/views/pdf/contract.blade.php index 1731ef8..946057f 100644 --- a/resources/views/pdf/contract.blade.php +++ b/resources/views/pdf/contract.blade.php @@ -103,6 +103,11 @@
{{ $booking->offerHtml('stay.house_rules') }}
@endif + @foreach (\App\Documents\OfferTerms::annexes($booking) as $extraAnnex) +

Anlage: {{ $extraAnnex['title'] }}

+
{!! $extraAnnex['html'] !!}
+ @endforeach +

{{ $booking->offerText('contract.closing') }}

{{ ($owner['name'] ?? null) }}

diff --git a/resources/views/self-service/cancel.blade.php b/resources/views/self-service/cancel.blade.php index 62855fc..9f9f4bb 100644 --- a/resources/views/self-service/cancel.blade.php +++ b/resources/views/self-service/cancel.blade.php @@ -30,6 +30,10 @@
{{ $booking->offerHtml('stay.cancellation') }}
@endif + @if ($cost) +

Nach den vereinbarten Stornobedingungen würde eine Stornierung heute {{ $cost['fee'] === 0 ? 'keine Kosten' : \App\Support\Money::format($cost['fee']) }} verursachen ({{ $cost['tier_text'] }}).

+ @endif +
@csrf @if ($instant) diff --git a/tests/Feature/CancellationPolicyTest.php b/tests/Feature/CancellationPolicyTest.php new file mode 100644 index 0000000..d6f6448 --- /dev/null +++ b/tests/Feature/CancellationPolicyTest.php @@ -0,0 +1,179 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Mail::fake(); + Storage::fake('local'); + $this->withoutVite(); + } + + public function test_the_tier_depends_on_the_days_left_before_arrival(): void + { + $policy = $this->policy()->snapshot(); + + $this->assertSame(0, CancellationPolicy::tierFor($policy, 90)['percent']); + $this->assertSame(0, CancellationPolicy::tierFor($policy, 60)['percent']); + $this->assertSame(50, CancellationPolicy::tierFor($policy, 59)['percent']); + $this->assertSame(50, CancellationPolicy::tierFor($policy, 30)['percent']); + $this->assertSame(100, CancellationPolicy::tierFor($policy, 29)['percent']); + $this->assertSame(100, CancellationPolicy::tierFor($policy, 0)['percent']); + } + + public function test_the_policy_reads_like_the_contract_and_keeps_tiers_sorted(): void + { + $lines = CancellationPolicy::describe($this->policy(['tiers' => [['min_days' => 0, 'percent' => 100], ['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50]], 'replacement_fee' => 3500])->snapshot()); + + $this->assertSame('Rücktritt bis 60 Tage vor Mietbeginn: 0 % des Mietpreises', $lines[0]); + $this->assertSame('Rücktritt 59 bis 30 Tage vor Mietbeginn: 50 % des Mietpreises', $lines[1]); + $this->assertSame('Rücktritt ab 29 Tage vor Mietbeginn bis Mietbeginn: 100 % des Mietpreises', $lines[2]); + $this->assertStringContainsString('35,00', $lines[3]); + } + + public function test_cost_is_calculated_from_the_rent_or_from_the_total_as_the_rule_says(): void + { + $rent = $this->offerWith($this->policy(['base' => CancellationPolicy::BASE_RENT])); + $cost = CancellationCost::calculate($rent, CarbonImmutable::parse('2026-10-24')); + $this->assertSame(CancellationCost::rent($rent), $cost['base_amount']); + $this->assertLessThan($rent->total, $cost['base_amount'], 'cleaning is not part of the rent'); + $this->assertSame(100, $cost['percent']); + + $total = $this->offerWith($this->policy(['name' => 'Gesamt', 'base' => CancellationPolicy::BASE_TOTAL]), '2026-12-01', '2026-12-04'); + $this->assertSame($total->total, CancellationCost::calculate($total, CarbonImmutable::parse('2026-10-24'))['base_amount']); + } + + public function test_the_offer_freezes_the_rule_and_the_contract_can_show_it(): void + { + $policy = $this->policy(); + $template = ContractTemplate::query()->create(['name' => 'Direkt', 'version' => 1, 'body' => '

Storno:

{{ storno_regel }}', 'cancellation_policy_id' => $policy->id]); + $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); + + $policy->update(['tiers' => [['min_days' => 0, 'percent' => 5]]]); + + $this->assertSame(0, $offer->fresh()->offer_terms['cancellation_policy']['tiers'][0]['percent'] + 0 * 1); + $this->assertStringContainsString('Rücktritt bis 60 Tage vor Mietbeginn: 0 %', OfferTerms::document($offer->fresh())['body']); + } + + public function test_cancelling_records_the_cancellation_with_the_proposed_cost_and_a_task(): void + { + $booking = $this->offerWith($this->policy(), '2026-11-02', '2026-11-05', confirm: true); + + app(CancelBooking::class)->handle($booking->fresh()); + + $record = Cancellation::query()->sole(); + $this->assertTrue($record->has_policy); + $this->assertSame(100, $record->percent); + $this->assertSame(CancellationCost::rent($booking), $record->base_amount); + $this->assertSame($record->calculated_fee, $record->fee()); + $this->assertStringContainsString('Vorschlag nach Stornoregel', BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->sole()->note); + $this->assertStringContainsString('Stornokosten', BookingProgress::next($booking->fresh())['text']); + } + + public function test_guest_link_is_instant_only_while_the_rule_makes_it_free_and_shows_the_cost(): void + { + $this->travelTo(CarbonImmutable::parse('2026-09-25 10:00')); + $this->property->update(['cancellation_mode' => CancellationMode::InstantWhenFree]); + $policy = $this->policy(); + $far = $this->offerWith($policy, '2026-11-26', '2026-11-29', confirm: true); + $near = $this->offerWith($policy, '2026-11-20', '2026-11-23', confirm: true); + + $cancel = app(CancelBookingByGuest::class); + $this->assertSame(CancellationMode::Instant, $cancel->modeFor($far->fresh())); + $this->assertSame(CancellationMode::Request, $cancel->modeFor($near->fresh())); + + $this->get(SelfServiceLinks::cancel($near->fresh()))->assertOk()->assertSee('verursachen', false); + + $cancel->handle($far->fresh()); + $this->assertSame(0, Cancellation::query()->where('booking_id', $far->id)->sole()->fee()); + } + + public function test_the_cancellation_management_lists_decides_and_settles(): void + { + $booking = $this->offerWith($this->policy(), '2026-11-02', '2026-11-05', confirm: true); + app(CancelBooking::class)->handle($booking->fresh()); + $cancellation = Cancellation::query()->sole(); + $this->actingAs(User::factory()->create()); + + Livewire::test(ListCancellations::class) + ->assertSee($booking->reference) + ->callAction(TestAction::make('decide')->table($cancellation), ['final_fee' => '123.45', 'note' => 'Kulanz']) + ->callAction(TestAction::make('settle')->table($cancellation->fresh())); + + $fresh = $cancellation->fresh(); + $this->assertSame(12345, $fresh->final_fee); + $this->assertSame(Cancellation::SETTLED, $fresh->status); + $this->assertSame(12345, $fresh->fee()); + } + + /** + * @param array $attributes + */ + private function policy(array $attributes = []): CancellationPolicy + { + return CancellationPolicy::query()->create([ + 'name' => 'Direkt', + 'base' => CancellationPolicy::BASE_RENT, + 'tiers' => [['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]], + ...$attributes, + ]); + } + + private function booking(string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking + { + return Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => $arrival, 'departure' => $departure, 'guests' => 2]); + } + + private function offerWith(CancellationPolicy $policy, string $arrival = '2026-11-07', string $departure = '2026-11-10', bool $confirm = false): Booking + { + $template = ContractTemplate::query()->firstOrCreate(['name' => 'T'.$policy->id, 'version' => 1], ['cancellation_policy_id' => $policy->id]); + $offer = app(SendOffer::class)->handle($this->booking($arrival, $departure), ['contract_template_id' => $template->id]); + if ($confirm) { + $offer->update(['status' => BookingStatus::Confirmed, 'hold_expires_at' => null]); + } + + return $offer->fresh(); + } +} diff --git a/tests/Feature/ContractAnnexTest.php b/tests/Feature/ContractAnnexTest.php new file mode 100644 index 0000000..28106e6 --- /dev/null +++ b/tests/Feature/ContractAnnexTest.php @@ -0,0 +1,146 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Mail::fake(); + Storage::fake('local'); + $this->withoutVite(); + } + + public function test_conditions_decide_which_annexes_fit_a_booking(): void + { + $linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 2300, 'pricing' => 'per_item', 'is_active' => true]); + $portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt']); + $always = $this->annex('WLAN', ContractAnnex::ALWAYS); + $withLinen = $this->annex('Wäsche', ContractAnnex::EXTRA, $linen->id); + $viaPortal = $this->annex('Portal', ContractAnnex::CHANNEL, $portal->id); + $manual = $this->annex('Key', ContractAnnex::MANUAL); + $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$always->id, $withLinen->id, $viaPortal->id, $manual->id]]); + + $plain = $this->booking(); + $this->assertSame(['WLAN'], $template->annexesFor($plain)->pluck('name')->all()); + + $withExtra = $this->booking(['extras' => [$linen->id => 2], 'arrival' => '2026-12-01', 'departure' => '2026-12-04']); + $this->assertEqualsCanonicalizing(['WLAN', 'Wäsche'], $template->annexesFor($withExtra)->pluck('name')->all()); + + $fromPortal = $this->booking(['import_channel_id' => $portal->id, 'source' => 'portal', 'arrival' => '2026-11-20', 'departure' => '2026-11-23']); + $this->assertEqualsCanonicalizing(['WLAN', 'Portal'], $template->annexesFor($fromPortal)->pluck('name')->all()); + } + + public function test_the_offer_freezes_the_matching_annexes_and_shows_them_everywhere(): void + { + $annex = $this->annex('WLAN', ContractAnnex::ALWAYS, null, 'Anlage WLAN', '

WLAN für {{ mieter }}

'); + $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'body' => '

Vertrag

', 'annex_ids' => [$annex->id]]); + + $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); + + $this->assertSame([$annex->id], array_column($offer->offer_terms['annexes'], 'id')); + $annex->update(['body' => '

GEÄNDERT

']); + $rendered = OfferTerms::annexes($offer->fresh()); + $this->assertStringContainsString($offer->guest->full_name, $rendered[0]['html']); + $this->assertStringNotContainsString('GEÄNDERT', $rendered[0]['html']); + + $this->get(app(SendOffer::class)->offerUrl($offer))->assertOk()->assertSee('Anlage: Anlage WLAN'); + Storage::disk('local')->assertExists($offer->offer_path); + } + + public function test_an_explicit_selection_in_the_offer_replaces_the_automatic_one(): void + { + $auto = $this->annex('WLAN', ContractAnnex::ALWAYS); + $manual = $this->annex('Key', ContractAnnex::MANUAL); + $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$auto->id]]); + + $offer = app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id, 'annex_ids' => [$manual->id]]); + $this->assertSame(['Key'], array_column($offer->offer_terms['annexes'], 'name')); + + $none = app(SendOffer::class)->handle($this->booking(['arrival' => '2026-12-01', 'departure' => '2026-12-04']), ['contract_template_id' => $template->id, 'annex_ids' => []]); + $this->assertSame([], $none->offer_terms['annexes']); + } + + public function test_used_annex_versions_are_locked_and_new_versions_can_be_made(): void + { + $annex = $this->annex('WLAN', ContractAnnex::ALWAYS); + $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); + $this->assertTrue(ContractAnnexResource::canEdit($annex)); + + app(SendOffer::class)->handle($this->booking(), ['contract_template_id' => $template->id]); + $this->assertFalse(ContractAnnexResource::canEdit($annex->fresh())); + + $this->actingAs(User::factory()->create()); + Livewire::test(ListContractAnnexes::class)->callAction(TestAction::make('newVersion')->table($annex), []); + $this->assertSame([1, 2], ContractAnnex::query()->where('name', 'WLAN')->orderBy('version')->pluck('version')->all()); + } + + public function test_recording_extra_services_in_the_booking_changes_the_preselected_annexes(): void + { + $linen = Extra::query()->create(['property_id' => $this->property->id, 'name' => 'Wäschepaket', 'price' => 0, 'pricing' => 'per_item', 'is_active' => true]); + $annex = $this->annex('Wäsche', ContractAnnex::EXTRA, $linen->id); + $template = ContractTemplate::query()->create(['name' => 'T', 'version' => 1, 'annex_ids' => [$annex->id]]); + $this->property->update(['contract_template_id' => $template->id]); + $booking = $this->booking(); + $this->actingAs(User::factory()->create()); + + $this->assertSame([], OfferTerms::templateFor($booking)->annexesFor($booking)->all()); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction('services', ['items' => [['extra_id' => $linen->id, 'quantity' => 2]]]) + ->assertNotified('Zusatzleistungen gespeichert'); + + $booking = $booking->fresh(); + $this->assertSame([$linen->id => 2], $booking->extras); + $this->assertSame(['Wäsche'], OfferTerms::templateFor($booking)->annexesFor($booking)->pluck('name')->all()); + } + + private function annex(string $name, string $type, ?int $conditionId = null, string $title = 'Anlage', string $body = '

Text

'): ContractAnnex + { + return ContractAnnex::query()->create(['name' => $name, 'version' => 1, 'title' => $title, 'body' => $body, 'condition_type' => $type, 'condition_id' => $conditionId]); + } + + /** + * @param array $attributes + */ + private function booking(array $attributes = []): Booking + { + return Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create([ + 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'guests' => 2, ...$attributes, + ]); + } +}