Files
fewo-stommer/app/Actions/CreateReservation.php
T
LarsandClaude Opus 5.5 ccac78a6c9 v0.11 U2: Angebots-Gate, gemeinsamer Fakteneingang mit Herkunft
- CaseRequirements: Vor einem eigenen verbindlichen Angebot und vor der
  verbindlichen Bestätigung eines Buchungswunsches müssen Vor- und
  Nachname, E-Mail, vollständige Anschrift mit Land, Personenzahl und
  Zeitraum vorliegen – harter Blocker, auch von Hand (G2a, B3). Die
  Auskunft unter Vorbehalt bleibt ohne dieses Gate.
- ContributeCaseFacts (S5): jede Angabe mit Herkunft und Ergebnis in
  case_facts; fehlend → übernommen, gleich → bestätigt, abweichend vom
  Gast → Prüfaufgabe (Kartei bleibt), Vermieterin maßgeblich, Zeitraum und
  Personen → Änderungswunsch; idempotent; danach einmal CaseAutomation.
- ProvideGuestContact und Webformular nutzen den Fakteneingang.
- Land als ISO-Code mit „Deutschland“ als änderbarem Formularstandard;
  guests.country ohne stillen Standardwert (B4).
- Testdaten bestehender Tests um Anschriften ergänzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:07:18 +01:00

200 lines
9.0 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\Enums\BookingStatus;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Exceptions\ReservationException;
use App\Mail\NewReservation;
use App\Mail\ReservationReceived;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Turns a guest request into a case (intake "request") that holds the dates for the hold time of the process settings,
* and sends the quote to the guest and a notification to the landlord.
*/
class CreateReservation
{
public function __construct(
private PriceCalculator $calculator,
private AvailabilityChecker $availability,
) {}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = [], ?Channel $originChannel = null): Booking
{
$tenant = $property->tenant;
if ($tenant === null) {
throw new TenantContextMissing(Property::class);
}
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution, $originChannel),
);
}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution, ?Channel $originChannel): Booking
{
if ($originChannel !== null && $originChannel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution, $originChannel): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
throw ReservationException::notAvailable();
}
$quote = $this->calculator->calculate($property, $stay);
[$guest, $differences] = $this->guestFor($guestData);
$profile = $originChannel === null && $source === 'website'
? app(ProcessSettings::class)->forWebsite($property)
: app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
'intake' => IntakeKind::Inquiry,
'origin_channel_id' => $originChannel?->id,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
'guests' => $stay->guests,
'extras' => array_filter($stay->extras),
'promo_code' => $quote->promoCodeApplied ? $stay->promoCode : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
'message' => $message,
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
]);
});
if ($source === 'website') {
// Evidence of what the guest typed (v0.11, S5): completed fields are confirmed, differing ones go to the
// landlord as a conflict instead of only a note. The guest record itself was already handled above.
$facts = collect(Arr::only($guestData, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']))
->filter(fn (?string $value): bool => filled($value))
->mapWithKeys(fn (string $value, string $field): array => ['guest.'.$field => $value])->all();
app(ContributeCaseFacts::class)->handle($booking, $facts, FactSource::WebsiteForm, ['advance' => false, 'reference' => 'request']);
$booking->refresh();
}
if ($sendMails) {
$this->sendMails($booking);
}
return $booking;
}
/**
* The guest record for the request. A known e-mail address never overwrites existing master data
* (anybody can type somebody else's address); empty fields are completed, differing values are
* returned so the landlord sees them with the request and can take them over in the offer.
*
* @param array<string, ?string> $guestData
* @return array{0: Guest, 1: list<string>}
*/
private function guestFor(array $guestData): array
{
$email = mb_strtolower(trim((string) ($guestData['email'] ?? '')));
$guest = $email === '' ? null : Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([
...$guestData,
'email' => $email,
'tenant_id' => app(TenantContext::class)->id(),
]), []];
}
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
$differences = [];
foreach ($labels as $field => $label) {
$value = trim((string) ($guestData[$field] ?? ''));
if ($value === '') {
continue;
}
if (blank($guest->{$field})) {
$guest->{$field} = $value;
} elseif (mb_strtolower((string) $guest->{$field}) !== mb_strtolower($value)) {
$differences[] = "{$label}: {$value} (Kartei: {$guest->{$field}})";
}
}
$guest->save();
return [$guest, $differences];
}
/**
* Automatic mode first tries to send the offer; the guest then gets the offer instead of the receipt, the
* landlord a note either way (with the reasons when the automatic offer was not possible). A failing mail
* server or any other error must not lose the reservation; failures are logged without personal data.
*/
private function sendMails(Booking $booking): void
{
$blockers = [];
$offerSent = false;
try {
$auto = app(AutoOffer::class);
if ($auto->applies($booking)) {
$blockers = $auto->handle($booking);
$offerSent = $blockers === [];
if (! $offerSent) {
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
}
$booking->refresh();
}
} catch (Throwable $exception) {
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
$offerSent = false;
}
try {
if (! $offerSent && 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));
} catch (Throwable $exception) {
Log::warning('Eingangsmail nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
}