diff --git a/app/Actions/CreateReservation.php b/app/Actions/CreateReservation.php index dad25c1..b44dec2 100644 --- a/app/Actions/CreateReservation.php +++ b/app/Actions/CreateReservation.php @@ -191,8 +191,20 @@ private function sendMails(Booking $booking): void $offerSent = false; } + // v0.11: details for the offer are missing – the data request asks for them (and then replaces the receipt). + $asked = false; + if (! $offerSent) { + try { + $request = app(RequestCaseData::class)->forNextStep($booking); + $asked = $request?->last_sent_at !== null; + $booking->refresh(); + } catch (Throwable $exception) { + Log::warning('Rückfrage fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]); + } + } + try { - if (! $offerSent && filled($booking->guest?->email)) { + if (! $offerSent && ! $asked && filled($booking->guest?->email)) { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking)); } Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers)); diff --git a/app/Actions/RequestCaseData.php b/app/Actions/RequestCaseData.php new file mode 100644 index 0000000..7b61b6e --- /dev/null +++ b/app/Actions/RequestCaseData.php @@ -0,0 +1,320 @@ +}|null + */ + public static function needs(Booking $booking): ?array + { + $booking->loadMissing('guest'); + if (in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true) || $booking->isInternal()) { + return null; + } + + if ($booking->isBinding()) { + // A binding booking (also from a portal, E-036) stays binding; only administrative guest details are asked for. + if ($booking->departure->isPast()) { + return null; + } + $fields = array_values(array_filter(CaseRequirements::missing($booking), fn (string $field): bool => str_starts_with($field, 'guest.'))); + + return $fields === [] ? null : ['purpose' => self::FOR_BOOKING, 'fields' => $fields]; + } + + if ($booking->intake === IntakeKind::Booking || $booking->status !== BookingStatus::Reserved || $booking->offer_version > 0) { + return null; + } + + $purpose = match (true) { + $booking->process()->preReservation() => self::FOR_OFFER, + $booking->wish_at !== null => self::FOR_WISH, + default => null, + }; + if ($purpose === null) { + return null; + } + + $fields = CaseRequirements::missing($booking, $purpose === self::FOR_WISH ? CaseRequirements::WISH_CONFIRMATION : CaseRequirements::OFFER); + + return $fields === [] ? null : ['purpose' => $purpose, 'fields' => $fields]; + } + + /** + * Starts the request for the next step if details are missing and none runs yet. Returns the running request. + */ + public function forNextStep(Booking $booking, ?DataRequestMode $mode = null): ?DataRequest + { + $needs = self::needs($booking); + // Without an e-mail address there is no way back to the guest: the case shows "enter the contact details". + if ($needs === null || ! CaseRequirements::isValid('guest.email', $booking->guest?->email)) { + return null; + } + + $request = DB::transaction(function () use ($booking, $needs, $mode): DataRequest { + $booking->lockForTransition(); + $running = $booking->openDataRequest(); + if ($running !== null) { + return $running; + } + + $mode ??= $booking->process()->dataRequestMode(); + + return $booking->dataRequests()->create([ + 'tenant_id' => $booking->tenant_id, + 'status' => match (true) { + $mode === DataRequestMode::Manual => DataRequest::MANUAL, + $mode === DataRequestMode::Automatic && self::mayGoOutAutomatically() => DataRequest::OPEN, + default => DataRequest::DRAFT, + }, + 'mode' => $mode, + 'purpose' => $needs['purpose'], + 'fields' => $needs['fields'], + 'last_message' => DataRequest::INITIAL, + ]); + }); + + if ($request->wasRecentlyCreated) { + CaseLog::record($booking, 'data_request', match ($request->status) { + DataRequest::OPEN => 'Fehlende Angaben werden beim Gast angefragt', + DataRequest::DRAFT => 'Rückfrage nach fehlenden Angaben vorbereitet – wartet auf Ihre Freigabe', + default => 'Fehlende Angaben: bitte selbst beim Gast nachfragen (Textvorschlag im Vorgang)', + }, data: ['fields' => $request->fields], actor: CaseLog::SYSTEM); + + if ($request->status === DataRequest::OPEN) { + $this->send($request, DataRequest::INITIAL); + } + } + + return $request; + } + + /** + * The landlord releases the prepared question (or asks now although the case is set to manual). + */ + public function approve(DataRequest $request): bool + { + if (! $request->isRunning()) { + return false; + } + if (! CaseRequirements::isValid('guest.email', $request->booking->guest?->email)) { + return false; + } + + $kind = $request->last_message === DataRequest::FOLLOWUP ? DataRequest::FOLLOWUP : DataRequest::INITIAL; + $request->update(['status' => DataRequest::OPEN]); + + return $this->send($request, $kind); + } + + /** + * Sends the question, follow-up or reminder. A failing mail is shown in the case; the landlord takes over. + */ + public function send(DataRequest $request, string $kind): bool + { + $booking = $request->booking()->with(['guest', 'property'])->firstOrFail(); + $profile = $booking->process(); + $needs = self::needs($booking); + if ($needs === null) { + $this->close($request, DataRequest::COMPLETED, 'alle Angaben da'); + + return false; + } + + $request->fields = $needs['fields']; + if ($kind === DataRequest::FOLLOWUP) { + $request->followups_sent++; + $request->link_version++; + } + if ($kind === DataRequest::REMINDER) { + $request->reminders_sent++; + } + + try { + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new DataRequested($booking, $request, $kind, $this->url($request, $booking))); + } catch (Throwable $exception) { + Log::warning('Rückfrage nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + $request->forceFill(['status' => DataRequest::MANUAL])->save(); + BookingTask::openOnce($booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => 'Die Rückfrage konnte nicht zugestellt werden – bitte die E-Mail-Adresse prüfen oder selbst nachfragen.']); + CaseLog::record($booking, 'data_request', 'Rückfrage konnte nicht zugestellt werden', actor: CaseLog::SYSTEM); + + return false; + } + + $request->forceFill([ + 'status' => DataRequest::OPEN, + 'last_message' => $kind, + 'last_sent_at' => now(), + 'response_due_at' => now()->addHours($profile->reminderHours()), + 'next_reminder_at' => now()->addHours($profile->reminderHours()), + ])->save(); + CaseLog::record($booking, 'data_request', match ($kind) { + DataRequest::FOLLOWUP => 'Gezielte Folgefrage an den Gast ('.$request->followups_sent.'.)', + DataRequest::REMINDER => 'Erinnerung an den Gast ('.$request->reminders_sent.'.)', + default => 'Rückfrage an den Gast gesendet', + }.': '.implode(', ', CaseRequirements::labels($request->fields)), actor: CaseLog::SYSTEM); + + return true; + } + + /** + * Details arrived (any source): the open reminder is cancelled; if everything is there the request ends, otherwise + * a targeted follow-up question follows within its limit (CH-15–17). The landlord's own entries never trigger a + * question to the guest. + */ + public function answered(Booking $booking, FactContribution $contribution, FactSource $source): void + { + $request = $booking->openDataRequest(); + if ($request === null) { + return; + } + + $needs = self::needs($booking->refresh()); + if ($needs === null) { + $this->close($request, DataRequest::COMPLETED, 'alle Angaben da'); + + return; + } + + if ($source->isAuthoritative() || $request->status !== DataRequest::OPEN || (! $contribution->anyApplied() && ! $contribution->needsReview())) { + $request->update(['fields' => $needs['fields']]); + + return; + } + + $request->forceFill(['answered_at' => now(), 'next_reminder_at' => null, 'fields' => $needs['fields']])->save(); + + if ($request->followups_sent >= $booking->process()->followupsMax()) { + $this->handOver($request, 'Antwort weiterhin unvollständig – die Grenze der Folgefragen ist erreicht.'); + + return; + } + + if ($request->mode === DataRequestMode::Automatic && self::mayGoOutAutomatically()) { + $this->send($request, DataRequest::FOLLOWUP); + + return; + } + + $request->forceFill(['status' => $request->mode === DataRequestMode::Manual ? DataRequest::MANUAL : DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP])->save(); + CaseLog::record($booking, 'data_request', 'Antwort unvollständig – Folgefrage vorbereitet: '.implode(', ', CaseRequirements::labels($needs['fields'])), actor: CaseLog::SYSTEM); + } + + /** + * Due reminders of every running request (scheduler). At the limit the landlord takes over; nothing changes any + * deadline of the case. + */ + public function remindDue(): int + { + $count = 0; + $due = DataRequest::query()->where('status', DataRequest::OPEN)->whereNotNull('next_reminder_at')->where('next_reminder_at', '<=', now())->with('booking')->get(); + + foreach ($due as $request) { + $booking = $request->booking; + if ($booking === null || self::needs($booking) === null) { + $this->close($request, $booking === null ? DataRequest::STOPPED : DataRequest::COMPLETED, $booking === null ? 'Vorgang entfernt' : 'nichts mehr offen'); + + continue; + } + + if ($request->reminders_sent >= $booking->process()->remindersMax()) { + $this->handOver($request, 'Der Gast hat auf die Rückfrage und '.$request->reminders_sent.' Erinnerung(en) nicht geantwortet.'); + + continue; + } + + $count += $this->send($request, DataRequest::REMINDER) ? 1 : 0; + } + + return $count; + } + + /** + * Ends the request (all details there, the case ended, or the landlord stopped it). + */ + public function close(DataRequest $request, string $status, string $reason): void + { + if (! $request->isRunning()) { + return; + } + + $request->forceFill(['status' => $status, 'closed_at' => now(), 'closed_reason' => $reason, 'next_reminder_at' => null])->save(); + BookingTask::query()->where('booking_id', $request->booking_id)->where('kind', BookingTaskKind::GuestUnresponsive)->where('subject', 'r'.$request->id)->where('status', BookingTaskStatus::Open) + ->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'note' => trim($task->note.' · '.$reason)])->save()); + if ($request->booking !== null) { + CaseLog::record($request->booking, 'data_request', 'Rückfrage beendet: '.$reason, actor: CaseLog::actor() ?? CaseLog::SYSTEM); + } + } + + /** + * The guest's signed link to the form; it belongs to this request and its current version. + */ + public function url(DataRequest $request, ?Booking $booking = null): string + { + $booking ??= $request->booking; + $parameters = ['booking' => $booking, 'r' => $request->id, 'v' => $request->link_version]; + $until = CarbonImmutable::now()->addDays($booking->process()->guestLinkValidDays()); + + return $booking->website()?->temporarySignedRoute('guest-data.show', $until, $parameters) + ?? URL::temporarySignedRoute('guest-data.show', $until, $parameters); + } + + /** + * Whether a question may go out without the landlord's click: its texts are released, or mails only reach the test + * recipient anyway (as for the automatic offer). + */ + public static function mayGoOutAutomatically(): bool + { + return DocumentReleases::isReleased(DocumentKind::DataRequest) || ! Settings::isLive(); + } + + private function handOver(DataRequest $request, string $note): void + { + $request->forceFill(['status' => DataRequest::MANUAL, 'next_reminder_at' => null])->save(); + BookingTask::openOnce($request->booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => $note]); + CaseLog::record($request->booking, 'data_request', 'Rückfrage an Sie übergeben: '.$note, actor: CaseLog::SYSTEM); + } +} diff --git a/app/Actions/SubmitBookingWish.php b/app/Actions/SubmitBookingWish.php index 1fe65b0..194231c 100644 --- a/app/Actions/SubmitBookingWish.php +++ b/app/Actions/SubmitBookingWish.php @@ -146,6 +146,11 @@ public function handle(Booking $booking, int $version, ?string $ip = null): stri $this->notify($booking, $outcome); + // v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing. + if ($outcome === self::PENDING) { + rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); + } + return $outcome; } diff --git a/app/Actions/TakeOverExternalBooking.php b/app/Actions/TakeOverExternalBooking.php index ac248d2..eeb94c5 100644 --- a/app/Actions/TakeOverExternalBooking.php +++ b/app/Actions/TakeOverExternalBooking.php @@ -97,6 +97,8 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar }); app(CaseAutomation::class)->advance($booking); + // v0.11 (E-036): the booking stays binding; only missing administrative details of a reachable guest are asked for. + rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true); return $booking->refresh(); } diff --git a/app/Console/Commands/ProcessDataRequests.php b/app/Console/Commands/ProcessDataRequests.php new file mode 100644 index 0000000..aeaabe8 --- /dev/null +++ b/app/Console/Commands/ProcessDataRequests.php @@ -0,0 +1,26 @@ +each(function (Tenant $tenant) use ($requests): void { + $count = $requests->remindDue(); + + $this->info("{$tenant->name}: {$count} Erinnerung(en) gesendet."); + }); + + return self::SUCCESS; + } +} diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index 7e0e6a7..e4667e6 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -33,6 +33,7 @@ enum BookingTaskKind: string implements HasLabel case OpenClaim = 'open_claim'; case FactConflict = 'fact_conflict'; case ChangeRequest = 'change_request'; + case GuestUnresponsive = 'guest_unresponsive'; public function getLabel(): string { @@ -55,6 +56,7 @@ public function getLabel(): string self::OpenClaim => 'Offenen Betrag nach der Abreise klären', self::FactConflict => 'Abweichende Angabe des Gastes prüfen', self::ChangeRequest => 'Änderungswunsch des Gastes prüfen', + self::GuestUnresponsive => 'Fehlende Angaben selbst beim Gast nachfragen', }; } diff --git a/app/Enums/DocumentKind.php b/app/Enums/DocumentKind.php index 259539e..2834a97 100644 --- a/app/Enums/DocumentKind.php +++ b/app/Enums/DocumentKind.php @@ -20,6 +20,7 @@ enum DocumentKind: string implements HasLabel case ExternalRecord = 'external_record'; case StayConfirmation = 'stay_confirmation'; case Internal = 'internal'; + case DataRequest = 'data_request'; public function getLabel(): string { @@ -30,6 +31,7 @@ public function getLabel(): string self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)', self::StayConfirmation => 'Aufenthaltsbestätigung (privat)', self::Internal => 'Nur intern, kein Dokument an Gäste', + self::DataRequest => 'Rückfrage nach fehlenden Angaben', }; } @@ -45,6 +47,7 @@ public function description(): string self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.', self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.', self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.', + self::DataRequest => 'E-Mail an den Gast mit der Bitte um fehlende Angaben (Anschrift, Personenzahl …) und einem persönlichen Link zum Ergänzen, dazu Erinnerungen und gezielte Folgefragen. Sie nennt nur eine tatsächlich bestehende vorläufige Reservierung. Im Testbetrieb gehen die Texte auch ohne Freigabe hinaus (nur an die Testadresse).', }; } @@ -85,7 +88,7 @@ public function containsContract(): bool */ public function isAvailable(): bool { - return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true); + return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation, self::DataRequest], true); } /** @@ -117,6 +120,7 @@ public function fileName(): string self::ExternalRecord => 'Buchungsunterlagen', self::StayConfirmation => 'Aufenthaltsbestaetigung', self::Internal => 'Intern', + self::DataRequest => 'Rueckfrage', }; } } diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index 9814a3c..7e7f229 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -9,6 +9,7 @@ use App\Actions\EndInternalCase; use App\Actions\ProvideGuestContact; use App\Actions\RecordPortalAmounts; +use App\Actions\RequestCaseData; use App\Actions\SendBookingDocuments; use App\Actions\SendOffer; use App\Actions\SetBookingStatus; @@ -37,6 +38,7 @@ use App\Models\BookingTask; use App\Models\ContractAnnex; use App\Models\ContractTemplate; +use App\Models\DataRequest; use App\Models\Extra; use App\Models\User; use App\Pricing\PrivateStayPrice; @@ -44,6 +46,7 @@ use App\Process\CaseActivities; use App\Process\CaseAutomation; use App\Process\CaseLog; +use App\Process\CaseRequirements; use App\Support\Countries; use App\Support\Money; use Carbon\CarbonImmutable; @@ -129,6 +132,8 @@ protected function getHeaderActions(): array $this->closeStayAction(), $this->settleAction(), $this->requestContactAction(), + $this->approveDataRequestAction(), + $this->stopDataRequestAction(), AssignGuestAction::make(), $this->confirmAction(), $this->sendDocumentsAction(), @@ -343,6 +348,55 @@ private function openFactConflicts(): string return $notes === [] ? '' : ' Abweichende Angaben des Gastes – bitte den richtigen Wert eintragen: '.implode(' · ', $notes); } + /** + * v0.11 data request: send the prepared question (or ask now although the case is set to asking by hand). + */ + private function approveDataRequestAction(): Action + { + return Action::make('approveDataRequest') + ->label('Rückfrage an den Gast senden') + ->icon(Heroicon::OutlinedPaperAirplane) + ->visible(fn (): bool => in_array($this->record->openDataRequest()?->status, [DataRequest::DRAFT, DataRequest::MANUAL], true) && filled($this->record->guest?->email)) + ->modalHeading('Fehlende Angaben beim Gast anfragen') + ->modalDescription(function (): string { + $request = $this->record->openDataRequest(); + $state = $this->record->clarificationState(); + + return 'Der Gast erhält eine E-Mail mit einem persönlichen Link und wird gebeten um: '.implode(', ', CaseRequirements::labels((array) $request?->fields)).'. ' + .match ($state['state']) { + 'active' => 'Die Mail nennt die vorläufige Reservierung bis '.$state['until']->format('d.m.Y, H:i').' Uhr.', + 'expired' => 'Die Mail sagt, dass die vorläufige Reservierung abgelaufen ist.', + default => $this->record->isBinding() ? 'Die Mail sagt, dass die Buchung verbindlich bleibt.' : 'Die Mail sagt, dass der Zeitraum noch nicht reserviert ist.', + } + .(RequestCaseData::mayGoOutAutomatically() ? '' : ' Hinweis: Der Text der Rückfrage ist noch eine Arbeitsfassung (So arbeite ich › Dokumente); mit „Senden“ bestätigen Sie ihn für diesen Vorgang.'); + }) + ->modalSubmitActionLabel('Senden') + ->action(function (RequestCaseData $requests): void { + $request = $this->record->openDataRequest(); + $sent = $request !== null && $requests->approve($request); + $this->record->refresh(); + $sent + ? Notification::make()->title('Rückfrage gesendet')->success()->send() + : Notification::make()->title('Nicht gesendet')->body('Bitte die E-Mail-Adresse des Gastes prüfen – oder es fehlt inzwischen nichts mehr.')->danger()->send(); + }); + } + + private function stopDataRequestAction(): Action + { + return Action::make('stopDataRequest') + ->label('Rückfrage beenden') + ->icon(Heroicon::OutlinedNoSymbol) + ->color('gray') + ->visible(fn (): bool => $this->record->openDataRequest() !== null) + ->requiresConfirmation() + ->modalDescription('Es gehen keine Erinnerungen und Folgefragen mehr hinaus. Die fehlenden Angaben tragen Sie dann selbst ein.') + ->action(function (RequestCaseData $requests): void { + $requests->close($this->record->openDataRequest(), DataRequest::STOPPED, 'von Ihnen beendet'); + $this->record->refresh(); + Notification::make()->title('Rückfrage beendet')->success()->send(); + }); + } + private function requestContactAction(): Action { return Action::make('requestContact') diff --git a/app/Http/Controllers/GuestDataController.php b/app/Http/Controllers/GuestDataController.php new file mode 100644 index 0000000..dbdb2ba --- /dev/null +++ b/app/Http/Controllers/GuestDataController.php @@ -0,0 +1,150 @@ +loadMissing(['guest', 'property']); + [$dataRequest, $problem] = $this->current($request, $booking); + $fields = $problem === null ? $this->fields($dataRequest, $booking) : []; + + return view('guest-data', [ + 'booking' => $booking, + 'problem' => $problem, + 'fields' => $fields, + 'values' => $this->ownValues($booking, $fields), + 'clarification' => $booking->clarificationState(), + 'purpose' => $dataRequest?->purpose, + 'submitUrl' => $problem === null ? $this->signed($booking, 'guest-data.submit', now()->addHour(), $dataRequest) : null, + ]); + } + + public function submit(Request $request, Booking $booking, ContributeCaseFacts $facts): RedirectResponse + { + $booking->loadMissing('guest'); + [$dataRequest, $problem] = $this->current($request, $booking); + $back = $dataRequest !== null ? $this->signed($booking, 'guest-data.show', now()->addDays(2), $dataRequest) : url()->previous(); + if ($problem !== null) { + return redirect()->to($back)->with('guest-data.error', $problem); + } + + $fields = $this->fields($dataRequest, $booking); + $rules = []; + foreach ($fields as $field) { + $rules[$this->input($field)] = match ($field) { + 'guest.country' => ['nullable', 'in:'.implode(',', array_keys(Countries::options()))], + 'guest.email' => ['nullable', 'email', 'max:255'], + 'booking.guests' => ['nullable', 'integer', 'min:1', 'max:'.$booking->property->max_guests], + default => ['nullable', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'], + }; + } + $input = $request->validate($rules, [], collect($fields)->mapWithKeys(fn (string $field): array => [$this->input($field) => CaseRequirements::label($field)])->all()); + + $given = collect($fields)->mapWithKeys(fn (string $field): array => [$field => $input[$this->input($field)] ?? null])->filter(fn (mixed $value): bool => filled($value))->all(); + if ($given === []) { + return redirect()->to($back)->with('guest-data.error', 'Bitte füllen Sie mindestens eines der Felder aus.'); + } + + $result = $facts->handle($booking, $given, FactSource::GuestLink, [ + 'reference' => 'link:r'.$dataRequest->id.':v'.$dataRequest->link_version.':'.hash('sha256', json_encode($given)), + 'actor' => 'Gast über den Ergänzungslink', + ]); + + $booking->refresh(); + $stillMissing = RequestCaseData::needs($booking)['fields'] ?? []; + + return redirect()->to($back)->with('guest-data.success', match (true) { + $result->isEmpty() => 'Diese Angaben liegen uns bereits vor – vielen Dank.', + $result->needsReview() => 'Vielen Dank! Einige Angaben weichen von unseren Unterlagen ab; wir prüfen sie und melden uns bei Bedarf.', + $stillMissing !== [] => 'Vielen Dank! Es fehlen noch: '.implode(', ', CaseRequirements::labels($stillMissing)).'.', + default => 'Vielen Dank – Ihre Angaben sind vollständig. Wir melden uns in Kürze per E-Mail.', + }); + } + + /** + * The request this link belongs to and why the link cannot be used (or null). + * + * @return array{0: ?DataRequest, 1: ?string} + */ + private function current(Request $request, Booking $booking): array + { + $dataRequest = $booking->dataRequests()->whereKey((int) $request->query('r'))->first(); + if ($dataRequest === null) { + return [null, 'Dieser Link gehört nicht zu dieser Anfrage.']; + } + if ((int) $request->query('v') !== $dataRequest->link_version) { + return [$dataRequest, 'Dieser Link ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere Nachricht gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.']; + } + if (RequestCaseData::needs($booking) === null) { + return [$dataRequest, in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true) + ? 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.' + : 'Vielen Dank – uns liegen alle Angaben vor. Sie müssen nichts weiter tun.']; + } + + return [$dataRequest, null]; + } + + /** + * The details asked for now, plus the phone number as an optional extra. + * + * @return list + */ + private function fields(?DataRequest $dataRequest, Booking $booking): array + { + $needed = RequestCaseData::needs($booking)['fields'] ?? (array) $dataRequest?->fields; + + return array_values(array_unique([...$needed, ...(blank($booking->guest?->phone) ? ['guest.phone'] : [])])); + } + + /** + * Pre-filled values: only what this guest gave for this case himself (minimal insight, CH-18), and Germany as a + * changeable default of the country (B4). + * + * @param list $fields + * @return array + */ + private function ownValues(Booking $booking, array $fields): array + { + $own = CaseFact::query()->where('booking_id', $booking->id)->whereIn('field', $fields) + ->whereIn('source', [FactSource::GuestLink, FactSource::WebsiteForm])->whereIn('outcome', [CaseFact::APPLIED, CaseFact::CONFIRMED]) + ->orderBy('id')->get()->mapWithKeys(fn (CaseFact $fact): array => [$fact->field => (string) $fact->value])->all(); + + return in_array('guest.country', $fields, true) && ! isset($own['guest.country']) ? [...$own, 'guest.country' => Countries::DEFAULT] : $own; + } + + private function input(string $field): string + { + return str_replace('.', '_', $field); + } + + private function signed(Booking $booking, string $name, DateTimeInterface $expiration, DataRequest $dataRequest): string + { + $parameters = ['booking' => $booking, 'r' => $dataRequest->id, 'v' => $dataRequest->link_version]; + + return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters) + ?? URL::temporarySignedRoute($name, $expiration, $parameters); + } +} diff --git a/app/Listeners/ContinueDataRequest.php b/app/Listeners/ContinueDataRequest.php new file mode 100644 index 0000000..6d3629d --- /dev/null +++ b/app/Listeners/ContinueDataRequest.php @@ -0,0 +1,31 @@ +requests->answered($event->booking, $event->contribution, $event->source); + + // Now the guest can be written to: ask for what is still missing (e.g. a portal booking's address). + if (in_array('guest.email', $event->contribution->fields(CaseFact::APPLIED), true) && $event->booking->openDataRequest() === null) { + $this->requests->forNextStep($event->booking->refresh()); + } + } catch (Throwable $exception) { + report($exception); + } + } +} diff --git a/app/Mail/DataRequested.php b/app/Mail/DataRequested.php new file mode 100644 index 0000000..41f1da2 --- /dev/null +++ b/app/Mail/DataRequested.php @@ -0,0 +1,57 @@ + */ + public array $missing; + + public function __construct(public Booking $booking, public DataRequest $request, public string $kind, public string $url) + { + $this->clarification = $booking->clarificationState(); + $this->missing = CaseRequirements::labels($request->fields); + } + + public function envelope(): Envelope + { + $subject = $this->request->purpose === RequestCaseData::FOR_BOOKING ? 'Ihre Buchung '.$this->booking->reference : 'Ihre Anfrage '.$this->booking->reference; + + return new Envelope( + subject: match ($this->kind) { + DataRequest::REMINDER => 'Erinnerung – '.$subject.': Es fehlen noch Angaben', + DataRequest::FOLLOWUP => $subject.': Noch eine kurze Rückfrage', + default => $subject.': Bitte ergänzen Sie Ihre Angaben', + }, + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.data-requested'); + } +} diff --git a/app/Mail/ReservationReceived.php b/app/Mail/ReservationReceived.php index 2e1180c..7aa3f20 100644 --- a/app/Mail/ReservationReceived.php +++ b/app/Mail/ReservationReceived.php @@ -22,7 +22,11 @@ public function __construct(public Booking $booking) {} public function envelope(): Envelope { return new Envelope( - subject: 'Ihre Anfrage '.$this->booking->reference.($this->booking->isHoldActive() ? ' – Termin vorgemerkt, Angebot folgt' : ' – Eingang bestätigt, Angebot folgt'), + subject: 'Ihre Anfrage '.$this->booking->reference.match (true) { + $this->booking->isHoldActive() && $this->booking->hold_purpose === Booking::HOLD_CLARIFICATION => ' – Eingang bestätigt, vorläufig reserviert', + $this->booking->isHoldActive() => ' – Termin vorgemerkt, Angebot folgt', + default => ' – Eingang bestätigt, Angebot folgt', + }, replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], ); } diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 376a448..84b324a 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -519,6 +519,20 @@ public function canBeArchived(): bool || ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true)); } + /** @return HasMany */ + public function dataRequests(): HasMany + { + return $this->hasMany(DataRequest::class)->latest('id'); + } + + /** + * The request for missing details that still runs (at most one per case, CH-17). + */ + public function openDataRequest(): ?DataRequest + { + return $this->dataRequests()->whereIn('status', DataRequest::RUNNING)->first(); + } + public function isHoldActive(): bool { return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture(); diff --git a/app/Models/DataRequest.php b/app/Models/DataRequest.php new file mode 100644 index 0000000..bd15c18 --- /dev/null +++ b/app/Models/DataRequest.php @@ -0,0 +1,87 @@ + + */ + protected function casts(): array + { + return [ + 'mode' => DataRequestMode::class, + 'fields' => 'array', + 'last_sent_at' => 'immutable_datetime', + 'response_due_at' => 'immutable_datetime', + 'next_reminder_at' => 'immutable_datetime', + 'answered_at' => 'immutable_datetime', + 'closed_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } + + public function isRunning(): bool + { + return in_array($this->status, self::RUNNING, true); + } + + public function statusLabel(): string + { + return match ($this->status) { + self::DRAFT => 'Rückfrage vorbereitet – wartet auf Ihre Freigabe', + self::OPEN => 'beim Gast angefragt', + self::MANUAL => 'von Ihnen nachzufragen', + self::COMPLETED => 'alle Angaben da', + default => 'beendet', + }; + } +} diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index c7ddd5b..b5ba303 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -20,6 +20,7 @@ use App\Models\Booking; use App\Models\BookingTask; use App\Models\ChannelTask; +use App\Models\DataRequest; use App\Pricing\CaseMoney; use App\Support\Money; use Carbon\CarbonImmutable; @@ -68,7 +69,8 @@ public static function for(Booking $booking): array $action = $profile->preReservation() || $booking->offer_version > 0 ? CaseRequirements::OFFER : CaseRequirements::WISH_CONFIRMATION; $needsDetails = $inquiry && ! $binding && $booking->offer_version === 0 && ($action === CaseRequirements::OFFER || $booking->wish_at !== null); $missing = $hasEmail && $needsDetails ? CaseRequirements::missing($booking, $action) : []; - $asked = $booking->contact_requested_at !== null; + $request = $booking->openDataRequest(); + $asked = $booking->contact_requested_at !== null || $request?->status === DataRequest::OPEN; $state = match (true) { $hasEmail && $missing === [] => ActivityState::Done, $asked => ActivityState::Waiting, @@ -82,11 +84,13 @@ public static function for(Booking $booking): array }; $detail = match (true) { $state === ActivityState::Done => $booking->guestName(), - $missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($asked ? ' · beim Gast angefragt' : ''), + $missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($request !== null ? ' · '.$request->statusLabel() : ($asked ? ' · beim Gast angefragt' : '')), $booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'), default => 'fehlt noch', }; - $activities[] = new Activity('contact', $title, $later($state), $detail, $state === ActivityState::Done ? null : 'provideContact'); + // A prepared data request waits for the landlord's release: that is the next step, otherwise entering the details. + $draft = $needsDetails && $request?->status === DataRequest::DRAFT; + $activities[] = new Activity('contact', $title, $later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact')); } if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) { @@ -228,6 +232,12 @@ public static function for(Booking $booking): array $activities[] = $profile->guestMessages() === Responsibility::Portal ? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen') : new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise'); + // v0.11: a binding booking (also from a portal) stays binding; missing administrative details are asked for + // alongside, after the steps of the booking itself. + if ($binding && ($bookingRequest = $booking->openDataRequest()) !== null) { + $activities[] = new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $later($bookingRequest->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open), + implode(', ', CaseRequirements::labels($bookingRequest->fields)).' · '.$bookingRequest->statusLabel(), $bookingRequest->status === DataRequest::OPEN ? null : 'approveDataRequest'); + } $activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) { $left => ActivityState::Done, $arrived => ActivityState::Waiting, diff --git a/database/migrations/2026_11_06_110000_create_data_requests.php b/database/migrations/2026_11_06_110000_create_data_requests.php new file mode 100644 index 0000000..f39120c --- /dev/null +++ b/database/migrations/2026_11_06_110000_create_data_requests.php @@ -0,0 +1,53 @@ +id(); + $table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->string('status', 20); + $table->string('mode', 20); + $table->string('purpose', 30); + $table->json('fields'); + $table->unsignedTinyInteger('followups_sent')->default(0); + $table->unsignedTinyInteger('reminders_sent')->default(0); + $table->unsignedSmallInteger('link_version')->default(1); + $table->string('last_message', 20)->nullable(); + $table->dateTime('last_sent_at')->nullable(); + $table->dateTime('response_due_at')->nullable(); + $table->dateTime('next_reminder_at')->nullable(); + $table->dateTime('answered_at')->nullable(); + $table->dateTime('closed_at')->nullable(); + $table->string('closed_reason')->nullable(); + $table->timestamps(); + + $table->index(['booking_id', 'status']); + $table->index(['status', 'next_reminder_at']); + }); + + Schema::table('booking_messages', function (Blueprint $table) { + $table->string('message_id')->nullable()->after('subject')->index(); + }); + } + + public function down(): void + { + Schema::table('booking_messages', function (Blueprint $table) { + $table->dropColumn('message_id'); + }); + + Schema::dropIfExists('data_requests'); + } +}; diff --git a/resources/views/guest-data.blade.php b/resources/views/guest-data.blade.php new file mode 100644 index 0000000..c9617f4 --- /dev/null +++ b/resources/views/guest-data.blade.php @@ -0,0 +1,64 @@ +@php($owner = \App\Documents\OfferTerms::owner($booking)) +@extends('theme::layouts.app', ['title' => 'Angaben ergänzen']) + +@push('head') + +@endpush + +@section('content') +
+

