Files
fewo-stommer/app/Actions/ContributeCaseFacts.php
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

235 lines
11 KiB
PHP
Raw Permalink 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\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Events\CaseFactsContributed;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\CaseFact;
use App\Models\Guest;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Process\FactContribution;
use Illuminate\Support\Facades\DB;
/**
* The common fact intake of v0.11 (S5, CH-03, E-038). Every source – website form, the guest's link, an e-mail,
* a portal mail, the extraction, the landlord – hands its details for a case to this one place:
*
* - a missing value is taken over, an equal one confirmed;
* - a different contact or address value from the guest's side is never written over the stored one: it becomes a
* conflict for the landlord (the guest record may belong to other cases too);
* - the landlord's own entry is authoritative and replaces the value, the previous one stays in the evidence;
* - dates and the number of guests are stay details: a differing value (and in a binding case also a missing one from
* the guest's side) is only a change request for the landlord – nothing about the booking changes here;
* - invalid values are rejected.
*
* Every detail is recorded with source and outcome. The same contribution again is harmless (idempotent). Afterwards
* the existing process is asked once to carry on (S6); this intake decides nothing about offers or bookings.
*/
class ContributeCaseFacts
{
/** Stay details: never changed through the intake once known (P02/P03: change requests). */
public const STAY_FIELDS = ['booking.guests', 'booking.arrival', 'booking.departure'];
/**
* @param array<string, mixed> $facts field key ({@see CaseRequirements::FIELDS} or OPTIONAL_FIELDS) => value
* @param array{reference?: string, inbound_message_id?: int, evidence?: array<string, string>, confidence?: array<string, float>, 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<string, string> $changes
* @param list<CaseFact> $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.',
]);
}
}
}
}