Files
fewo-stommer/app/Livewire/BookingRequest.php
T
Lars StommerandClaude Opus 5.5 0b7205e050 Portal-Synchronisation: unser System führt
- Connector-System (app/Channels, config/channels.php) mit iCal-Connector, robustem Parser und Export-Feed je Portal (ohne eigene Belegungen, ohne Gästedaten)
- Abgleich alle 5 Min. mit Protokoll, Echo-Erkennung, Konflikt-Mail bei möglicher Doppelbuchung
- Überwachung: Störungs-Mail, Status-Endpunkt /health/sync für n8n
- Portal-Aufgaben für Sofortbuchungsportale (FeWo-direkt): automatisch aus Buchungen/Sperren/anderen Portalen, Mail + Erinnerung, Abhaken im Admin
- Optionaler signierter Automatisierungs-Webhook mit Rückmeldung
- Herkunftsmessung: Abfrage im Formular + UTM-Parameter
- Portal-Analyse: AGB-Prüfung Automatisierung, Umsetzungsbeschreibung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:13:55 +02:00

348 lines
11 KiB
PHP

<?php
namespace App\Livewire;
use App\Actions\CreateReservation;
use App\Actions\RequestMarketingConsent;
use App\Availability\AvailabilityChecker;
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 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 = '';
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 = '';
#[Locked]
public ?int $bookingId = null;
public function mount(?Property $property = null): void
{
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
$this->month = CarbonImmutable::today()->format('Y-m');
$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);
}
/**
* @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();
if ($this->website !== '') {
return;
}
$rateLimitKey = 'booking-request:'.request()->ip();
if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) {
$this->addError('email', 'Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an.');
return;
}
RateLimiter::hit($rateLimitKey, 3600);
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<string, list<string>>
*/
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'],
'lastName' => ['required', 'string', 'max:255'],
'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'],
'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',
'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,
);
}
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;
}
}