diff --git a/app/Actions/CancelBooking.php b/app/Actions/CancelBooking.php new file mode 100644 index 0000000..b692ba5 --- /dev/null +++ b/app/Actions/CancelBooking.php @@ -0,0 +1,80 @@ +guest?->email)) { + throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.'); + } + + DB::transaction(function () use ($booking, $costsTask, $by): void { + $booking->lockForTransition(); + + if (! in_array($booking->status, BookingStatus::occupying(), true)) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert'); + } + + $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); + + 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()]); + } + }); + + $booking->loadMissing(['guest', 'property']); + + return $this->notify($booking, $notifyGuest); + } + + private function notify(Booking $booking, bool $notifyGuest): bool + { + $informed = true; + + try { + Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, cancelled: true)); + } catch (Throwable $exception) { + Log::warning('Stornomitteilung an den Vermieter nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + + if ($notifyGuest) { + try { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, cancelled: true)); + } catch (Throwable $exception) { + $informed = false; + Log::warning('Stornomail an den Gast nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + } + + return $informed; + } +} diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index 8c51362..50a6c39 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -15,6 +15,7 @@ enum BookingTaskKind: string implements HasLabel case BalanceRequest = 'balance_request'; case BalanceReminder = 'balance_reminder'; case CancellationRequest = 'cancellation_request'; + case CancellationFee = 'cancellation_fee'; public function getLabel(): string { @@ -23,12 +24,13 @@ public function getLabel(): string self::BalanceRequest => 'Restzahlung bald fällig – anfordern', self::BalanceReminder => 'Restzahlung überfällig – anmahnen', self::CancellationRequest => 'Stornierungswunsch des Gastes', + self::CancellationFee => 'Stornokosten prüfen und abrechnen', }; } public function isPayment(): bool { - return $this !== self::CancellationRequest; + return ! in_array($this, [self::CancellationRequest, self::CancellationFee], true); } /** @@ -42,7 +44,7 @@ public function reminder(): ?array self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'], self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'], self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'], - self::CancellationRequest => null, + self::CancellationRequest, self::CancellationFee => null, }; } } diff --git a/app/Filament/Resources/Bookings/BookingResource.php b/app/Filament/Resources/Bookings/BookingResource.php index 5ffe7ee..4132347 100644 --- a/app/Filament/Resources/Bookings/BookingResource.php +++ b/app/Filament/Resources/Bookings/BookingResource.php @@ -8,7 +8,9 @@ use App\Filament\Resources\Bookings\Pages\CreateBooking; use App\Filament\Resources\Bookings\Pages\ListBookings; use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager; use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager; +use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager; use App\Filament\Resources\Bookings\Schemas\BookingForm; use App\Filament\Resources\Bookings\Schemas\BookingInfolist; use App\Filament\Resources\Bookings\Tables\BookingsTable; @@ -72,6 +74,8 @@ public static function getRelations(): array { return [ PaymentsRelationManager::class, + TasksRelationManager::class, + MessagesRelationManager::class, ]; } diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index 95171a8..1ffa36b 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -2,6 +2,7 @@ namespace App\Filament\Resources\Bookings\Pages; +use App\Actions\CancelBooking; use App\Actions\ConfirmBooking; use App\Actions\DeclineBooking; use App\Actions\SendOffer; @@ -189,6 +190,16 @@ 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('contractText') + ->label('Vertragstext ansehen') + ->icon(Heroicon::OutlinedDocumentMagnifyingGlass) + ->color('gray') + ->visible(fn (): bool => $this->record->offer_terms !== null) + ->modalHeading(fn (): string => 'Vertrag '.$this->record->reference) + ->modalContent(fn () => view('filament.booking-contract', ['booking' => $this->record])) + ->modalSubmitAction(false) + ->modalCancelActionLabel('Schließen') + ->modalWidth('4xl'), Action::make('contract') ->label('Mietvertrag') ->icon(Heroicon::OutlinedDocumentText) @@ -209,12 +220,23 @@ protected function getHeaderActions(): array ->icon(Heroicon::OutlinedNoSymbol) ->color('danger') ->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true)) - ->requiresConfirmation() - ->modalDescription('Der Zeitraum wird wieder freigegeben. Der Gast wird nicht automatisch benachrichtigt.') - ->action(function (): void { - $this->record->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); + ->modalHeading('Buchung stornieren') + ->modalDescription('Der Zeitraum wird wieder freigegeben. Gast und Vermieter erhalten eine Stornierungs-E-Mail; die Stornokosten bleiben als Aufgabe offen.') + ->schema([ + Toggle::make('notify_guest')->label('Gast per E-Mail informieren')->default(true), + Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true), + ]) + ->action(function (array $data, CancelBooking $cancel): void { + try { + $informed = $cancel->handle($this->record, (bool) $data['notify_guest'], (bool) $data['costs_task'], auth()->user()->name); + } catch (ReservationException $exception) { + Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); - Notification::make()->title('Buchung storniert')->success()->send(); + return; + } + + $notification = Notification::make()->title('Buchung storniert'); + ($informed ? $notification->success() : $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte den Gast selbst informieren.'))->send(); }), ]), ]; diff --git a/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php b/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php new file mode 100644 index 0000000..e73c46b --- /dev/null +++ b/app/Filament/Resources/Bookings/RelationManagers/MessagesRelationManager.php @@ -0,0 +1,40 @@ +recordTitleAttribute('subject') + ->defaultSort('sent_at', 'desc') + ->emptyStateHeading('Noch keine E-Mails zu dieser Buchung') + ->description('Betreff und Empfängerart jeder E-Mail zu dieser Buchung. Im Testbetrieb gehen alle Mails an die Testadresse.') + ->columns([ + TextColumn::make('sent_at')->label('Gesendet')->dateTime('d.m.Y, H:i'), + TextColumn::make('audience')->label('An')->badge()->formatStateUsing(fn (string $state): string => match ($state) { + 'guest' => 'Gast', + 'landlord' => 'Vermieter', + default => 'Testadresse', + }), + TextColumn::make('subject')->label('Betreff')->wrap(), + ]); + } +} diff --git a/app/Filament/Resources/Bookings/RelationManagers/TasksRelationManager.php b/app/Filament/Resources/Bookings/RelationManagers/TasksRelationManager.php new file mode 100644 index 0000000..87ba5fa --- /dev/null +++ b/app/Filament/Resources/Bookings/RelationManagers/TasksRelationManager.php @@ -0,0 +1,48 @@ +recordTitleAttribute('kind') + ->defaultSort('created_at', 'desc') + ->emptyStateHeading('Keine Aufgaben zu dieser Buchung') + ->columns([ + TextColumn::make('kind')->label('Aufgabe')->badge(), + TextColumn::make('status')->label('Status')->badge(), + TextColumn::make('due_on')->label('Seit / fällig')->date('d.m.Y')->placeholder('–'), + TextColumn::make('note')->label('Hinweis')->wrap()->placeholder('–'), + ]) + ->recordActions([ + Action::make('done') + ->label('Erledigt') + ->icon(Heroicon::OutlinedCheck) + ->color('success') + ->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open) + ->action(fn (BookingTask $record) => $record->complete(auth()->user()->name)), + ]); + } +} diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index 5419f7a..651b99e 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -3,24 +3,68 @@ namespace App\Filament\Resources\Bookings\Schemas; use App\Models\Booking; +use App\Support\BookingProgress; use App\Support\Money; +use Carbon\CarbonImmutable; use Filament\Infolists\Components\RepeatableEntry; use Filament\Infolists\Components\RepeatableEntry\TableColumn; use Filament\Infolists\Components\TextEntry; use Filament\Schemas\Components\Grid; use Filament\Schemas\Components\Section; use Filament\Schemas\Schema; +use Illuminate\Support\HtmlString; class BookingInfolist { + /** + * The steps of the process as a row of chips. + */ + private static function timeline(Booking $booking): HtmlString + { + $style = [ + 'done' => 'background:#dcfce7;color:#14532d', + 'current' => 'background:#fef3c7;color:#78350f;font-weight:700', + 'todo' => 'background:#f3f4f6;color:#4b5563', + 'skipped' => 'background:#f3f4f6;color:#9ca3af;text-decoration:line-through', + ]; + $icon = ['done' => '✓ ', 'current' => '● ', 'todo' => '', 'skipped' => '']; + + return new HtmlString('
'.collect(BookingProgress::steps($booking))->map(fn (array $step): string => ''.$icon[$step['state']].e($step['label']).($step['detail'] ? ' · '.e($step['detail']) : '').'')->implode('').'
'); + } + public static function configure(Schema $schema): Schema { return $schema ->columns(3) ->components([ + Section::make('Vorgang') + ->columnSpanFull() + ->schema([ + TextEntry::make('process')->label('Art des Vorgangs')->state(fn (Booking $record): string => BookingProgress::kindLabel($record)), + TextEntry::make('next') + ->label(fn (Booking $record): string => 'Nächster Schritt: '.BookingProgress::next($record)['title']) + ->state(fn (Booking $record): string => BookingProgress::next($record)['text']) + ->color(fn (Booking $record): string => BookingProgress::next($record)['color']) + ->weight('bold'), + TextEntry::make('steps') + ->label('Verlauf') + ->state(fn (Booking $record): HtmlString => self::timeline($record)) + ->html() + ->columnSpanFull(), + ]), Grid::make(1) ->columnSpan(2) ->schema([ + Section::make('Vertrag') + ->columns(2) + ->schema([ + TextEntry::make('contract_template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) ? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].')' : ($record->offer_terms ? 'Texte der Webseite (Stand '.CarbonImmutable::parse($record->offer_terms['captured_at'])->format('d.m.Y').')' : 'Noch kein Angebot / Vertrag')), + TextEntry::make('contract_state')->label('Dokumente')->state(fn (Booking $record): string => collect([ + $record->offer_path ? 'Angebot (PDF) Version '.$record->offer_version : null, + $record->contract_path ? 'Mietvertrag (PDF, unveränderlich, Prüfsumme '.substr((string) $record->contract_pdf_sha256, 0, 10).')' : null, + ])->filter()->implode(' · ') ?: 'Noch kein Dokument – der Vertrag entsteht mit dem Angebot bzw. der Bestätigung'), + TextEntry::make('contract_mail')->label('Zustellung')->state(fn (Booking $record): string => $record->confirmation_sent_at ? 'Bestätigung mit Vertrag gesendet am '.$record->confirmation_sent_at->format('d.m.Y, H:i') : ($record->confirmation_failed_at ? 'Versand fehlgeschlagen' : 'Noch nicht gesendet'))->columnSpanFull(), + ]), Section::make('Aufenthalt') ->columns(3) ->schema([ diff --git a/app/Filament/Resources/Bookings/Tables/BookingsTable.php b/app/Filament/Resources/Bookings/Tables/BookingsTable.php index 4fb0a00..bff8c98 100644 --- a/app/Filament/Resources/Bookings/Tables/BookingsTable.php +++ b/app/Filament/Resources/Bookings/Tables/BookingsTable.php @@ -37,6 +37,9 @@ public static function configure(Table $table, ?int $guestId = null): Table } if (filled($filters['status']['values'] ?? [])) { $records = $records->whereIn('status_key', $filters['status']['values']); + } elseif (! ($filters['show_closed']['isActive'] ?? false)) { + // Cancelled, declined and expired requests leave the main list (they stay available as archive). + $records = $records->reject(fn (array $record): bool => in_array($record['status_key'], ['cancelled', 'declined', 'expired'], true)); } $column = in_array($sortColumn, ['arrival', 'departure', 'reference', 'guest', 'source', 'total'], true) ? $sortColumn : 'arrival'; $records = $records->sortBy($column, SORT_REGULAR, $sortDirection === 'desc'); @@ -69,6 +72,7 @@ public static function configure(Table $table, ?int $guestId = null): Table 'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed', ]), Filter::make('upcoming')->label('Nur kommende Aufenthalte'), + Filter::make('show_closed')->label('Archiv anzeigen (storniert, abgelehnt, abgelaufen)'), Filter::make('without_guest')->label('Gastzuordnung offen'), ]) ->recordUrl(fn (array $record): string => $record['url']) diff --git a/app/Listeners/LogBookingMail.php b/app/Listeners/LogBookingMail.php new file mode 100644 index 0000000..bece040 --- /dev/null +++ b/app/Listeners/LogBookingMail.php @@ -0,0 +1,40 @@ +data['booking'] ?? null; + if (! $booking instanceof Booking) { + return; + } + + $recipients = collect($event->message->getTo())->map(fn ($address): string => mb_strtolower($address->getAddress())); + $guest = mb_strtolower((string) $booking->guest?->email); + $audience = ! Settings::isLive() ? 'test' : ($guest !== '' && $recipients->contains($guest) ? 'guest' : 'landlord'); + + BookingMessage::query()->create([ + 'booking_id' => $booking->id, + 'audience' => $audience, + 'subject' => mb_substr((string) $event->message->getSubject(), 0, 255), + 'sent_at' => now(), + ]); + } catch (Throwable) { + // The log is a convenience; the mail has been sent. + } + } +} diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 9fce7e0..8b2d048 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -236,6 +236,22 @@ public function review(): HasOne return $this->hasOne(Review::class); } + /** + * @return HasMany + */ + public function messages(): HasMany + { + return $this->hasMany(BookingMessage::class); + } + + /** + * @return HasMany + */ + public function tasks(): HasMany + { + return $this->hasMany(BookingTask::class); + } + /** * @return HasMany */ diff --git a/app/Models/BookingMessage.php b/app/Models/BookingMessage.php new file mode 100644 index 0000000..1e3dd73 --- /dev/null +++ b/app/Models/BookingMessage.php @@ -0,0 +1,37 @@ + + */ + protected function casts(): array + { + return ['sent_at' => 'immutable_datetime']; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } +} diff --git a/app/Support/BookingProgress.php b/app/Support/BookingProgress.php new file mode 100644 index 0000000..26f5b95 --- /dev/null +++ b/app/Support/BookingProgress.php @@ -0,0 +1,128 @@ +importChannel ?? $booking->originChannel; + if ($channel !== null) { + return $channel->booking_model === ChannelBookingModel::PortalBooking ? self::PORTAL_BOOKING : self::PORTAL_INQUIRY; + } + + return $booking->source === 'website' ? self::OWN : self::MANUAL; + } + + public static function kindLabel(Booking $booking): string + { + $portal = ($booking->importChannel ?? $booking->originChannel)?->name; + + return match (self::kind($booking)) { + self::OWN => 'Eigene Webseite: Anfrage → Angebot → Annahme', + self::MANUAL => 'Manuell erfasste Buchung', + self::PORTAL_BOOKING => 'Portal-Buchung'.($portal ? " ({$portal})" : '').': beim Portal verbindlich, Vertrag von uns', + default => 'Portal-Anfrage'.($portal ? " ({$portal})" : '').': wir antworten persönlich, Angebot und Vertrag von uns', + }; + } + + /** + * @return list state: done | current | todo | skipped + */ + public static function steps(Booking $booking): array + { + $today = CarbonImmutable::today(); + $kind = self::kind($booking); + $closed = in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true); + $binding = in_array($booking->status, BookingStatus::occupying(), true); + $steps = []; + + $steps[] = ['label' => 'Anfrage / Eingang', 'state' => 'done', 'detail' => $booking->created_at?->format('d.m.Y')]; + + $needsOffer = in_array($kind, [self::OWN, self::PORTAL_INQUIRY, self::MANUAL], true); + if ($needsOffer) { + $steps[] = [ + 'label' => 'Angebot', + 'state' => $booking->offer_version > 0 || $binding ? 'done' : ($closed ? 'skipped' : 'current'), + 'detail' => $booking->offer_version > 0 ? 'Version '.$booking->offer_version.', '.$booking->offer_sent_at?->format('d.m.Y') : null, + ]; + } + + $steps[] = [ + 'label' => $needsOffer ? 'Annahme / Vertrag' : 'Vertrag senden', + 'state' => $binding ? ($booking->confirmation_sent_at !== null || $booking->accepted_at !== null || $needsOffer ? 'done' : 'current') : ($closed ? 'skipped' : ($booking->status === BookingStatus::OfferSent ? 'current' : 'todo')), + 'detail' => $booking->accepted_at ? 'angenommen '.$booking->accepted_at->format('d.m.Y') : ($booking->confirmation_sent_at ? 'Vertrag gesendet '.$booking->confirmation_sent_at->format('d.m.Y') : null), + ]; + + if ($booking->wantsPaymentTasks()) { + $paid = $booking->paidAmount(); + $steps[] = ['label' => 'Anzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->deposit && $binding ? 'done' : ($binding ? 'current' : 'todo')), 'detail' => $booking->deposit_due_on ? 'fällig '.$booking->deposit_due_on->format('d.m.Y') : null]; + $steps[] = ['label' => 'Restzahlung', 'state' => $closed ? 'skipped' : ($paid >= $booking->total && $binding ? 'done' : ($binding && $paid >= $booking->deposit ? 'current' : 'todo')), 'detail' => 'fällig '.$booking->balance_due_on?->format('d.m.Y')]; + } else { + $steps[] = ['label' => 'Zahlung', 'state' => 'skipped', 'detail' => 'läuft über das Portal']; + } + + $arrived = ! $closed && $binding && $booking->arrival <= $today; + $left = ! $closed && $binding && $booking->departure <= $today; + $steps[] = ['label' => 'Anreise', 'state' => $closed ? 'skipped' : ($arrived ? 'done' : 'todo'), 'detail' => $booking->arrival->format('d.m.Y')]; + $steps[] = ['label' => 'Vor Ort', 'state' => $closed ? 'skipped' : ($arrived && ! $left ? 'current' : ($left ? 'done' : 'todo')), 'detail' => null]; + $steps[] = ['label' => 'Abreise', 'state' => $closed ? 'skipped' : ($left ? 'done' : 'todo'), 'detail' => $booking->departure->format('d.m.Y')]; + + return $steps; + } + + /** + * @return array{title: string, text: string, color: string} + */ + public static function next(Booking $booking): array + { + $today = CarbonImmutable::today(); + $kind = self::kind($booking); + $money = fn (int $cents): string => Money::format($cents); + + $openTasks = BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)->get(); + $costs = $openTasks->firstWhere('kind', BookingTaskKind::CancellationFee); + $wish = $openTasks->firstWhere('kind', BookingTaskKind::CancellationRequest); + + if ($wish !== null && $booking->status !== BookingStatus::Cancelled) { + return ['title' => 'Stornierungswunsch des Gastes', 'text' => 'Der Gast möchte stornieren. Bitte prüfen: stornieren (mit Mail an den Gast) oder ablehnen, und Stornokosten klären.', 'color' => 'danger']; + } + + 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::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 + ? 'Kontaktdaten des Gastes eintragen, dann „Direkt bestätigen“ – der Vertrag geht per E-Mail an den Gast.' + : 'Angebot senden („Angebot senden“) oder ablehnen.'.($booking->hold_expires_at ? ' Vorgemerkt bis '.$booking->hold_expires_at->format('d.m.Y, H:i').' Uhr.' : ' Es ist kein Zeitraum vorgemerkt.'), 'color' => 'warning'], + $booking->status === BookingStatus::OfferSent => ['title' => 'Wartet auf den Gast', 'text' => 'Angebot Version '.$booking->offer_version.' ist beim Gast. Gültig bis '.$booking->hold_expires_at?->format('d.m.Y, H:i').' Uhr.', 'color' => 'info'], + $booking->confirmation_failed_at !== null && $booking->confirmation_sent_at === null => ['title' => 'Bestätigung nicht zugestellt', 'text' => 'Die Buchung steht, aber die Bestätigungs-E-Mail ist nicht beim Gast angekommen. „Bestätigung erneut senden“.', 'color' => 'danger'], + $kind === self::PORTAL_BOOKING && $booking->confirmation_sent_at === null && $booking->contract_path === null => ['title' => 'Vertrag senden', 'text' => 'Die Buchung ist beim Portal verbindlich. Bitte den Vertrag an den Gast senden (Bestätigung erneut senden).', 'color' => 'warning'], + $booking->wantsPaymentTasks() && $booking->openDeposit() > 0 && $booking->status === BookingStatus::Confirmed => ['title' => 'Anzahlung offen', 'text' => $money($booking->openDeposit()).' fällig bis '.$booking->deposit_due_on?->format('d.m.Y').'. Zahlungseingang unter „Zahlungen“ erfassen.', 'color' => $booking->deposit_due_on?->isPast() ? 'danger' : 'warning'], + $booking->wantsPaymentTasks() && $booking->openAmount() > 0 && $booking->balance_due_on?->lessThanOrEqualTo($today->addDays(14)) => ['title' => 'Restzahlung offen', 'text' => $money($booking->openAmount()).' fällig bis '.$booking->balance_due_on->format('d.m.Y').'.', 'color' => $booking->balance_due_on->isPast() ? 'danger' : 'warning'], + $booking->arrival <= $today && $booking->departure > $today => ['title' => 'Gast ist vor Ort', 'text' => 'Abreise am '.$booking->departure->format('d.m.Y').'.', 'color' => 'success'], + $booking->arrival > $today => ['title' => 'Anreise in '.$today->diffInDays($booking->arrival).' Tagen', 'text' => 'Anreise am '.$booking->arrival->format('d.m.Y').'. Anreise-Informationen gehen '.$booking->property->arrival_info_days_before.' Tage vorher automatisch an den Gast.', 'color' => 'success'], + default => ['title' => 'Aufenthalt beendet', 'text' => 'Abreise war am '.$booking->departure->format('d.m.Y').'.', 'color' => 'gray'], + }; + } +} diff --git a/database/migrations/2026_10_30_160954_create_booking_messages_table.php b/database/migrations/2026_10_30_160954_create_booking_messages_table.php new file mode 100644 index 0000000..fbe53e3 --- /dev/null +++ b/database/migrations/2026_10_30_160954_create_booking_messages_table.php @@ -0,0 +1,32 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->string('audience', 12); + $table->string('subject', 255); + $table->timestamp('sent_at'); + $table->index(['booking_id', 'sent_at']); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::dropIfExists('booking_messages'); + } +}; diff --git a/resources/views/filament/booking-contract.blade.php b/resources/views/filament/booking-contract.blade.php new file mode 100644 index 0000000..c543e2b --- /dev/null +++ b/resources/views/filament/booking-contract.blade.php @@ -0,0 +1,22 @@ +@php($document = \App\Documents\OfferTerms::document($booking)) +
+

+ Der Vertragstext, wie er beim Angebot festgehalten wurde (Stand {{ \Carbon\CarbonImmutable::parse($booking->offer_terms['captured_at'])->format('d.m.Y, H:i') }} Uhr). + @if ($booking->offer_hash) Prüfsumme des Angebots: {{ substr($booking->offer_hash, 0, 16) }}… @endif +

+ + @if ($document) +
{!! $document['body'] !!}
+ @if ($document['annex']) +
+

{{ $document['annex_title'] ?: 'Anlage' }}

+
{!! $document['annex'] !!}
+ @endif + @else +
{{ $booking->offerHtml('contract.terms') }}
+ @if ($booking->offerText('stay.cancellation')) +

Rücktritt / Stornierung

+
{{ $booking->offerHtml('stay.cancellation') }}
+ @endif + @endif +
diff --git a/tests/Feature/BookingFileTest.php b/tests/Feature/BookingFileTest.php new file mode 100644 index 0000000..25ab0d9 --- /dev/null +++ b/tests/Feature/BookingFileTest.php @@ -0,0 +1,158 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Storage::fake('local'); + $this->withoutVite(); + } + + public function test_next_step_follows_the_state_of_the_booking(): void + { + $request = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']); + $this->assertSame('Anfrage prüfen', BookingProgress::next($request)['title']); + + Mail::fake(); + $offer = app(SendOffer::class)->handle($request); + $this->assertSame('Wartet auf den Gast', BookingProgress::next($offer)['title']); + + $confirmed = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05', 'deposit_due_on' => '2026-10-25', 'balance_due_on' => '2026-11-20', 'total' => 100000, 'deposit' => 30000]); + $this->assertSame('Anzahlung offen', BookingProgress::next($confirmed)['title']); + + $this->travelTo(CarbonImmutable::parse('2026-12-02 12:00')); + $confirmed->update(['status' => BookingStatus::Paid, 'total' => 0, 'deposit' => 0]); + $this->assertSame('Gast ist vor Ort', BookingProgress::next($confirmed->fresh())['title']); + $this->assertContains('current', array_column(BookingProgress::steps($confirmed->fresh()), 'state')); + } + + public function test_portal_booking_is_recognised_without_payment_steps_and_asks_to_send_the_contract(): void + { + $portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking']); + $booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'import_channel_id' => $portal->id, 'source' => 'portal', 'arrival' => '2026-12-01', 'departure' => '2026-12-05']); + + $this->assertSame(BookingProgress::PORTAL_BOOKING, BookingProgress::kind($booking)); + $this->assertStringContainsString('FeWo-direkt', BookingProgress::kindLabel($booking)); + $this->assertSame('Vertrag senden', BookingProgress::next($booking)['title']); + $this->assertContains('Zahlung', array_column(BookingProgress::steps($booking), 'label')); + $this->assertNotContains('Anzahlung', array_column(BookingProgress::steps($booking), 'label')); + } + + public function test_every_booking_mail_lands_in_the_communication_log_with_its_audience(): void + { + $booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']); + + app(SendOffer::class)->handle($booking); + $this->assertSame(['test'], BookingMessage::query()->pluck('audience')->unique()->all()); + + Settings::tenant()->update(['operating_mode' => Settings::MODE_LIVE]); + Settings::applyMailRouting(); + BookingMessage::query()->delete(); + $other = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-12-01', 'departure' => '2026-12-04']); + app(SendOffer::class)->handle($other); + + $message = BookingMessage::query()->where('booking_id', $other->id)->sole(); + $this->assertSame('guest', $message->audience); + $this->assertStringContainsString('Angebot', $message->subject); + } + + public function test_cancellation_by_the_landlord_informs_guest_and_landlord_and_leaves_a_cost_task(): void + { + $booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']); + BookingTask::query()->create(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationRequest, 'status' => BookingTaskStatus::Open]); + Mail::fake(); + + $this->assertTrue(app(CancelBooking::class)->handle($booking, notifyGuest: true)); + + $this->assertSame(BookingStatus::Cancelled, $booking->fresh()->status); + Mail::assertSent(BookingCancelled::class, fn (BookingCancelled $mail): bool => $mail->cancelled); + Mail::assertSent(CancellationRequested::class, 1); + $this->assertSame(BookingTaskStatus::Done, BookingTask::query()->where('kind', BookingTaskKind::CancellationRequest)->sole()->status); + $this->assertSame(BookingTaskStatus::Open, BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->sole()->status); + $this->assertSame(0, Booking::query()->occupying()->count()); + } + + public function test_cancellation_without_guest_mail_and_the_admin_action_offer_both_choices(): void + { + $booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']); + Mail::fake(); + $this->actingAs(User::factory()->create()); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->callAction(TestAction::make('cancel')->arguments([]), ['notify_guest' => false, 'costs_task' => false]) + ->assertNotified('Buchung storniert'); + + Mail::assertNotSent(BookingCancelled::class); + Mail::assertSent(CancellationRequested::class, 1); + $this->assertSame(0, BookingTask::query()->where('kind', BookingTaskKind::CancellationFee)->count()); + } + + public function test_cancelled_bookings_leave_the_main_list_but_stay_in_the_archive_filter(): void + { + $active = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-12-01', 'departure' => '2026-12-05']); + $cancelled = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Cancelled, 'arrival' => '2026-12-10', 'departure' => '2026-12-12']); + $this->actingAs(User::factory()->create()); + + Livewire::test(ListBookings::class) + ->assertSee($active->reference) + ->assertDontSee($cancelled->reference) + ->filterTable('show_closed', true) + ->assertSee($cancelled->reference); + } + + public function test_the_booking_page_shows_process_contract_tasks_and_mail_log(): void + { + Mail::fake(); + $booking = app(SendOffer::class)->handle(Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10'])); + $this->actingAs(User::factory()->create()); + + Livewire::test(ViewBooking::class, ['record' => $booking->getRouteKey()]) + ->assertSee('Nächster Schritt: Wartet auf den Gast') + ->assertSee('Vertrag') + ->assertSee('Angebot (PDF) Version 1'); + + Livewire::test(MessagesRelationManager::class, ['ownerRecord' => $booking, 'pageClass' => ViewBooking::class])->assertSuccessful(); + } +}