Files
fewo-stommer/app/Livewire/BookingRequest.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

449 lines
15 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\Livewire;
use App\Actions\CreateReservation;
use App\Actions\RequestMarketingConsent;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\ReferralSource;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Extra;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Support\Countries;
use App\Tenancy\TenantContext;
use Carbon\CarbonImmutable;
use Illuminate\Contracts\View\View;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Validation\Rule;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Public availability calendar, live price and booking request form.
*/
class BookingRequest extends Component
{
private const MONTHS_SHOWN = 2;
#[Locked]
public int $propertyId;
/** First shown month as 'Y-m'. */
public string $month;
public ?string $arrival = null;
public ?string $departure = null;
public int $guests = 2;
/** @var array<int|string, int|string|null> quantity per extra id */
public array $extras = [];
public string $promoCode = '';
public string $firstName = '';
public string $lastName = '';
public string $email = '';
public string $phone = '';
public string $street = '';
public string $postalCode = '';
public string $city = '';
/** Pre-filled but changeable; it only counts because the guest sends it with the form (B4). */
public string $country = Countries::DEFAULT;
public string $message = '';
public bool $privacyAccepted = false;
/** Optional opt-in for offer e-mails (confirmed by double opt-in). */
public bool $marketingOptIn = false;
public string $referralSource = '';
/** @var array{utm_source?: string, utm_medium?: string, utm_campaign?: string} UTM parameters of the landing URL */
#[Locked]
public array $utm = [];
/** Honeypot, must stay empty. */
public string $website = '';
/** When the form was opened (time trap against bots); cannot be changed by the browser. */
#[Locked]
public int $openedAt = 0;
#[Locked]
public ?int $bookingId = null;
public function mount(?Property $property = null): void
{
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
$this->openedAt = now()->getTimestamp();
$this->month = CarbonImmutable::today()->format('Y-m');
$this->prefillFromSearch();
$this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign']))
->filter(fn ($value): bool => is_string($value) && $value !== '')
->map(fn (string $value): string => mb_substr($value, 0, 100))
->all();
}
#[Computed]
public function property(): Property
{
return Property::findOrFail($this->propertyId);
}
/**
* Whether the full address must be given in the form (channel manager, website entry; default: no – missing
* details are asked for afterwards, v0.11 B2).
*/
#[Computed]
public function requiresAddress(): bool
{
return app(ProcessSettings::class)->forWebsite($this->property)->formRequiresAddress();
}
/**
* Whether a request on the website reserves the dates (else it is answered with an information, package 7).
*/
#[Computed]
public function reservesDates(): bool
{
return app(ProcessSettings::class)->forWebsite($this->property)->preReservation();
}
/**
* @return Collection<int, Extra>
*/
#[Computed]
public function availableExtras(): Collection
{
return $this->property->extras()->active()->get();
}
public function previousMonth(): void
{
$previous = $this->firstMonth()->subMonth();
if ($previous->greaterThanOrEqualTo(CarbonImmutable::today()->startOfMonth())) {
$this->month = $previous->format('Y-m');
}
}
public function nextMonth(): void
{
$this->month = $this->firstMonth()->addMonth()->format('Y-m');
}
/**
* Calendar click: the first click sets the arrival, the second the departure.
*/
public function selectDate(string $date): void
{
$day = CarbonImmutable::parse($date);
$occupied = $this->occupiedNights();
if ($this->arrival !== null && $this->departure === null && $day->greaterThan(CarbonImmutable::parse($this->arrival))) {
if ($this->allNightsFree(CarbonImmutable::parse($this->arrival), $day, $occupied)) {
$this->departure = $day->toDateString();
return;
}
}
if ($day->isBefore(CarbonImmutable::today()) || isset($occupied[$day->toDateString()])) {
return;
}
$this->arrival = $day->toDateString();
$this->departure = null;
}
public function clearDates(): void
{
$this->arrival = null;
$this->departure = null;
}
/**
* @return array{quote: ?PriceQuote, error: ?string}
*/
#[Computed]
public function pricing(): array
{
if ($this->arrival === null || $this->departure === null) {
return ['quote' => null, 'error' => null];
}
$stay = $this->stayRequest();
if ($stay->arrival->isBefore(CarbonImmutable::today())) {
return ['quote' => null, 'error' => 'Die Anreise darf nicht in der Vergangenheit liegen.'];
}
if ($stay->departure->greaterThan($stay->arrival) && ! app(AvailabilityChecker::class)->isAvailable($this->property, $stay->arrival, $stay->departure)) {
return ['quote' => null, 'error' => 'Der Zeitraum ist leider bereits belegt.'];
}
try {
return ['quote' => app(PriceCalculator::class)->calculate($this->property, $stay), 'error' => null];
} catch (QuoteException $exception) {
return ['quote' => null, 'error' => $exception->getMessage()];
}
}
/**
* Weeks of the shown months; every day knows whether its night is still free.
*
* @return list<array{label: string, weeks: list<list<?array{date: string, day: int, free: bool, past: bool, selected: bool, inRange: bool}>>}>
*/
#[Computed]
public function calendar(): array
{
$occupied = $this->occupiedNights();
$today = CarbonImmutable::today();
$arrival = $this->arrival ? CarbonImmutable::parse($this->arrival) : null;
$departure = $this->departure ? CarbonImmutable::parse($this->departure) : null;
$months = [];
for ($index = 0; $index < self::MONTHS_SHOWN; $index++) {
$first = $this->firstMonth()->addMonths($index);
$days = array_fill(0, $first->isoWeekday() - 1, null);
for ($day = $first; $day->month === $first->month; $day = $day->addDay()) {
$days[] = [
'date' => $day->toDateString(),
'day' => $day->day,
'free' => ! isset($occupied[$day->toDateString()]),
'past' => $day->isBefore($today),
'selected' => in_array($day->toDateString(), [$this->arrival, $this->departure], true),
'inRange' => $arrival && $departure && $day->greaterThan($arrival) && $day->lessThan($departure),
];
}
$months[] = ['label' => $first->translatedFormat('F Y'), 'weeks' => array_chunk($days, 7)];
}
return $months;
}
public function submit(CreateReservation $createReservation): void
{
$this->validate();
// Bots: honeypot filled or submitted faster than a human can fill the form – silently ignored.
if ($this->website !== '' || now()->getTimestamp() - $this->openedAt < config('fewo.spam.min_seconds')) {
return;
}
if ($this->tooManyRequests()) {
$this->addError('email', 'Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an.');
return;
}
if ($this->openRequestsOfEmail() >= config('fewo.spam.open_requests_per_email')) {
$this->addError('email', 'Zu dieser E-Mail-Adresse liegen bereits offene Anfragen vor. Wir melden uns in Kürze – bei Fragen rufen Sie uns gern an.');
return;
}
try {
$booking = $createReservation->handle(
$this->property,
$this->stayRequest(),
[
'first_name' => $this->firstName,
'last_name' => $this->lastName,
'email' => $this->email,
'phone' => $this->phone ?: null,
'street' => $this->street ?: null,
'postal_code' => $this->postalCode ?: null,
'city' => $this->city ?: null,
'country' => $this->country ?: null,
],
$this->message ?: null,
attribution: [...$this->utm, 'referral_source' => $this->referralSource ?: null],
);
} catch (QuoteException|ReservationException $exception) {
$this->addError('arrival', $exception->getMessage());
unset($this->calendar, $this->pricing);
return;
}
if ($this->marketingOptIn) {
rescue(fn () => app(RequestMarketingConsent::class)->handle($booking->guest));
}
$this->bookingId = $booking->id;
}
/**
* @return array<string, list<string>>
*/
/**
* Rate limits per IP address, per e-mail address and for all requests together (counted when they pass).
*/
private function tooManyRequests(): bool
{
$tenantKey = (string) (app(TenantContext::class)->id() ?? 'global');
$limits = [
'booking-request:'.$tenantKey.':'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
'booking-request-email:'.$tenantKey.':'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
'booking-request-all' => [config('fewo.spam.total_per_hour'), 3600],
];
foreach ($limits as $key => [$max]) {
if (RateLimiter::tooManyAttempts($key, $max)) {
return true;
}
}
foreach ($limits as $key => [, $decay]) {
RateLimiter::hit($key, $decay);
}
return false;
}
private function openRequestsOfEmail(): int
{
return Booking::query()
->whereIn('status', BookingStatus::holding())
->where('hold_expires_at', '>', now())
->whereHas('guest', fn ($query) => $query->where('email', mb_strtolower($this->email)))
->count();
}
protected function rules(): array
{
return [
'arrival' => ['required', 'date', 'after_or_equal:today'],
'departure' => ['required', 'date', 'after:arrival'],
'guests' => ['required', 'integer', 'min:1', 'max:'.$this->property->max_guests],
'extras.*' => ['nullable', 'integer', 'min:0', 'max:10'],
'promoCode' => ['nullable', 'string', 'max:50'],
'firstName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'],
'lastName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'],
'email' => ['required', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:50'],
'street' => [$this->requiresAddress() ? 'required' : 'nullable', 'string', 'max:255'],
'postalCode' => [$this->requiresAddress() ? 'required' : 'nullable', 'string', 'max:20'],
'city' => [$this->requiresAddress() ? 'required' : 'nullable', 'string', 'max:255'],
'country' => [$this->requiresAddress() ? 'required' : 'nullable', Rule::in(array_keys(Countries::options()))],
'message' => ['nullable', 'string', 'max:5000', function (string $attribute, mixed $value, \Closure $fail): void {
if (preg_match_all('~https?://|www\.~i', (string) $value) > config('fewo.spam.max_links')) {
$fail('Bitte schreiben Sie Ihre Nachricht ohne Links.');
}
}],
'referralSource' => ['nullable', Rule::enum(ReferralSource::class)],
'privacyAccepted' => ['accepted'],
];
}
/**
* @return array<string, string>
*/
protected function validationAttributes(): array
{
return [
'arrival' => 'Anreise',
'departure' => 'Abreise',
'guests' => 'Personen',
'firstName' => 'Vorname',
'lastName' => 'Nachname',
'email' => 'E-Mail',
'street' => 'Straße & Hausnr.',
'postalCode' => 'PLZ',
'city' => 'Ort',
'country' => 'Land',
'privacyAccepted' => 'Datenschutzerklärung',
];
}
public function render(): View
{
return view('livewire.booking-request', [
'booking' => $this->bookingId ? Booking::with('guest')->find($this->bookingId) : null,
]);
}
private function stayRequest(): StayRequest
{
return new StayRequest(
CarbonImmutable::parse($this->arrival),
CarbonImmutable::parse($this->departure),
$this->guests,
array_map('intval', array_filter($this->extras, fn ($quantity): bool => (int) $quantity > 0)),
$this->promoCode !== '' ? trim($this->promoCode) : null,
);
}
/**
* Dates and guests from the availability search of the hero section (?anreise=…&abreise=…&personen=…).
*/
private function prefillFromSearch(): void
{
$arrival = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('anreise')) ?: null, null, false);
$departure = rescue(fn () => CarbonImmutable::createFromFormat('!Y-m-d', (string) request()->query('abreise')) ?: null, null, false);
if ($arrival && $departure && $departure->greaterThan($arrival) && $arrival->greaterThanOrEqualTo(CarbonImmutable::today())) {
$this->arrival = $arrival->toDateString();
$this->departure = $departure->toDateString();
$this->month = $arrival->format('Y-m');
}
$guests = (int) request()->query('personen');
if ($guests >= 1 && $guests <= $this->property->max_guests) {
$this->guests = $guests;
}
}
private function firstMonth(): CarbonImmutable
{
return CarbonImmutable::createFromFormat('!Y-m', $this->month);
}
/**
* Occupied nights from the first shown month until a year ahead, so departures can be checked beyond the view.
*
* @return array<string, true>
*/
private function occupiedNights(): array
{
$from = $this->firstMonth()->min(CarbonImmutable::parse($this->arrival ?? $this->month.'-01'));
return app(AvailabilityChecker::class)->occupiedNights($this->property, $from, $from->addYear());
}
/**
* @param array<string, true> $occupied
*/
private function allNightsFree(CarbonImmutable $from, CarbonImmutable $until, array $occupied): bool
{
for ($night = $from; $night->lessThan($until); $night = $night->addDay()) {
if (isset($occupied[$night->toDateString()])) {
return false;
}
}
return true;
}
}