{{ $purpose === \App\Actions\RequestCaseData::FOR_BOOKING ? 'Buchung' : 'Anfrage' }} {{ $booking->reference }}

+

Angaben ergänzen

+

{{ $booking->property->name }} · {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}

+ + @if (session('guest-data.success')) +
{{ session('guest-data.success') }}
+ @endif + @if (session('guest-data.error') || $problem) + + @endif + + @if ($fields !== [] && ! $problem) +
+ @if ($purpose === \App\Actions\RequestCaseData::FOR_BOOKING) +

Ihre Buchung ist verbindlich bestätigt; daran ändert dieses Formular nichts.

+ @elseif ($clarification['state'] === 'active') +

Der Zeitraum ist zur Klärung bis {{ $clarification['until']->format('d.m.Y, H:i') }} Uhr vorläufig reserviert. Das ist noch kein verbindliches Angebot.

+ @elseif ($clarification['state'] === 'expired') +

Die vorläufige Reservierung ist abgelaufen. Ihre Angaben können Sie trotzdem senden; wir prüfen die Verfügbarkeit dann erneut.

+ @else +

Der Zeitraum ist noch nicht für Sie reserviert. Sobald die Angaben vorliegen, prüfen wir die Verfügbarkeit erneut.

+ @endif +

Mit dem Absenden wird nichts gebucht und kein Vertrag geschlossen.

