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 = ''; 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 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)->resolve($this->property, null, IntakeKind::Inquiry)->preReservation(); } /** * @return Collection */ #[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>}> */ #[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, ], $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> */ /** * 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' => ['nullable', 'string', 'max:255'], 'postalCode' => ['nullable', 'string', 'max:20'], 'city' => ['nullable', 'string', 'max:255'], '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 */ protected function validationAttributes(): array { return [ 'arrival' => 'Anreise', 'departure' => 'Abreise', 'guests' => 'Personen', 'firstName' => 'Vorname', 'lastName' => 'Nachname', 'email' => 'E-Mail', '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 */ 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 $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; } }