diff --git a/app/Actions/AssignOccupationGuest.php b/app/Actions/AssignOccupationGuest.php index 0316952..eb7cabc 100644 --- a/app/Actions/AssignOccupationGuest.php +++ b/app/Actions/AssignOccupationGuest.php @@ -41,7 +41,7 @@ public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $ 'tags' => ['nullable', 'array'], 'tags.*' => ['string', 'max:255'], ])->validate(); - $guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? 'DE']); + $guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? null]); $guest->forceFill(['tenant_id' => $record->tenant_id])->save(); } $record->forceFill(['guest_id' => $guest->id])->save(); diff --git a/app/Actions/AutoOffer.php b/app/Actions/AutoOffer.php index e48ffd2..8dc4bd0 100644 --- a/app/Actions/AutoOffer.php +++ b/app/Actions/AutoOffer.php @@ -12,6 +12,7 @@ use App\Exceptions\ReservationException; use App\Models\Booking; use App\Pricing\QuoteException; +use App\Process\CaseRequirements; use App\Support\Content; use App\Support\Settings; @@ -58,6 +59,8 @@ public function blockers(Booking $booking): array } if (blank($booking->guest?->email)) { $reasons[] = 'Die E-Mail-Adresse des Gastes fehlt.'; + } elseif (! $information && ($missing = CaseRequirements::blocker($booking, CaseRequirements::OFFER)) !== null) { + $reasons[] = $missing; } if (! $this->availability->isAvailable($property, $booking->arrival, $booking->departure, ignore: $booking)) { $reasons[] = 'Der Zeitraum ist inzwischen belegt.'; diff --git a/app/Actions/ContributeCaseFacts.php b/app/Actions/ContributeCaseFacts.php new file mode 100644 index 0000000..1ab4038 --- /dev/null +++ b/app/Actions/ContributeCaseFacts.php @@ -0,0 +1,234 @@ + $facts field key ({@see CaseRequirements::FIELDS} or OPTIONAL_FIELDS) => value + * @param array{reference?: string, inbound_message_id?: int, evidence?: array, confidence?: array, actor?: string, advance?: bool} $options + */ + public function handle(Booking $booking, array $facts, FactSource $source, array $options = []): FactContribution + { + $known = [...CaseRequirements::FIELDS, ...CaseRequirements::OPTIONAL_FIELDS]; + $facts = array_filter(array_map(fn (mixed $value): mixed => is_string($value) ? trim($value) : $value, array_intersect_key($facts, $known)), fn (mixed $value): bool => $value !== null && $value !== ''); + if (isset($facts['guest.email'])) { + $facts['guest.email'] = mb_strtolower((string) $facts['guest.email']); + } + if ($facts === []) { + return new FactContribution; + } + + $actor = $options['actor'] ?? ($source === FactSource::Landlord ? (auth()->user()?->name ?? 'Vermieter') : CaseLog::GUEST); + $reference = (string) ($options['reference'] ?? $options['inbound_message_id'] ?? ''); + + $contribution = DB::transaction(function () use ($booking, $facts, $source, $options, $actor, $reference): FactContribution { + $booking->lockForTransition(); + $booking->load('guest'); + + $recorded = []; + $guestChanges = []; + $bookingChanges = []; + foreach ($facts as $field => $value) { + $value = is_scalar($value) ? (string) $value : json_encode($value); + $fingerprint = hash('sha256', implode('|', [$booking->id, $source->value, $reference, $field, mb_strtolower($value)])); + if (CaseFact::query()->withoutGlobalScopes()->where('booking_id', $booking->id)->where('fingerprint', $fingerprint)->exists()) { + continue; + } + + $current = CaseRequirements::value($booking, $field); + $outcome = $this->outcome($booking, $field, $value, $current, $source); + if ($outcome === CaseFact::APPLIED) { + [$scope, $attribute] = explode('.', $field, 2); + if ($scope === 'guest') { + $guestChanges[$attribute] = $value; + } else { + $bookingChanges[$attribute] = $field === 'booking.guests' ? (int) $value : $value; + } + } + + $recorded[] = new CaseFact([ + 'booking_id' => $booking->id, + 'field' => $field, + 'value' => $value, + 'previous_value' => filled($current) ? (string) $current : null, + 'source' => $source, + 'inbound_message_id' => $options['inbound_message_id'] ?? null, + 'evidence' => $options['evidence'][$field] ?? null, + 'confidence' => $options['confidence'][$field] ?? null, + 'outcome' => $outcome, + 'fingerprint' => $fingerprint, + 'actor' => $actor, + 'created_at' => now(), + ]); + } + + $this->applyGuest($booking, $guestChanges, $recorded, $source); + if ($bookingChanges !== []) { + $booking->update($bookingChanges); + } + + foreach ($recorded as $fact) { + $fact->tenant_id = $booking->tenant_id; + $fact->save(); + } + + $contribution = new FactContribution($recorded); + if (! $contribution->isEmpty()) { + $this->openTasks($booking, $contribution, $source); + CaseLog::record($booking, 'facts', 'Angaben von '.$source->getLabel().': '.$contribution->summary(), data: ['fields' => array_map(fn (CaseFact $fact): array => ['field' => $fact->field, 'outcome' => $fact->outcome], $recorded)], actor: $actor); + } + + return $contribution; + }); + + if (! $contribution->isEmpty()) { + $booking->refresh()->load('guest'); + event(new CaseFactsContributed($booking, $contribution, $source)); + + if ($contribution->anyApplied() && ($options['advance'] ?? true)) { + app(CaseAutomation::class)->advance($booking); + } + } + + return $contribution; + } + + /** + * Phase of the case for the rules (CH §1.4): binding (P3) or not. + */ + public static function isBinding(Booking $booking): bool + { + return in_array($booking->status, BookingStatus::occupying(), true); + } + + private function outcome(Booking $booking, string $field, string $value, mixed $current, FactSource $source): string + { + if (! CaseRequirements::isValid($field, $value)) { + return CaseFact::REJECTED; + } + + $known = CaseRequirements::isValid($field, $current); + if ($known && $this->same($field, $value, $current)) { + return CaseFact::CONFIRMED; + } + + if (in_array($field, self::STAY_FIELDS, true)) { + // A stay detail never changes through the intake. Only an unknown number of guests may be completed – by the + // landlord or the portal's own message, or on a request that binds nobody yet. + $completes = ! $known && ($source->isAuthoritative() || $source === FactSource::PortalMail || ! self::isBinding($booking)); + + return $completes ? CaseFact::APPLIED : CaseFact::CHANGE_REQUEST; + } + + if (! $known || $source->isAuthoritative()) { + return CaseFact::APPLIED; + } + + return CaseFact::CONFLICT; + } + + private function same(string $field, string $value, mixed $current): bool + { + if ($field === 'booking.guests') { + return (int) $value === (int) $current; + } + + return mb_strtolower(preg_replace('/\s+/', ' ', $value)) === mb_strtolower(preg_replace('/\s+/', ' ', trim((string) $current))); + } + + /** + * Writes the taken-over guest details. A case without a guest gets a new guest record once a name is known; a + * known e-mail address never joins another person's record silently (the landlord assigns it). + * + * @param array $changes + * @param list $recorded + */ + private function applyGuest(Booking $booking, array $changes, array $recorded, FactSource $source): void + { + if ($changes === []) { + return; + } + + if ($booking->guest !== null) { + $booking->guest->update($changes); + + return; + } + + $email = $changes['email'] ?? ''; + // The landlord knows whom he enters; any other source must not attach the case to somebody else's record. + $taken = ! $source->isAuthoritative() && $email !== '' && Guest::query()->where('email', $email)->exists(); + if (blank($changes['first_name'] ?? null) || blank($changes['last_name'] ?? null) || $taken) { + foreach ($recorded as $fact) { + if ($fact->outcome === CaseFact::APPLIED && str_starts_with($fact->field, 'guest.')) { + $fact->outcome = CaseFact::CONFLICT; + } + } + + return; + } + + $guest = Guest::query()->create([...$changes, 'email' => $email, 'tenant_id' => $booking->tenant_id]); + $booking->update(['guest_id' => $guest->id]); + $booking->setRelation('guest', $guest); + } + + private function openTasks(Booking $booking, FactContribution $contribution, FactSource $source): void + { + if ($source->isAuthoritative()) { + // The landlord's entry settles what was put to him for these details. + BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::FactConflict)->where('status', BookingTaskStatus::Open) + ->whereIn('subject', array_map(fn (CaseFact $fact): string => $fact->field, $contribution->facts)) + ->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => auth()->user()?->name, 'note' => trim($task->note.' · von Ihnen entschieden')])->save()); + } + + foreach ($contribution->facts as $fact) { + if ($fact->outcome === CaseFact::CONFLICT) { + BookingTask::openOnce($booking, BookingTaskKind::FactConflict, $fact->field, [ + 'due_on' => today(), + 'note' => CaseRequirements::label($fact->field).' laut '.$source->getLabel().': „'.$fact->value.'“'.($fact->previous_value ? ' (bisher „'.$fact->previous_value.'“)' : ' (noch nicht eingetragen – Zuordnung prüfen)'), + ]); + } + if ($fact->outcome === CaseFact::CHANGE_REQUEST) { + BookingTask::openOnce($booking, BookingTaskKind::ChangeRequest, $fact->field.':'.substr($fact->fingerprint, 0, 12), [ + 'due_on' => today(), + 'note' => 'Gewünscht laut '.$source->getLabel().': '.CaseRequirements::label($fact->field).' „'.$fact->value.'“'.($fact->previous_value ? ' (gebucht: „'.$fact->previous_value.'“)' : '').'. Nichts wurde geändert – bitte über „Buchung ändern“ bzw. ein neues Angebot entscheiden.', + ]); + } + } + } +} diff --git a/app/Actions/CreateReservation.php b/app/Actions/CreateReservation.php index 7bcf143..7daf59d 100644 --- a/app/Actions/CreateReservation.php +++ b/app/Actions/CreateReservation.php @@ -4,6 +4,7 @@ use App\Availability\AvailabilityChecker; use App\Enums\BookingStatus; +use App\Enums\FactSource; use App\Enums\IntakeKind; use App\Exceptions\ReservationException; use App\Mail\NewReservation; @@ -103,6 +104,16 @@ private function create(Property $property, StayRequest $stay, array $guestData, ]); }); + 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); } diff --git a/app/Actions/DecideBookingWish.php b/app/Actions/DecideBookingWish.php index cbd04bf..f831d05 100644 --- a/app/Actions/DecideBookingWish.php +++ b/app/Actions/DecideBookingWish.php @@ -11,6 +11,7 @@ use App\Models\BookingTask; use App\Pricing\StayRequest; use App\Process\CaseLog; +use App\Process\CaseRequirements; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; @@ -43,6 +44,10 @@ public function confirm(Booking $booking, bool $useTodaysPrice = false, bool $no if ($booking->status !== BookingStatus::Reserved || $booking->wish_at === null) { throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Buchungswunsch bestätigt'); } + // G2a also before the binding confirmation of a wish (v0.11, B3), by hand as well. + if (($missing = CaseRequirements::blocker($booking->load('guest'), CaseRequirements::WISH_CONFIRMATION)) !== null) { + throw new ReservationException($missing); + } if ($useTodaysPrice) { $quote = $this->offer->quoteFor($booking, new StayRequest($booking->arrival, $booking->departure, $booking->guests, $booking->extras ?? [], $booking->promo_code), (int) $booking->price_adjustment, (string) ($booking->price_adjustment_label ?: 'Zuschlag')); diff --git a/app/Actions/ProvideGuestContact.php b/app/Actions/ProvideGuestContact.php index 61bcedf..1836ab3 100644 --- a/app/Actions/ProvideGuestContact.php +++ b/app/Actions/ProvideGuestContact.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Enums\BookingStatus; +use App\Enums\FactSource; use App\Enums\IntakeKind; use App\Enums\ProcessingMode; use App\Exceptions\ReservationException; @@ -41,15 +42,13 @@ public function handle(Booking $booking, array $contact, string $process = self: throw new ReservationException('Für den automatischen Ablauf wird die E-Mail-Adresse des Gastes benötigt.'); } - if ($booking->guest === null) { - if (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null)) { - throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.'); - } - $guest = Guest::query()->create([...array_filter($contact, fn ($value) => $value !== null), 'email' => $contact['email'] ?? '']); - $booking->update(['guest_id' => $guest->id]); - } else { - $booking->guest->update(array_filter($contact, fn ($value) => $value !== null)); + if ($booking->guest === null && (blank($contact['first_name'] ?? null) || blank($contact['last_name'] ?? null))) { + throw new ReservationException('Bitte Vor- und Nachnamen des Gastes angeben.'); } + + // The landlord's entry goes through the common fact intake (v0.11, S5): taken over with its source, the previous + // value kept as evidence. Carrying on stays with the choice below. + app(ContributeCaseFacts::class)->handle($booking, collect($contact)->mapWithKeys(fn (?string $value, string $field): array => ['guest.'.$field => $value])->all(), FactSource::Landlord, ['advance' => false, 'reference' => 'landlord:'.now()->getTimestampMs()]); if ($guestConfirmed) { $booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->save(); } diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index 3a18140..bfb59c0 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -20,6 +20,7 @@ use App\Pricing\QuoteLine; use App\Pricing\StayRequest; use App\Process\CaseLog; +use App\Process\CaseRequirements; use App\Support\Inbox; use Carbon\CarbonImmutable; use Illuminate\Support\Arr; @@ -65,6 +66,11 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet'); } + // G2a (v0.11): never an own binding offer without the required details – not even confirmed by hand. + if (($missing = CaseRequirements::blocker($booking->loadMissing('guest'), CaseRequirements::OFFER)) !== null) { + throw new ReservationException($missing); + } + $toConfirm = app(DocumentComposer::class)->compose($booking, DocumentKind::Offer, $changes)->toConfirm(); if ($toConfirm !== [] && ! ($changes['acknowledged'] ?? false)) { throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $toConfirm)); diff --git a/app/Actions/SubmitBookingWish.php b/app/Actions/SubmitBookingWish.php index bf405c9..1fe65b0 100644 --- a/app/Actions/SubmitBookingWish.php +++ b/app/Actions/SubmitBookingWish.php @@ -20,6 +20,7 @@ use App\Pricing\StayRequest; use App\Process\CaseAutomation; use App\Process\CaseLog; +use App\Process\CaseRequirements; use App\Support\Inbox; use App\Support\Money; use App\Support\Settings; @@ -198,6 +199,9 @@ public function findings(Booking $booking, array $stale = []): array } $findings = [...$findings, ...app(CaseAutomation::class)->documentBlockers($booking)]; + if (($missing = CaseRequirements::blocker($booking, CaseRequirements::WISH_CONFIRMATION)) !== null) { + $findings[] = $missing; + } if (! app(AutoOffer::class)->contractTextsReleased()) { $findings[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).'; } diff --git a/app/Documents/DocumentComposer.php b/app/Documents/DocumentComposer.php index bff9d75..4cc9a71 100644 --- a/app/Documents/DocumentComposer.php +++ b/app/Documents/DocumentComposer.php @@ -17,6 +17,7 @@ use App\Pricing\QuoteException; use App\Pricing\StayRequest; use App\Process\CaseActivities; +use App\Process\CaseRequirements; use App\Process\ProcessProfile; use App\Process\ProcessSettings; use App\Support\Money; @@ -194,6 +195,11 @@ private function commonFindings(Booking $booking, Booking $draft, DocumentKind $ } elseif (blank($draft->guest->email)) { $findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.'); } + // G2a (v0.11, E-032): an own binding offer needs the contracting party's name, e-mail, full address with country, + // the number of guests and the dates – a hard blocker, also by hand. The information "unter Vorbehalt" does not (B3). + if ($kind === DocumentKind::Offer && $draft->guest !== null && ($missing = CaseRequirements::blocker($draft, CaseRequirements::OFFER)) !== null) { + $findings[] = DocumentFinding::blocker($missing); + } if (! in_array($kind, [DocumentKind::Offer, DocumentKind::Information], true) && $booking->total === null) { $findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.'); } diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php index 9ce05a4..7e0e6a7 100644 --- a/app/Enums/BookingTaskKind.php +++ b/app/Enums/BookingTaskKind.php @@ -31,6 +31,8 @@ enum BookingTaskKind: string implements HasLabel case FollowUp = 'follow_up'; case PayoutCheck = 'payout_check'; case OpenClaim = 'open_claim'; + case FactConflict = 'fact_conflict'; + case ChangeRequest = 'change_request'; public function getLabel(): string { @@ -51,6 +53,8 @@ public function getLabel(): string self::FollowUp => 'Folgeaufgabe', self::PayoutCheck => 'Auszahlung des Portals prüfen', self::OpenClaim => 'Offenen Betrag nach der Abreise klären', + self::FactConflict => 'Abweichende Angabe des Gastes prüfen', + self::ChangeRequest => 'Änderungswunsch des Gastes prüfen', }; } diff --git a/app/Enums/FactSource.php b/app/Enums/FactSource.php new file mode 100644 index 0000000..bbb9b7f --- /dev/null +++ b/app/Enums/FactSource.php @@ -0,0 +1,38 @@ + 'Anfrageformular der Webseite', + self::GuestLink => 'Gast über den Ergänzungslink', + self::Email => 'E-Mail des Gastes', + self::PortalMail => 'Portal-Mail', + self::Extraction => 'aus einer Nachricht erkannt (KI)', + self::Landlord => 'von Ihnen eingetragen', + }; + } + + /** + * The landlord's own entry is authoritative; every other source only completes or is put to the landlord. + */ + public function isAuthoritative(): bool + { + return $this === self::Landlord; + } +} diff --git a/app/Events/CaseFactsContributed.php b/app/Events/CaseFactsContributed.php new file mode 100644 index 0000000..0181f6e --- /dev/null +++ b/app/Events/CaseFactsContributed.php @@ -0,0 +1,23 @@ +findOrFail($data['channel_id']) : null; $arrival = CarbonImmutable::parse($data['arrival']); $departure = CarbonImmutable::parse($data['departure']); - $guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']); + $guest = Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']); if ($data['kind'] === BookingForm::EXTERNAL) { return app(TakeOverExternalBooking::class)->handle($property, $channel, $arrival, $departure, [ diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index 718b051..9814a3c 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -44,6 +44,7 @@ use App\Process\CaseActivities; use App\Process\CaseAutomation; use App\Process\CaseLog; +use App\Support\Countries; use App\Support\Money; use Carbon\CarbonImmutable; use Filament\Actions\Action; @@ -291,10 +292,10 @@ private function provideContactAction(): Action ->icon(Heroicon::OutlinedUserPlus) ->visible(fn (): bool => $this->record->internal_kind !== InternalKind::Block && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true)) ->modalHeading('Kontaktdaten des Gastes') - ->modalDescription('Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.') + ->modalDescription(fn (): string => 'Aus Portalnachricht, E-Mail oder Telefonat. Nur eintragen, was bekannt ist.'.$this->openFactConflicts()) ->modalWidth('3xl') ->fillForm(fn (): array => [ - 'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']) ?? [], + 'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']) ?? [], 'process' => $this->record->processingMode() === ProcessingMode::Automatic ? ProvideGuestContact::AUTOMATIC : ProvideGuestContact::MANUAL, 'guest_confirmed' => $this->record->guest_confirmed_at !== null, ]) @@ -307,6 +308,7 @@ private function provideContactAction(): Action TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150), TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20), TextInput::make('guest.city')->label('Ort')->maxLength(100), + Select::make('guest.country')->label('Land')->options(Countries::options())->placeholder('nicht bekannt'), ]), Section::make('Wie geht es danach weiter?')->schema([ Radio::make('process')->hiddenLabel()->options([ @@ -331,6 +333,16 @@ private function provideContactAction(): Action }); } + /** + * Details from the guest's side that differ from the stored ones (v0.11 fact intake), for the contact dialog. + */ + private function openFactConflicts(): string + { + $notes = $this->record->tasks()->where('kind', BookingTaskKind::FactConflict)->where('status', BookingTaskStatus::Open)->pluck('note')->all(); + + return $notes === [] ? '' : ' Abweichende Angaben des Gastes – bitte den richtigen Wert eintragen: '.implode(' · ', $notes); + } + private function requestContactAction(): Action { return Action::make('requestContact') diff --git a/app/Filament/Resources/Bookings/Schemas/BookingForm.php b/app/Filament/Resources/Bookings/Schemas/BookingForm.php index b1907c8..66a7ff2 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingForm.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingForm.php @@ -7,6 +7,7 @@ use App\Models\Channel; use App\Models\Extra; use App\Models\Property; +use App\Support\Countries; use App\Support\CurrentProperty; use App\Support\Money; use Filament\Forms\Components\DatePicker; @@ -140,6 +141,7 @@ public static function configure(Schema $schema): Schema TextInput::make('street')->label('Straße')->maxLength(255), TextInput::make('postal_code')->label('PLZ')->maxLength(20), TextInput::make('city')->label('Ort')->maxLength(255), + Select::make('country')->label('Land')->options(Countries::options())->placeholder('nicht bekannt'), Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible($is(self::EXTERNAL)), ]), Section::make('Wie geht es weiter?') diff --git a/app/Livewire/BookingRequest.php b/app/Livewire/BookingRequest.php index 129eeec..42fad6b 100644 --- a/app/Livewire/BookingRequest.php +++ b/app/Livewire/BookingRequest.php @@ -16,6 +16,7 @@ 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; @@ -64,6 +65,9 @@ class BookingRequest extends Component 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; @@ -105,6 +109,16 @@ 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). */ @@ -261,6 +275,7 @@ public function submit(CreateReservation $createReservation): void '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], @@ -328,9 +343,10 @@ protected function rules(): array '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'], + '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.'); @@ -353,6 +369,10 @@ protected function validationAttributes(): array 'firstName' => 'Vorname', 'lastName' => 'Nachname', 'email' => 'E-Mail', + 'street' => 'Straße & Hausnr.', + 'postalCode' => 'PLZ', + 'city' => 'Ort', + 'country' => 'Land', 'privacyAccepted' => 'Datenschutzerklärung', ]; } diff --git a/app/Models/CaseFact.php b/app/Models/CaseFact.php new file mode 100644 index 0000000..443ae6b --- /dev/null +++ b/app/Models/CaseFact.php @@ -0,0 +1,65 @@ + + */ + protected function casts(): array + { + return [ + 'value' => 'encrypted', + 'previous_value' => 'encrypted', + 'evidence' => 'encrypted', + 'source' => FactSource::class, + 'confidence' => 'float', + 'created_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } + + public function outcomeLabel(): string + { + return match ($this->outcome) { + self::APPLIED => 'übernommen', + self::CONFIRMED => 'bestätigt (gleicher Wert)', + self::CONFLICT => 'weicht ab – zur Prüfung', + self::CHANGE_REQUEST => 'Änderungswunsch – zur Prüfung', + default => 'nicht verwendbar', + }; + } +} diff --git a/app/Process/CaseActivities.php b/app/Process/CaseActivities.php index d362371..c7ddd5b 100644 --- a/app/Process/CaseActivities.php +++ b/app/Process/CaseActivities.php @@ -64,14 +64,29 @@ public static function for(Booking $booking): array $needsContact = $inquiry || $profile->documents() === Responsibility::Landlord || $profile->guestMessages() === Responsibility::Landlord || $profile->payments() === Responsibility::Landlord; if ($needsContact) { $hasEmail = filled($booking->guest?->email); + // v0.11 (G2a): before the own binding offer – or the binding confirmation of a wish – every required detail. + $action = $profile->preReservation() || $booking->offer_version > 0 ? CaseRequirements::OFFER : CaseRequirements::WISH_CONFIRMATION; + $needsDetails = $inquiry && ! $binding && $booking->offer_version === 0 && ($action === CaseRequirements::OFFER || $booking->wish_at !== null); + $missing = $hasEmail && $needsDetails ? CaseRequirements::missing($booking, $action) : []; + $asked = $booking->contact_requested_at !== null; $state = match (true) { - $hasEmail => ActivityState::Done, - $booking->contact_requested_at !== null => ActivityState::Waiting, + $hasEmail && $missing === [] => ActivityState::Done, + $asked => ActivityState::Waiting, default => ActivityState::Open, }; - $activities[] = new Activity('contact', $booking->guest === null ? 'Name und Kontaktdaten des Gastes eintragen' : 'E-Mail-Adresse des Gastes eintragen', $later($state), - $hasEmail ? $booking->guestName() : ($booking->contact_requested_at ? 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y') : 'fehlt noch'), - $hasEmail ? null : 'provideContact'); + $title = match (true) { + $booking->guest === null => 'Name und Kontaktdaten des Gastes eintragen', + ! $hasEmail => 'E-Mail-Adresse des Gastes eintragen', + $missing !== [] => $action === CaseRequirements::OFFER ? 'Angaben für das Angebot vervollständigen' : 'Angaben für die Bestätigung vervollständigen', + default => 'Kontaktdaten des Gastes', + }; + $detail = match (true) { + $state === ActivityState::Done => $booking->guestName(), + $missing !== [] => 'fehlt: '.implode(', ', CaseRequirements::labels($missing)).($asked ? ' · beim Gast angefragt' : ''), + $booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'), + default => 'fehlt noch', + }; + $activities[] = new Activity('contact', $title, $later($state), $detail, $state === ActivityState::Done ? null : 'provideContact'); } if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) { @@ -322,6 +337,7 @@ private static function task(BookingTask $task): Activity BookingTaskKind::BookingWish => 'decideWish', BookingTaskKind::ArrivalDetails => 'arrivalDetails', BookingTaskKind::CancellationRequest => 'end', + BookingTaskKind::FactConflict => 'provideContact', default => $task->kind->isPayment() ? null : 'completeTask', }; $today = CarbonImmutable::today(); diff --git a/app/Process/CaseRequirements.php b/app/Process/CaseRequirements.php new file mode 100644 index 0000000..d440862 --- /dev/null +++ b/app/Process/CaseRequirements.php @@ -0,0 +1,138 @@ + field key => label */ + public const FIELDS = [ + 'guest.first_name' => 'Vorname', + 'guest.last_name' => 'Nachname', + 'guest.email' => 'E-Mail-Adresse', + 'guest.street' => 'Straße und Hausnummer', + 'guest.postal_code' => 'PLZ', + 'guest.city' => 'Ort', + 'guest.country' => 'Land', + 'booking.guests' => 'Personenzahl', + 'booking.arrival' => 'Anreise', + 'booking.departure' => 'Abreise', + ]; + + /** Fields the guest can give for a case (contact and stay details beyond the required ones). */ + public const OPTIONAL_FIELDS = [ + 'guest.phone' => 'Telefon', + 'booking.arrival_time' => 'Voraussichtliche Anreisezeit', + ]; + + /** + * Required fields of the action that are missing or not valid. + * + * @return list field keys of {@see self::FIELDS} + */ + public static function missing(Booking $booking, string $action = self::OFFER): array + { + $missing = []; + foreach (array_keys(self::FIELDS) as $field) { + if (! self::isValid($field, self::value($booking, $field))) { + $missing[] = $field; + } + } + + return $missing; + } + + public static function isComplete(Booking $booking, string $action = self::OFFER): bool + { + return self::missing($booking, $action) === []; + } + + /** + * The blocker text for the action, or null when nothing is missing. + */ + public static function blocker(Booking $booking, string $action = self::OFFER): ?string + { + $missing = self::missing($booking, $action); + if ($missing === []) { + return null; + } + + $what = $action === self::WISH_CONFIRMATION ? 'die verbindliche Bestätigung' : 'ein verbindliches Angebot'; + + return 'Für '.$what.' fehlen noch Angaben: '.implode(', ', self::labels($missing)).'.'; + } + + /** + * Whether an incomplete request may get the clarification hold (V1, E-033): property, unambiguous dates and an + * e-mail address that can be written to. The free calendar is checked by the caller. + */ + public static function qualifiesForClarificationHold(Booking $booking): bool + { + return $booking->property_id !== null + && $booking->arrival !== null && $booking->departure !== null && $booking->departure->greaterThan($booking->arrival) + && self::isValid('guest.email', $booking->guest?->email); + } + + /** + * @param list $fields + * @return list + */ + public static function labels(array $fields): array + { + return array_map(fn (string $field): string => self::FIELDS[$field] ?? self::OPTIONAL_FIELDS[$field] ?? $field, $fields); + } + + public static function label(string $field): string + { + return self::labels([$field])[0]; + } + + /** + * Current value of a field of the case (guest fields from the guest record). + */ + public static function value(Booking $booking, string $field): mixed + { + [$scope, $attribute] = explode('.', $field, 2); + $value = $scope === 'guest' ? $booking->guest?->{$attribute} : $booking->{$attribute}; + + return $value instanceof \DateTimeInterface ? $value->format('Y-m-d') : $value; + } + + /** + * Whether a value is usable for the field. + */ + public static function isValid(string $field, mixed $value): bool + { + if (is_string($value)) { + $value = trim($value); + } + if ($value === null || $value === '') { + return false; + } + + return match ($field) { + 'guest.email' => filter_var($value, FILTER_VALIDATE_EMAIL) !== false, + 'guest.postal_code' => (bool) preg_match('/^[A-Za-z0-9][A-Za-z0-9 \-]{1,9}$/', (string) $value), + 'guest.country' => (bool) preg_match('/^[A-Z]{2}$/', (string) $value), + 'booking.guests' => is_numeric($value) && (int) $value >= 1, + 'booking.arrival', 'booking.departure' => strtotime((string) $value) !== false, + default => mb_strlen((string) $value) >= 1, + }; + } +} diff --git a/app/Process/FactContribution.php b/app/Process/FactContribution.php new file mode 100644 index 0000000..6066113 --- /dev/null +++ b/app/Process/FactContribution.php @@ -0,0 +1,55 @@ + $facts recorded facts (duplicates of an earlier contribution are not recorded again) + */ + public function __construct(public readonly array $facts = []) {} + + /** + * @return list field keys with the given outcome + */ + public function fields(string $outcome): array + { + return array_values(array_map(fn (CaseFact $fact): string => $fact->field, array_filter($this->facts, fn (CaseFact $fact): bool => $fact->outcome === $outcome))); + } + + public function anyApplied(): bool + { + return $this->fields(CaseFact::APPLIED) !== []; + } + + public function needsReview(): bool + { + return $this->fields(CaseFact::CONFLICT) !== [] || $this->fields(CaseFact::CHANGE_REQUEST) !== []; + } + + public function isEmpty(): bool + { + return $this->facts === []; + } + + /** + * Plain words for the landlord, e.g. for a notification. + */ + public function summary(): string + { + $parts = []; + foreach ([CaseFact::APPLIED => 'übernommen', CaseFact::CONFIRMED => 'bestätigt', CaseFact::CONFLICT => 'weichen ab (zur Prüfung)', CaseFact::CHANGE_REQUEST => 'Änderungswunsch (zur Prüfung)', CaseFact::REJECTED => 'nicht verwendbar'] as $outcome => $label) { + $fields = $this->fields($outcome); + if ($fields !== []) { + $parts[] = implode(', ', CaseRequirements::labels($fields)).' '.$label; + } + } + + return $parts === [] ? 'Keine neuen Angaben.' : implode(' · ', $parts); + } +} diff --git a/app/Support/Countries.php b/app/Support/Countries.php new file mode 100644 index 0000000..e9619c1 --- /dev/null +++ b/app/Support/Countries.php @@ -0,0 +1,44 @@ + code => name + */ + public static function options(): array + { + return [ + 'DE' => 'Deutschland', + 'AT' => 'Österreich', + 'CH' => 'Schweiz', + 'NL' => 'Niederlande', + 'BE' => 'Belgien', + 'LU' => 'Luxemburg', + 'DK' => 'Dänemark', + 'SE' => 'Schweden', + 'NO' => 'Norwegen', + 'FI' => 'Finnland', + 'PL' => 'Polen', + 'CZ' => 'Tschechien', + 'FR' => 'Frankreich', + 'IT' => 'Italien', + 'ES' => 'Spanien', + 'GB' => 'Vereinigtes Königreich', + 'IE' => 'Irland', + 'US' => 'Vereinigte Staaten', + ]; + } + + public static function name(?string $code): ?string + { + return $code === null ? null : (self::options()[$code] ?? $code); + } +} diff --git a/database/migrations/2026_11_06_100000_create_case_facts.php b/database/migrations/2026_11_06_100000_create_case_facts.php new file mode 100644 index 0000000..8a68bf5 --- /dev/null +++ b/database/migrations/2026_11_06_100000_create_case_facts.php @@ -0,0 +1,60 @@ +id(); + $table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->string('field', 60); + $table->text('value')->nullable(); + $table->text('previous_value')->nullable(); + $table->string('source', 30); + $table->unsignedBigInteger('inbound_message_id')->nullable()->index(); + $table->text('evidence')->nullable(); + $table->decimal('confidence', 4, 3)->nullable(); + $table->string('outcome', 20); + $table->string('fingerprint', 64); + $table->string('actor')->nullable(); + $table->dateTime('created_at'); + + $table->index(['booking_id', 'field']); + $table->index(['booking_id', 'fingerprint']); + }); + + Schema::table('bookings', function (Blueprint $table) { + $table->string('hold_purpose', 20)->default('offer')->after('hold_expires_at'); + }); + + // B4: the country is never assumed. New guests have none until a source names it (existing values stay, they + // cannot be told apart from confirmed ones). + Schema::table('guests', function (Blueprint $table) { + $table->string('country', 2)->nullable()->default(null)->change(); + }); + } + + public function down(): void + { + Schema::table('guests', function (Blueprint $table) { + $table->string('country', 2)->default('DE')->change(); + }); + + Schema::table('bookings', function (Blueprint $table) { + $table->dropColumn('hold_purpose'); + }); + + Schema::dropIfExists('case_facts'); + } +}; diff --git a/resources/views/livewire/booking-request.blade.php b/resources/views/livewire/booking-request.blade.php index 569c451..c39362e 100644 --- a/resources/views/livewire/booking-request.blade.php +++ b/resources/views/livewire/booking-request.blade.php @@ -168,9 +168,9 @@ ['lastName', 'Nachname', 'text', 'family-name', true], ['email', 'E-Mail', 'email', 'email', true], ['phone', 'Telefon', 'tel', 'tel', false], - ['street', 'Straße & Hausnr.', 'text', 'street-address', false], - ['postalCode', 'PLZ', 'text', 'postal-code', false], - ['city', 'Ort', 'text', 'address-level2', false], + ['street', 'Straße & Hausnr.', 'text', 'street-address', $this->requiresAddress], + ['postalCode', 'PLZ', 'text', 'postal-code', $this->requiresAddress], + ['city', 'Ort', 'text', 'address-level2', $this->requiresAddress], ] as [$field, $label, $type, $autocomplete, $required]) @endforeach +