+
+ +
+ @csrf +
+ @foreach ($fields as $field) + @php($name = str_replace('.', '_', $field)) + + @endforeach +
+ +

Sie können auch einfach auf unsere E-Mail antworten.

+
+ @endif + +

Fragen? {{ $owner['name'] ?? '' }} · {{ $owner['phone'] ?? '' }} · {{ $owner['email'] ?? '' }}

+
+@endsection diff --git a/resources/views/mail/data-requested.blade.php b/resources/views/mail/data-requested.blade.php new file mode 100644 index 0000000..bd8bd9a --- /dev/null +++ b/resources/views/mail/data-requested.blade.php @@ -0,0 +1,44 @@ + +# {{ $kind === \App\Models\DataRequest::REMINDER ? 'Kurze Erinnerung' : ($kind === \App\Models\DataRequest::FOLLOWUP ? 'Noch eine kurze Rückfrage' : 'Es fehlen noch ein paar Angaben') }} + +Guten Tag {{ $booking->guest->full_name }}, + +@if ($request->purpose === \App\Actions\RequestCaseData::FOR_BOOKING) +Ihre Buchung der **{{ $booking->property->name }}** ist verbindlich bestätigt – daran ändert diese Nachricht nichts. Für die weitere Abwicklung benötigen wir noch: +@elseif ($request->purpose === \App\Actions\RequestCaseData::FOR_WISH) +vielen Dank für Ihren Buchungswunsch für die **{{ $booking->property->name }}**. Damit wir ihn verbindlich bestätigen können, benötigen wir noch: +@else +vielen Dank für Ihre Anfrage für die **{{ $booking->property->name }}**. Damit wir Ihnen ein verbindliches Angebot senden können, benötigen wir noch: +@endif + +@foreach ($missing as $label) +- {{ $label }} +@endforeach + + +Angaben ergänzen + + +Sie können auch einfach auf diese E-Mail antworten. + +**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}
+**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}
+**Anfragenummer:** {{ $booking->reference }} + +@if ($request->purpose !== \App\Actions\RequestCaseData::FOR_BOOKING) +@if ($clarification['state'] === 'active') +Den Zeitraum haben wir für Sie **zur Klärung bis {{ $clarification['until']->format('d.m.Y, H:i') }} Uhr vorläufig reserviert**. Das ist noch kein verbindliches Angebot; danach kann der Zeitraum anderweitig vergeben werden. +@elseif ($clarification['state'] === 'expired') +Die vorläufige Reservierung zur Klärung ist abgelaufen. Ihre Angaben können Sie trotzdem übermitteln; wir prüfen die Verfügbarkeit dann erneut. +@elseif ($request->purpose === \App\Actions\RequestCaseData::FOR_WISH) +Ihr Buchungswunsch ist noch nicht bestätigt, und der Zeitraum ist nicht für Sie reserviert. Sobald Ihre Angaben vorliegen, prüfen wir die Verfügbarkeit erneut. +@else +Der Zeitraum ist noch **nicht für Sie reserviert**. Sobald die fehlenden Angaben vorliegen, prüfen wir die Verfügbarkeit erneut. +@endif +@endif + +Bei Fragen antworten Sie einfach auf diese E-Mail oder rufen Sie uns an: {{ config('fewo.owner.phone') }} + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/mail/reservation-received.blade.php b/resources/views/mail/reservation-received.blade.php index 2b30e91..65cc929 100644 --- a/resources/views/mail/reservation-received.blade.php +++ b/resources/views/mail/reservation-received.blade.php @@ -3,7 +3,7 @@ Guten Tag {{ $booking->guest->full_name }}, -wir haben Ihre unverbindliche Anfrage für die **{{ $booking->property->name }}** erhalten.@if ($booking->isHoldActive()) Wir haben den Zeitraum in unserem Kalender für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**.@else Der Zeitraum ist damit noch **nicht reserviert**; er kann in der Zwischenzeit anderweitig vergeben werden.@endif +wir haben Ihre unverbindliche Anfrage für die **{{ $booking->property->name }}** erhalten.@if ($booking->isHoldActive() && $booking->hold_purpose === \App\Models\Booking::HOLD_CLARIFICATION) Den Zeitraum haben wir **zur Klärung bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorläufig reserviert**; für ein verbindliches Angebot fehlen uns noch Angaben, nach denen wir Sie gesondert fragen.@elseif ($booking->isHoldActive()) Wir haben den Zeitraum in unserem Kalender für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**.@else Der Zeitraum ist damit noch **nicht reserviert**; er kann in der Zwischenzeit anderweitig vergeben werden.@endif **Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}
**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}
diff --git a/routes/console.php b/routes/console.php index 04ff157..94c1128 100644 --- a/routes/console.php +++ b/routes/console.php @@ -18,6 +18,9 @@ Schedule::command('bookings:auto-offers')->everyFiveMinutes()->withoutOverlapping(); +// v0.11: reminders of data requests (never extends a hold or a deadline of the case). +Schedule::command('cases:data-requests')->everyFiveMinutes()->withoutOverlapping(); + Schedule::command('bookings:resend-confirmations')->everyFifteenMinutes()->withoutOverlapping(); Schedule::command('channels:sync')->everyFiveMinutes()->withoutOverlapping(10); diff --git a/routes/web.php b/routes/web.php index 9b012cd..a14a46c 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,6 +2,7 @@ use App\Http\Controllers\ChangeController; use App\Http\Controllers\ChannelController; +use App\Http\Controllers\GuestDataController; use App\Http\Controllers\InformationController; use App\Http\Controllers\MarketingConsentController; use App\Http\Controllers\OfferController; @@ -31,6 +32,9 @@ // Information "unter Vorbehalt" of a request without a hold and the guest's booking wish (package 7). Route::get('/angebot/auskunft/{booking}', [InformationController::class, 'show'])->name('information.show')->middleware('throttle:30,1'); Route::post('/angebot/auskunft/{booking}/buchung-anfragen', [InformationController::class, 'wish'])->name('information.wish')->middleware('throttle:10,1'); + // The guest completes missing details of a case (v0.11, CH-18); under /angebot/ so the requested host is kept. + Route::get('/angebot/angaben/{booking}', [GuestDataController::class, 'show'])->name('guest-data.show')->middleware('throttle:30,1'); + Route::post('/angebot/angaben/{booking}', [GuestDataController::class, 'submit'])->name('guest-data.submit')->middleware('throttle:10,1'); }); Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); diff --git a/tests/Feature/DataRequestTest.php b/tests/Feature/DataRequestTest.php new file mode 100644 index 0000000..ea8f570 --- /dev/null +++ b/tests/Feature/DataRequestTest.php @@ -0,0 +1,271 @@ +travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Mail::fake(); + Storage::fake('local'); + Http::fake(['*' => Http::response('', 500)]); + Content::save(['contract.terms' => '

