Files
fewo-stommer/app/Actions/SubmitBookingWish.php
T
LarsandClaude Opus 5.5 7e22e12cac U-A/U-B: Prozesskern mit Fachmodulen, versionierten Modellen, eingefrorenem Prozessplan, ProcessRunner (harte/weiche Abhängigkeiten), CasePricing, Loyalty nur im Tester
CaseActivities/CaseAutomation sind Fassaden über ProcessRunner. Verhaltensvergleich v0.11:
11 Abläufe und 198 Konstellationen gleich, beabsichtigte Abweichungen I-004/I-005 (F-001/F-002).
Volle Suite vor U-B: 785/785.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 14:49:44 +01:00

262 lines
12 KiB
PHP
Raw 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\Availability\AvailabilityChecker;
use App\Availability\CalendarClearance;
use App\Documents\DocumentComposer;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\BookingWishAnswered;
use App\Mail\BookingWishNotice;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Process\ProcessRunner;
use App\Support\Inbox;
use App\Support\Money;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Package 7 (E-026, E-030): the guest asks for the booking from an information "unter Vorbehalt". Everything is checked
* again in one locked step – the whole stay still free, the imported portal calendars current, the price the guest was
* told still the price of today, the data for the booking complete. Then the effective processing decides:
* automatically the booking is confirmed at once (only when nothing at all stands in the way), otherwise the landlord
* gets the task "Buchungswunsch bestätigen?". When the dates were given away meanwhile, no booking comes about; the
* guest gets a friendly answer and the landlord a note.
*
* Asking again for the same information is harmless (no second booking, no second mail); a link of an older information
* no longer works.
*/
class SubmitBookingWish
{
public const CONFIRMED = 'confirmed';
public const PENDING = 'pending';
public const UNAVAILABLE = 'unavailable';
public const ALREADY = 'already';
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private CalendarClearance $clearance,
private ConfirmBooking $confirm,
private Inbox $inbox,
) {}
/**
* @return string one of the outcome constants
*
* @throws ReservationException when the link is outdated, expired or the request is no longer open
*/
public function handle(Booking $booking, int $version, ?string $ip = null): string
{
$booking->loadMissing(['guest', 'property']);
if ($this->alreadyAsked($booking, $version)) {
return self::ALREADY;
}
$this->ensureCurrent($booking, $version);
// Network access (calendar imports) stays outside the transaction.
rescue(fn () => $this->clearance->refresh($booking->property), report: false);
$stale = $this->clearance->staleImports($booking->property)->pluck('name')->all();
$outcome = DB::transaction(function () use ($booking, $version, $ip, $stale): string {
$booking->lockForTransition();
if ($this->alreadyAsked($booking, $version)) {
return self::ALREADY;
}
$this->ensureCurrent($booking, $version);
$record = [
'information_version' => $version,
'at' => now()->toIso8601String(),
'ip_hash' => $ip !== null ? hash('sha256', $ip.config('app.key')) : null,
'total_told' => $booking->information['total'] ?? $booking->total,
'terms_sha256' => $booking->information['terms_sha256'] ?? null,
'via' => 'information_link',
];
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
$booking->update([
'wish_at' => now(),
'wish' => [...$record, 'outcome' => self::UNAVAILABLE, 'findings' => ['Der Zeitraum ist inzwischen vergeben.']],
'status' => BookingStatus::Declined,
'declined_by' => 'us',
]);
return self::UNAVAILABLE;
}
$findings = $this->findings($booking, $stale);
$automatic = $booking->processingMode() === ProcessingMode::Automatic;
$booking->update([
'wish_at' => now(),
'wish' => [...$record, 'total_now' => $findings['total_now'], 'findings' => $findings['findings'], 'outcome' => $automatic && $findings['findings'] === [] ? self::CONFIRMED : self::PENDING],
]);
if ($automatic && $findings['findings'] === []) {
$this->confirm->bind($booking);
$booking->update([
'accepted_at' => now(),
'acceptance' => [
'via' => 'booking_wish',
'information_version' => $version,
'wish_at' => $booking->wish_at?->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => SendInformation::quoteHash($booking),
'terms_sha256' => $record['terms_sha256'],
'confirmed_by' => 'automatisch nach erneuter Prüfung',
],
]);
return self::CONFIRMED;
}
BookingTask::openOnce($booking, BookingTaskKind::BookingWish, 'v'.$version, [
'due_on' => today(),
'note' => $findings['findings'] === [] ? 'Zeitraum frei, Preis unverändert.' : implode(' ', $findings['findings']),
]);
return self::PENDING;
});
$booking->refresh();
CaseLog::record($booking, 'wish', match ($outcome) {
self::CONFIRMED => 'Buchungswunsch des Gastes – automatisch geprüft und verbindlich bestätigt',
self::PENDING => 'Buchungswunsch des Gastes eingegangen – wartet auf Ihre Bestätigung',
self::UNAVAILABLE => 'Buchungswunsch des Gastes – Zeitraum inzwischen vergeben, keine Buchung',
default => 'Buchungswunsch wiederholt (ohne Wirkung)',
}, data: $outcome === self::ALREADY ? [] : ['wish' => $booking->wish], actor: CaseLog::GUEST);
$this->notify($booking, $outcome);
// v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing.
if ($outcome === self::PENDING) {
app(ProcessRunner::class)->advance($booking->fresh(), 'wish');
}
return $outcome;
}
/**
* Checks that the page shows the form for: the information is the current one, still valid and the request open.
*
* @throws ReservationException
*/
public function ensureCurrent(Booking $booking, int $version): void
{
if ($booking->information_version === 0 || $version !== $booking->information_version) {
throw new ReservationException('Diese Auskunft ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.');
}
if ($booking->wish_at !== null) {
throw new ReservationException('Zu dieser Auskunft liegt Ihr Buchungswunsch bereits vor.');
}
if ($booking->status !== BookingStatus::Reserved) {
throw new ReservationException(in_array($booking->status, BookingStatus::occupying(), true)
? 'Ihre Buchung ist bereits verbindlich bestätigt – Sie müssen nichts weiter tun.'
: 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.');
}
if (! $booking->information_valid_until?->isFuture()) {
throw new ReservationException('Diese Auskunft ist abgelaufen. Gern können Sie über unsere Webseite neu anfragen; wir prüfen dann Preis und Verfügbarkeit erneut.');
}
}
/**
* Everything that keeps the wish from being confirmed automatically, and the price of today.
*
* @param list<string> $stale names of portals whose calendar is not current
* @return array{findings: list<string>, total_now: ?int}
*/
public function findings(Booking $booking, array $stale = []): array
{
$findings = [];
$totalNow = null;
try {
$label = (string) ($booking->price_adjustment_label ?: 'Zuschlag');
$quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, $label);
$totalNow = $quote->total();
$told = (int) ($booking->information['total'] ?? $booking->total);
if ($totalNow !== $told) {
$findings[] = 'Der Preis hat sich seit der Auskunft geändert: damals '.Money::format($told).', heute '.Money::format($totalNow).'.';
}
} catch (QuoteException $exception) {
$findings[] = 'Der Preis lässt sich heute nicht berechnen: '.$exception->getMessage();
}
if ($stale !== []) {
$findings[] = 'Der Kalenderstand von '.implode(', ', $stale).' ist nicht aktuell.';
}
$findings = [...$findings, ...app(CaseAutomation::class)->documentBlockers($booking)];
if (($missing = CaseRequirements::blocker($booking, CaseRequirements::WISH_CONFIRMATION)) !== null) {
$findings[] = $missing;
}
if (! app(AutoOffer::class)->contractTextsReleased()) {
$findings[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
}
// What the confirmation with the contract would need to be confirmed by the landlord (unreleased texts, gaps).
foreach (app(DocumentComposer::class)->compose($booking, DocumentKind::Confirmation)->toConfirm() as $point) {
$findings[] = $point;
}
return ['findings' => array_values(array_unique($findings)), 'total_now' => $totalNow];
}
private function alreadyAsked(Booking $booking, int $version): bool
{
return $booking->wish_at !== null && ($booking->wish['information_version'] ?? null) === $version;
}
/**
* Mails after the commit; none of them can undo what was decided.
*/
private function notify(Booking $booking, string $outcome): void
{
if ($outcome === self::ALREADY) {
return;
}
if ($outcome === self::CONFIRMED) {
$this->confirm->deliver($booking);
}
try {
if ($outcome !== self::CONFIRMED && filled($booking->guest?->email)) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingWishAnswered($booking, $outcome));
}
Mail::to(Settings::notificationRecipients())->send(new BookingWishNotice($booking, $outcome));
} catch (Throwable $exception) {
Log::warning('Mail zum Buchungswunsch nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
if ($outcome === self::UNAVAILABLE) {
$this->inbox->post(
InboxMessageKind::OfferRejected,
'wish-'.$booking->id.':i'.$booking->information_version,
'Buchungswunsch '.$booking->reference.': Zeitraum inzwischen vergeben',
'Der Gast hat aus der Auskunft die Buchung angefragt, aber der Zeitraum ist inzwischen belegt. Es ist keine Buchung entstanden; der Gast hat eine freundliche Absage erhalten.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
}
}
}