Files
fewo-stommer/app/Actions/RequestCaseData.php
LarsandClaude Sonnet 5.5 221ce8ca81 Anfrage-Basisprozess inquiry.request mit Schablonen für Antwort und Gastkommunikation
Antwortart (Auskunft/Angebot) und Reservierung sind entkoppelt (neue Einstellung inquiry_answer;
pre_reservation bleibt die Reservierungsstrategie). Anlass-bezogene Absender für Anreise-Information
und Bewertungsbitte; Schablonen liefern Standardwerte unterhalb aller einstellbaren Ebenen.
A1/A2 bleiben Voreinstellungen und Altfassungen.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 12:40:22 +01:00

345 lines
15 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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\InquiryAnswer;
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()->inquiryAnswer() === InquiryAnswer::Offer => 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 && $request->next_reminder_at === null && $request->followups_sent < $booking->process()->followupsMax()) {
// The landlord took over the guest's e-mail answer and something is still missing: a follow-up question is
// prepared for his release.
$request->forceFill(['status' => DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP, 'fields' => $needs['fields']])->save();
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);
}
/**
* A reply of the guest arrived (assigned by the inbox): the open reminder is cancelled (CH-17). What it says is
* taken over only through the extraction and the fact intake.
*/
public function replyReceived(Booking $booking): void
{
$request = $booking->openDataRequest();
if ($request?->status !== DataRequest::OPEN) {
return;
}
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null])->save();
CaseLog::record($booking, 'data_request', 'Antwort des Gastes per E-Mail – Erinnerungen ruhen', 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);
}
}