Echte Bedingungen

', 'stay.cancellation' => '

Echtes Storno

']); + Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']); + } + + public function test_automatic_mode_asks_the_guest_at_once_instead_of_only_confirming_the_receipt(): void + { + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'data_request_mode' => 'automatic']]); + + $booking = $this->request(); + + $request = $booking->openDataRequest(); + $this->assertSame(DataRequest::OPEN, $request->status); + $this->assertSame(['guest.street', 'guest.postal_code', 'guest.city', 'guest.country'], $request->fields); + Mail::assertSent(DataRequested::class, fn (DataRequested $mail): bool => $mail->hasTo('gesa@example.org') && $mail->kind === DataRequest::INITIAL); + Mail::assertNotSent(ReservationReceived::class); + $this->assertTrue($booking->hold_expires_at->equalTo(now()->addMinutes(15)), 'the clarification hold is unchanged by the request'); + } + + public function test_approval_mode_prepares_the_question_and_the_landlord_releases_it(): void + { + $booking = $this->request(); + + $request = $booking->openDataRequest(); + $this->assertSame(DataRequest::DRAFT, $request->status); + Mail::assertNotSent(DataRequested::class); + Mail::assertSent(ReservationReceived::class); + $this->assertSame('approveDataRequest', CaseActivities::next($booking)?->action); + + $this->assertTrue(app(RequestCaseData::class)->approve($request)); + Mail::assertSent(DataRequested::class, 1); + $this->assertSame(DataRequest::OPEN, $request->fresh()->status); + } + + public function test_manual_mode_leaves_the_question_to_the_landlord(): void + { + Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'manual']]); + + $booking = $this->request(); + + $this->assertSame(DataRequest::MANUAL, $booking->openDataRequest()->status); + Mail::assertNotSent(DataRequested::class); + } + + public function test_without_an_email_address_nothing_is_sent_and_the_case_asks_for_the_contact(): void + { + $booking = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Paul', 'last_name' => 'Telefon', 'email' => ''], source: 'phone'); + + $this->assertNull($booking->openDataRequest()); + $this->assertSame('provideContact', CaseActivities::next($booking)?->action); + } + + /** M02 (form), M03 */ + public function test_the_guest_completes_the_details_through_the_link_partly_and_then_fully(): void + { + Settings::tenant()->update(['process_defaults' => ['processing' => 'automatic', 'data_request_mode' => 'automatic']]); + $booking = $this->request(); + $request = $booking->openDataRequest(); + $url = app(RequestCaseData::class)->url($request); + + $this->get($url)->assertOk()->assertSee('Straße und Hausnummer')->assertSee('zur Klärung bis'); + $this->assertSame(0, CaseFact::query()->where('source', FactSource::GuestLink)->count(), 'opening the link writes nothing'); + + $this->post($this->submitUrl($booking, $request), ['guest_street' => 'Strandweg 1', 'guest_postal_code' => '18225'])->assertRedirect(); + $request->refresh(); + $this->assertSame('Strandweg 1', $booking->guest->fresh()->street); + $this->assertSame(['guest.city', 'guest.country'], $request->fields); + $this->assertSame(1, $request->followups_sent, 'a partial answer gets a targeted follow-up question'); + $this->assertSame(2, $request->link_version); + Mail::assertSent(DataRequested::class, fn (DataRequested $mail): bool => $mail->kind === DataRequest::FOLLOWUP); + + $this->get($url)->assertSee('nicht mehr aktuell'); + + $fresh = app(RequestCaseData::class)->url($request); + $this->post($this->submitUrl($booking, $request), ['guest_city' => 'Kühlungsborn', 'guest_country' => 'DE'])->assertRedirect(); + $this->post($this->submitUrl($booking, $request), ['guest_city' => 'Kühlungsborn', 'guest_country' => 'DE']); + + $booking->refresh(); + $this->assertSame(DataRequest::COMPLETED, $request->fresh()->status); + $this->assertSame(BookingStatus::OfferSent, $booking->status, 'complete: the existing process sends the offer'); + $this->assertSame(1, $booking->offer_version, 'no second offer from the repeated submit'); + $this->get($fresh)->assertSee('alle Angaben vor'); + } + + public function test_a_differing_value_from_the_link_never_overwrites_the_guest_record(): void + { + $booking = $this->request(['street' => 'Alter Weg 2']); + $request = $booking->openDataRequest(); + app(RequestCaseData::class)->approve($request); + + $this->post($this->submitUrl($booking, $request->fresh()), ['guest_postal_code' => '18225', 'guest_city' => 'Kühlungsborn', 'guest_country' => 'DE', 'guest_street' => 'Neuer Weg 3']); + + $this->assertSame('Alter Weg 2', $booking->guest->fresh()->street); + } + + /** M08 */ + public function test_reminders_follow_their_limit_and_then_the_landlord_takes_over_without_extending_any_deadline(): void + { + Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'automatic']]); + $booking = $this->request(); + $holdBefore = $booking->hold_expires_at; + $requests = app(RequestCaseData::class); + + $this->travel(25)->hours(); + $this->assertSame(1, $requests->remindDue()); + $this->travel(25)->hours(); + $this->assertSame(1, $requests->remindDue()); + $this->travel(25)->hours(); + $this->assertSame(0, $requests->remindDue()); + + $request = $booking->openDataRequest(); + $this->assertSame([2, DataRequest::MANUAL], [$request->reminders_sent, $request->status]); + Mail::assertSent(DataRequested::class, fn (DataRequested $mail): bool => $mail->kind === DataRequest::REMINDER); + $this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::GuestUnresponsive)->count()); + $this->assertTrue($booking->fresh()->hold_expires_at->equalTo($holdBefore), 'no reminder extends the clarification hold'); + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + } + + public function test_an_answer_stops_the_reminder_and_the_follow_up_limit_hands_over(): void + { + Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'automatic', 'data_request_followups_max' => 0]]); + $booking = $this->request(); + + app(ContributeCaseFacts::class)->handle($booking, ['guest.street' => 'Strandweg 1'], FactSource::Email, ['reference' => 'mail-1']); + + $request = $booking->openDataRequest(); + $this->assertSame(DataRequest::MANUAL, $request->status); + $this->assertNull($request->next_reminder_at); + Mail::assertNotSent(DataRequested::class, fn (DataRequested $mail): bool => $mail->kind === DataRequest::FOLLOWUP); + } + + /** M09 */ + public function test_foreign_outdated_and_unsigned_links_change_nothing(): void + { + $booking = $this->request(); + $other = $this->request(email: 'andere@example.org', arrival: '2026-11-20', departure: '2026-11-23'); + $request = $booking->openDataRequest(); + + $this->get(route('guest-data.show', ['booking' => $booking, 'r' => $request->id, 'v' => 1]))->assertForbidden(); + $this->get(app(RequestCaseData::class)->url($other->openDataRequest(), $booking))->assertSee('gehört nicht zu dieser Anfrage'); + $this->post($this->submitUrl($booking, $other->openDataRequest()), ['guest_street' => 'Falsch 1'])->assertRedirect(); + $this->assertNull($booking->guest->fresh()->street); + + $this->travel(15)->days(); + $this->get(app(RequestCaseData::class)->url($request))->assertOk(); + $this->travelBack(); + $expired = app(RequestCaseData::class)->url($request); + $this->travel(15)->days(); + $this->get($expired)->assertForbidden(); + } + + public function test_a_mail_failure_is_visible_and_hands_over(): void + { + Settings::tenant()->update(['process_defaults' => ['data_request_mode' => 'automatic']]); + Mail::shouldReceive('to')->andThrow(new \RuntimeException('SMTP down')); + + $booking = app(CreateReservation::class)->handle($this->property->fresh(), new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => 'gesa@example.org']); + + $this->assertSame(DataRequest::MANUAL, $booking->openDataRequest()->status); + $this->assertSame(1, BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::GuestUnresponsive)->count()); + } + + /** M11: what the guest is told follows the real hold. */ + public function test_the_texts_follow_the_real_state_of_the_hold(): void + { + $active = $this->request(); + $this->assertStringContainsString('zur Klärung bis 22.10.2026, 13:00 Uhr vorläufig reserviert', $this->mailText($active)); + + $this->travel(4)->hours(); + $this->assertStringContainsString('vorläufige Reservierung zur Klärung ist abgelaufen', $this->mailText($active->fresh())); + $this->travelBack(); + + Settings::tenant()->update(['process_defaults' => ['clarification_hold_manual_minutes' => 0]]); + $none = $this->request(email: 'null@example.org', arrival: '2026-11-20', departure: '2026-11-23'); + $text = $this->mailText($none); + $this->assertStringContainsString('noch nicht für Sie reserviert', $text); + $this->assertStringNotContainsString('vorläufig reserviert', $text); + } + + /** M12 part: a binding portal booking is only asked for administrative details – no hold, no offer texts. */ + public function test_a_binding_portal_booking_is_asked_only_for_administrative_details(): void + { + $portal = Channel::factory()->for($this->property)->create(['name' => 'FeWo-direkt', 'booking_model' => 'portal_booking']); + + $booking = app(TakeOverExternalBooking::class)->handle($this->property, $portal, CarbonImmutable::parse('2026-12-05'), CarbonImmutable::parse('2026-12-08'), ['portal_reference' => 'HA-7', 'guest' => ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'erika@example.org']]); + + $request = $booking->openDataRequest(); + $this->assertSame(RequestCaseData::FOR_BOOKING, $request->purpose); + $this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status); + $text = $this->mailText($booking, $request); + $this->assertStringContainsString('verbindlich bestätigt', $text); + $this->assertStringNotContainsString('reserviert', $text); + $this->assertNotSame('approveDataRequest', CaseActivities::next($booking->fresh())?->action, 'the booking\'s own steps come first'); + } + + /** + * @param array $guest + */ + private function request(array $guest = [], string $email = 'gesa@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking + { + return app(CreateReservation::class)->handle( + $this->property->fresh(), + new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2), + ['first_name' => 'Gesa', 'last_name' => 'Gast', 'email' => $email, ...$guest], + )->fresh(); + } + + private function submitUrl(Booking $booking, DataRequest $request): string + { + return URL::temporarySignedRoute('guest-data.submit', now()->addHour(), ['booking' => $booking, 'r' => $request->id, 'v' => $request->fresh()->link_version]); + } + + private function mailText(Booking $booking, ?DataRequest $request = null): string + { + $request ??= $booking->openDataRequest(); + + return strip_tags((new DataRequested($booking->fresh(), $request, DataRequest::INITIAL, 'https://example.test/link'))->render()); + } +}