$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.', ]); } } } }