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); $draft = new Booking(['property_id' => $property->id, 'arrival' => $stay->arrival->toDateString(), 'departure' => $stay->departure->toDateString(), 'guests' => $stay->guests]); $draft->setRelation('guest', $guest); $hold = RequestHold::for($draft, $profile); return $property->bookings()->create([ ...$hold, '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(), '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 $guestData * @return array{0: Guest, 1: list} */ 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]); } } }