v0.11 U4: Rückfrage, Folgefrage, Erinnerung und Ergänzungslink

- data_requests: ein Beschaffungsvorgang je Vorgang mit Modus
  (automatisch / Freigabe / manuell), getrennten Zählern für Folgefragen
  und Erinnerungen ohne Rücksetzen, Antwortfrist ≠ Reservierungsfrist.
- RequestCaseData: fragt nach, was für das nächste Angebot, die
  Wunschbestätigung oder (bei verbindlichen Buchungen) administrativ fehlt;
  ohne E-Mail keine Rückfrage. Teilantwort → gezielte Folgefrage, Schweigen
  → Erinnerungen, an der Grenze Aufgabe für die Vermieterin. Nie ein Hold.
- Mail DataRequested mit Texten nach tatsächlichem Sperrstatus (M11);
  Dokumentart „Rückfrage“ – im Live-Betrieb ohne Freigabe nur nach Klick.
- Signierter, versionierter Ergänzungslink (/angebot/angaben): Lesen
  schreibt nicht, Absenden über den Fakteneingang, idempotent.
- Vorgang: „Rückfrage an den Gast senden“ / „Rückfrage beenden“;
  Eingangsbestätigung nennt die Klärungsreservierung korrekt.
- Zeitplan: cases:data-requests alle fünf Minuten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-11-03 13:25:48 +01:00
1 parent 37f48defcc
commit e4a3cb7f7b
22 files changed
+1224 -7

No files matched your search

+13 -1
View File
@@ -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));
+320
View File
@@ -0,0 +1,320 @@
<?php
namespace App\Actions;
use App\Documents\DocumentReleases;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\DataRequestMode;
use App\Enums\DocumentKind;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Mail\DataRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\DataRequest;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Process\FactContribution;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* The data request of v0.11 (S1, S4, CH-04, CH-15–CH-18): when the next step of a case lacks details, the guest is
* asked – automatically, prepared for the landlord's release, or by the landlord himself, as the case's settings say.
* At most one request runs per case. A partial answer leads to a targeted follow-up question, silence to reminders;
* both have their own limits and counters that are never reset. At the limit the landlord takes over.
*
* The request decides nothing about the case: answers go through the common fact intake, which asks the existing
* process to carry on. It never touches a hold or a deadline of the offer (CH-16/17, architecture test).
*/
class RequestCaseData
{
/** What the details are needed for. */
public const FOR_OFFER = 'offer';
public const FOR_WISH = 'wish_confirmation';
public const FOR_BOOKING = 'booking';
/**
* What the case needs next and which details are missing for it, or null when nothing is to be asked.
*
* @return array{purpose: string, fields: list<string>}|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);
}
}
+5
View File
@@ -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;
}
+2
View File
@@ -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();
}
@@ -0,0 +1,26 @@
<?php
namespace App\Console\Commands;
use App\Actions\RequestCaseData;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('cases:data-requests')]
#[Description('Send due reminders of data requests and hand silent ones over to the landlord – once per landlord (v0.11)')]
class ProcessDataRequests extends Command
{
public function handle(RequestCaseData $requests, TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant) use ($requests): void {
$count = $requests->remindDue();
$this->info("{$tenant->name}: {$count} Erinnerung(en) gesendet.");
});
return self::SUCCESS;
}
}
+2
View File
@@ -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',
};
}
+5 -1
View File
@@ -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',
};
}
}
@@ -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')
@@ -0,0 +1,150 @@
<?php
namespace App\Http\Controllers;
use App\Actions\ContributeCaseFacts;
use App\Actions\RequestCaseData;
use App\Enums\BookingStatus;
use App\Enums\FactSource;
use App\Models\Booking;
use App\Models\CaseFact;
use App\Models\DataRequest;
use App\Process\CaseRequirements;
use App\Support\Countries;
use DateTimeInterface;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\View\View;
/**
* The guest's page to complete missing details (v0.11, CH-18, signed link from the data request): no account, the link
* belongs to one case, one request and its current version. Opening it changes nothing; it shows only the details that
* are asked for and what the guest gave for this case himself. Sending goes through the common fact intake – the same
* form twice is harmless, a differing value never overwrites a stored one, and nothing binding happens here.
*/
class GuestDataController extends Controller
{
public function show(Request $request, Booking $booking): View
{
$booking->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<string>
*/
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<string> $fields
* @return array<string, string>
*/
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);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Listeners;
use App\Actions\RequestCaseData;
use App\Events\CaseFactsContributed;
use App\Models\CaseFact;
use Throwable;
/**
* After details arrived for a case, the running data request learns about it: reminders stop, a follow-up question is
* planned or the request ends (CH-17). A problem here never undoes the details that were taken over.
*/
class ContinueDataRequest
{
public function __construct(private RequestCaseData $requests) {}
public function handle(CaseFactsContributed $event): void
{
try {
$this->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);
}
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Mail;
use App\Actions\RequestCaseData;
use App\Models\Booking;
use App\Models\DataRequest;
use App\Process\CaseRequirements;
use Carbon\CarbonImmutable;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* The question for missing details (v0.11, S4): first question, targeted follow-up or reminder, with the guest's link.
* What it says about the dates follows the real state of the case at the moment of sending (CH §2a table): no hold,
* a clarification hold until its real end, an expired one, or a booking that is already binding – never the
* configured value. The guest may also simply answer the e-mail.
*/
class DataRequested extends Mailable
{
use Queueable, SerializesModels;
/** @var array{state: 'none'|'active'|'expired', until: ?CarbonImmutable} */
public array $clarification;
/** @var list<string> */
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');
}
}
+5 -1
View File
@@ -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'))],
);
}
+14
View File
@@ -519,6 +519,20 @@ public function canBeArchived(): bool
|| ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true));
}
/** @return HasMany<DataRequest, $this> */
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();
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Models;
use App\Enums\DataRequestMode;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One coherent request for missing details of a case (v0.11, CH-16/17): at most one is open per case. Follow-up
* questions and reminders have separate counters that a partial answer never resets; the answer deadline is not a
* reservation deadline.
*/
#[Fillable(['booking_id', 'status', 'mode', 'purpose', 'fields', 'followups_sent', 'reminders_sent', 'link_version', 'last_message', 'last_sent_at', 'response_due_at', 'next_reminder_at', 'answered_at', 'closed_at', 'closed_reason'])]
class DataRequest extends Model
{
use BelongsToTenant;
/** Prepared, waits for the landlord's release. */
public const DRAFT = 'draft';
/** Sent; the guest is asked and may be reminded. */
public const OPEN = 'open';
/** The landlord asks himself (no automatic message), or the limits were reached. */
public const MANUAL = 'manual';
/** Every requested detail is there. */
public const COMPLETED = 'completed';
/** Ended without the details (case closed, landlord stopped it). */
public const STOPPED = 'stopped';
/** Statuses of a request that still runs. */
public const RUNNING = [self::DRAFT, self::OPEN, self::MANUAL];
/** First question. */
public const INITIAL = 'initial';
/** Targeted follow-up question after a partial or unclear answer. */
public const FOLLOWUP = 'followup';
/** Reminder when no answer came. */
public const REMINDER = 'reminder';
/**
* @return array<string, string>
*/
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<Booking, $this>
*/
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',
};
}
}
+13 -3
View File
@@ -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,