Compare commits

...
10 Commits
Author SHA1 Message Date
LarsandClaude Opus 5.5 6862dec201 v0.11 U6: Bring your own key für die KI-Auswertung (Anthropic, OpenRouter)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 5m11s
- Jeder Mandant verbindet unter „System › KI-Anbindung“ seinen eigenen
  Zugang: Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für
  die erste Auswertung und für die Prüfung – keine Modellkennung im Code,
  kein zentraler Betreiberschlüssel (FEWO_AI_API_KEY entfällt).
- Gespeichert im bestehenden TenantService (ai_guest_mail): Schlüssel
  verschlüsselt, nie wieder angezeigt, nie in Meldungen; Anbieter/Modelle
  in settings, Prüfergebnis in check_status/check_message/checked_at.
- Feste Endpunkte je Anbieter (AiProvider), nicht konfigurierbar.
  OpenRouter mit response_format json_schema (strict) und
  provider.require_parameters.
- „Verbindung prüfen“ testet beide Modelle. Ein abgelehnter Zugang
  (401/402/403) schaltet die Auswertung für den Mandanten ab, meldet es im
  Postfach der Verwaltung; Nachrichten bleiben zur Prüfung im Posteingang.
- Zweistufige Extraktion und ihre Sicherheitsregeln unverändert.
- Zielarchitektur §3.8, Umsetzungsplan U6, Bericht, Drehbuch, Status.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:19:13 +01:00
LarsandClaude Opus 5.5 6f9aa46943 v0.11: Umsetzungsbericht, Abnahme-Drehbuch, Status; InboxTest wiederhergestellt
- Umsetzungsergebnis mit Rückverfolgung CH-01–18, S1–S6, E-032–038,
  M01–M12, Entscheidungen, Einschränkungen und Go-live-Bedingungen.
- Abnahme auf dem Testsystem: benötigte Dienste, Testkonfiguration,
  Drehbuch ohne manuelle Ersatzschritte.
- Der bestehende InboxTest (Postfach der Vermieterin) war versehentlich
  überschrieben worden; wiederhergestellt, die U5-Tests heißen jetzt
  GuestMailInboxTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:03:17 +01:00
LarsandClaude Opus 5.5 73c0a716b9 v0.11: durchgehender Integrationstest des MVP (Anfrage bis Buchung, Portalbuchung)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:55:35 +01:00
LarsandClaude Opus 5.5 4170e3bd29 v0.11 U6: risikobasierte KI-Extraktion von Gast- und Portalnachrichten
- Kleines Modell (claude-haiku-5-5) extrahiert Fakten mit Belegstelle und
  Konfidenz; programmatische Prüfung (Gültigkeit, Belegstelle im Original,
  Widerspruch zum gespeicherten Wert oder in der Nachricht, Plausibilität,
  Kritikalität nach Feld und Phase). Widerspruch oder fehlgeschlagene
  Prüfung → Prüfmodell (claude-opus-5-5, serverseitiger Fallback bei
  Ablehnung) unabhängig von der Konfidenz; solche Fakten nie automatisch.
- Nur geprüfte, bisher fehlende Angaben gehen an den Fakteneingang (Quelle
  „llm“); Zeitraum/Personen nur als Änderungswunsch (M06); Rest als
  Vorschlag im Posteingang („Vorschläge übernehmen“).
- Versionierte Prompts mit Platzhaltern, JSON-Schema mit eigener
  Validierung und einer Wiederholung; Ausfall/Ablehnung → sicherer
  Rückfall zur Vermieterin. HTTP-Client, kein SDK (laut Plan).
- Dienst „KI: Gästekommunikation“ verdrahtet, standardmäßig aus;
  Schlüssel je Mandant oder FEWO_AI_API_KEY; Verbrauch in service_usages.
- messages:extract alle fünf Minuten; ai:evaluate misst Fehlwerte und
  übersehene Angaben getrennt (M05).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:49:51 +01:00
LarsandClaude Opus 5.5 dff9e2344e v0.11 U5: Posteingang, deterministische Zuordnung, Klärungsansicht
- mailboxes (Modell für mehrere, eines aktiv): Übernahme des bisherigen
  Postfachs als „nur Portal-Mails“; Modus „alle Nachrichten“ für ein
  eigenes Postfach; Adresse als Antwortadresse der Rückfragen.
- inbound_messages: jede Nachricht zuerst gespeichert, einmal je
  Message-ID, mit Testbetriebs-Kennzeichen (M10). Portal-Mails laufen
  unverändert über den Portalpfad (CH-08).
- MessageMatcher (CH-13, ohne Scoring): Antwortbezug; Vorgangsnummer nur
  mit dem Gast als Absender; sonst Absender + Wohnung + beide Termine eines
  einzigen offenen Vorgangs. Ein offener Vorgang des Absenders allein
  genügt nicht (nur Hinweis). Alles andere → Klärung (M04).
- Ausgehende Mails speichern ihre Message-ID; Antwort stoppt Erinnerungen.
- Filament „Posteingang“: lesen, Vorgang zuordnen, als neue Anfrage
  anlegen, ignorieren, erledigt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:39:20 +01:00
LarsandClaude Opus 5.5 e4a3cb7f7b v0.11 U4: Rückfrage, Folgefrage, Erinnerung und Ergänzungslink
- data_requests: ein Beschaffungsvorgang je Vorgang mit Modus
  (automatisch / Freigabe / manuell), getrennten Zählern für Folgefragen
  und Erinnerungen ohne Rücksetzen, Antwortfrist ≠ Reservierungsfrist.
- RequestCaseData: fragt nach, was für das nächste Angebot, die
  Wunschbestätigung oder (bei verbindlichen Buchungen) administrativ fehlt;
  ohne E-Mail keine Rückfrage. Teilantwort → gezielte Folgefrage, Schweigen
  → Erinnerungen, an der Grenze Aufgabe für die Vermieterin. Nie ein Hold.
- Mail DataRequested mit Texten nach tatsächlichem Sperrstatus (M11);
  Dokumentart „Rückfrage“ – im Live-Betrieb ohne Freigabe nur nach Klick.
- Signierter, versionierter Ergänzungslink (/angebot/angaben): Lesen
  schreibt nicht, Absenden über den Fakteneingang, idempotent.
- Vorgang: „Rückfrage an den Gast senden“ / „Rückfrage beenden“;
  Eingangsbestätigung nennt die Klärungsreservierung korrekt.
- Zeitplan: cases:data-requests alle fünf Minuten.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:25:48 +01:00
LarsandClaude Opus 5.5 37f48defcc v0.11 U3: Klärungsreservierung für unvollständige Anfragen
- bookings.hold_purpose (offer wie bisher / clarification).
- RequestHold: vollständige Anfrage → Angebots-Hold unverändert;
  unvollständig, aber Wohnung, Zeitraum, verwendbare E-Mail und freier
  Zeitraum → nur Klärungsreservierung (15 min automatisch / 180 min
  Freigabe oder manuell, 0 = keine); sonst nichts (B1). Auch für
  Portalanfragen ohne Gastdaten.
- ExpireReservations beendet nur Angebots-Holds; ein abgelaufener
  Klärungsblock gibt nur den Kalender frei, der Vorgang bleibt offen.
- Vervollständigen erzeugt keinen Hold; erst SendOffer setzt den
  unveränderten Angebots-Hold. AutoOffer prüft danach nur die Verfügbarkeit.
- Booking::clarificationState() liefert den tatsächlichen Sperrstatus.
- Architekturtest: nur die bestehenden Reservierungsschritte schreiben Holds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 13:13:24 +01:00
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
LarsandClaude Opus 5.5 799869c6a4 v0.11 U1: Kanalmanager mit eigener Webseite und neuen Prozessparametern
- Eigene Webseite als Kanal eigener Art (channels.kind = website), nur zur
  Konfiguration: Webseiten-Anfragen bleiben direkt (A1) ohne Kanalbezug;
  der Eintrag nimmt an Sync, Export, Überwachung und Sperraufgaben nicht teil
  (active()/Property::channels() nur Portale, Feed nur für Portale).
- Neue Einstellungen im bestehenden ProcessSetting: Klärungsreservierung
  automatisch/Freigabe (15/180 min, 0 = keine), Rückfragemodus,
  Erinnerungen, Folgefragen, Erinnerungsabstand, Linkgültigkeit,
  Anschrift im Webformular verlangen (Standard: nein).
- „Kanäle“ in der einfachen Ansicht: Webseite und Portale an einer Stelle,
  Verweis auf „Ihre Standards“; „Wirksame Einstellungen“ mit Spalte
  „Eigene Webseite“ und Herkunft „Webseite“.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:52:50 +01:00
LarsandClaude Opus 5.5 bfccfe7eed v0.11: Soll-Ist-Analyse, technische Zielarchitektur und Umsetzungsplan
Planung zur Prozessarchitektur v0.11 (Communication Handler,
Datenbeschaffung, Klärungsreservierung, zentraler Kanalmanager) mit sechs
Umsetzungspaketen U1–U6. Betreiberentscheidungen B1–B4 vom 03.11.2026
eingearbeitet; Präzisierungen zur Zuordnung direkter Gast-Mails (CH-13)
und zur KI-Eskalation unabhängig von der Modellkonfidenz.

Keine Codeänderung.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:32:48 +01:00
125 changed files with 7040 additions and 182 deletions

No files matched your search

+1 -1
View File
@@ -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();
+6 -1
View File
@@ -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;
@@ -53,11 +54,15 @@ public function blockers(Booking $booking): array
if ($information && ($booking->status !== BookingStatus::Reserved || $booking->information_version > 0)) {
$reasons[] = 'Die Anfrage ist bereits beantwortet oder nicht mehr offen.';
}
if (! $information && ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive())) {
// A request after its clarification hold (v0.11) only needs free dates, which are checked below.
$clarified = $booking->hold_purpose === Booking::HOLD_CLARIFICATION;
if (! $information && ($booking->status !== BookingStatus::Reserved || (! $clarified && ! $booking->isHoldActive()))) {
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
}
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.';
+234
View File
@@ -0,0 +1,234 @@
<?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.',
]);
}
}
}
}
+32 -3
View File
@@ -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;
@@ -16,6 +17,7 @@
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Process\RequestHold;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
@@ -77,9 +79,15 @@ private function create(Property $property, StayRequest $stay, array $guestData,
$quote = $this->calculator->calculate($property, $stay);
[$guest, $differences] = $this->guestFor($guestData);
$profile = app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
$profile = $originChannel === null && $source === 'website'
? app(ProcessSettings::class)->forWebsite($property)
: app(ProcessSettings::class)->resolve($property, $originChannel, IntakeKind::Inquiry);
$draft = new Booking(['property_id' => $property->id, 'arrival' => $stay->arrival->toDateString(), 'departure' => $stay->departure->toDateString(), 'guests' => $stay->guests]);
$draft->setRelation('guest', $guest);
$hold = RequestHold::for($draft, $profile);
return $property->bookings()->create([
...$hold,
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
@@ -95,12 +103,21 @@ private function create(Property $property, StayRequest $stay, array $guestData,
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
'message' => $message,
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
]);
});
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);
}
@@ -174,8 +191,20 @@ private function sendMails(Booking $booking): void
$offerSent = false;
}
// v0.11: details for the offer are missing – the data request asks for them (and then replaces the receipt).
$asked = false;
if (! $offerSent) {
try {
$request = app(RequestCaseData::class)->forNextStep($booking);
$asked = $request?->last_sent_at !== null;
$booking->refresh();
} catch (Throwable $exception) {
Log::warning('Rückfrage fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
try {
if (! $offerSent && filled($booking->guest?->email)) {
if (! $offerSent && ! $asked && filled($booking->guest?->email)) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
}
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
+5
View File
@@ -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'));
+2 -1
View File
@@ -20,7 +20,8 @@ public function handle(): int
$expired = Booking::query()
->whereIn('status', BookingStatus::holding())
->where(fn ($query) => $query
->where('hold_expires_at', '<=', now())
// A lapsed clarification hold (v0.11) only frees the calendar; the request stays open for its details.
->where(fn ($offer) => $offer->where('hold_expires_at', '<=', now())->where('hold_purpose', Booking::HOLD_OFFER))
// An information without a hold (package 7) ends when its link expires and the guest did not ask for the booking.
->orWhere(fn ($information) => $information->where('status', BookingStatus::Reserved)->whereNull('hold_expires_at')
->where('information_valid_until', '<=', now())->whereNull('wish_at')))
+188
View File
@@ -0,0 +1,188 @@
<?php
namespace App\Actions;
use App\Communication\Extraction\AccessRejected;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\MessageExtractor;
use App\Communication\Extraction\RiskAssessment;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Enums\InboxMessageKind;
use App\Enums\TenantServiceKey;
use App\Filament\Pages\AiConnection;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\ServiceUsage;
use App\Process\CaseLog;
use App\Support\Inbox;
use App\Support\Settings;
/**
* The risk-based two-stage extraction of v0.11 (CH-14, E-035): the small model extracts facts with evidence and
* confidence, programmatic rules check phase, stored values, contradictions and plausibility, and – when the risk is
* high, something contradicts or a check fails – the review model looks at the original and the first extraction.
* Only facts that pass every check go to the common fact intake (which applies its own rules); everything else is
* proposed to the landlord in the inbox. Wishes to change the stay only become change requests. The extraction
* decides nothing binding; without the service, a key or a usable answer the message simply waits for the landlord.
*/
class ExtractMessageFacts
{
public function __construct(private MessageExtractor $extractor, private RiskAssessment $risk, private ContributeCaseFacts $facts) {}
/**
* @return string the extraction status: done, failed or disabled
*/
public function handle(InboundMessage $message): string
{
$booking = $message->booking()->with(['guest', 'property'])->first();
if ($booking === null || $message->extraction_status !== null) {
return (string) $message->extraction_status;
}
// Bring your own key: only the landlord's own, complete and not rejected access is used.
$access = AiAccess::for(Settings::tenant());
if ($access === null) {
$message->update(['extraction_status' => 'disabled']);
return 'disabled';
}
$record = ['prompt_version' => MessageExtractor::promptVersion()];
try {
$first = $this->extractor->extract($access, $message, $booking);
$this->meter();
$record['first'] = $first;
$data = $first['data'];
$checked = $this->risk->facts($booking, (string) $message->body, $data);
if ($this->risk->needsReview($booking, $checked, $data)) {
$review = $this->extractor->review($access, $message, $booking, $data);
$this->meter();
$record['review'] = $review;
$data = $review['data'];
$checked = $this->markDisagreements($this->risk->facts($booking, (string) $message->body, $data), $first['data']);
}
} catch (AccessRejected $exception) {
// The access is no longer valid: off for this landlord until he saves or checks it again (no retry loop).
AiAccess::markInvalid(Settings::tenant(), $exception->getMessage());
app(Inbox::class)->post(InboxMessageKind::AiAccessRejected, 'ai-access', 'KI-Anbindung abgelehnt', $exception->getMessage().' Die automatische Auswertung ist ausgeschaltet, bis Sie den Zugang unter System › KI-Anbindung prüfen. Nachrichten liegen im Posteingang.', actionUrl: AiConnection::getUrl());
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
return 'failed';
} catch (ExtractionFailed $exception) {
$message->update(['extraction_status' => 'failed', 'extraction' => [...$record, 'error' => $exception->getMessage()]]);
CaseLog::record($booking, 'mail_in', 'Automatische Auswertung nicht möglich – bitte die Nachricht selbst lesen', actor: CaseLog::SYSTEM);
return 'failed';
}
$automatic = array_values(array_filter($checked, fn (array $fact): bool => $this->risk->mayTakeOver($booking, $fact)));
$proposed = array_values(array_filter($checked, fn (array $fact): bool => ! in_array($fact, $automatic, true)));
$source = $message->status === InboundMessage::PORTAL ? FactSource::PortalMail : FactSource::Extraction;
if ($automatic !== []) {
$this->facts->handle($booking, collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['value']])->all(), $source, [
'inbound_message_id' => $message->id,
'reference' => 'message:'.$message->id,
'evidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['evidence']])->all(),
'confidence' => collect($automatic)->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['confidence']])->all(),
'actor' => 'Auswertung der E-Mail (KI, geprüft nach Regeln)',
]);
}
$changes = $this->changeRequests($booking, $message, $data['change_requests']);
$message->update([
'extraction_status' => 'done',
'extraction' => [...$record, 'intent' => $data['intent'], 'uncertainties' => $data['uncertainties'], 'applied' => $automatic, 'proposed' => $proposed, 'change_requests' => $changes],
]);
$this->finish($message, $automatic, $proposed, $changes, $data['intent']);
return 'done';
}
/**
* Facts the two models disagree on are proposed, never taken over.
*
* @param list<array<string, mixed>> $checked
* @param array{facts: list<array{field: string, value: string}>} $first
* @return list<array<string, mixed>>
*/
private function markDisagreements(array $checked, array $first): array
{
$firstValues = collect($first['facts'])->mapWithKeys(fn (array $fact): array => [$fact['field'] => mb_strtolower(trim($fact['value']))])->all();
return array_map(function (array $fact) use ($firstValues): array {
if (isset($firstValues[$fact['field']]) && $firstValues[$fact['field']] !== mb_strtolower($fact['value'])) {
$fact['problems'][] = 'die beiden Modelle lesen den Wert unterschiedlich';
}
return $fact;
}, $checked);
}
/**
* Wishes to change the stay become change requests through the fact intake (dates, guests) or a task; nothing about
* the booking changes (E-038).
*
* @param list<array{field: string, value: string, evidence: string}> $requests
* @return list<array{field: string, value: string, evidence: string}>
*/
private function changeRequests(Booking $booking, InboundMessage $message, array $requests): array
{
$kept = array_values(array_filter($requests, fn (array $request): bool => $this->risk->evidenceFound((string) $message->body, $request['evidence'])));
$stay = array_filter($kept, fn (array $request): bool => in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true));
if ($stay !== []) {
$this->facts->handle($booking, collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['value']])->all(), FactSource::Extraction, [
'inbound_message_id' => $message->id, 'reference' => 'message-change:'.$message->id, 'advance' => false,
'evidence' => collect($stay)->mapWithKeys(fn (array $request): array => [$request['field'] => $request['evidence']])->all(),
]);
}
foreach (array_filter($kept, fn (array $request): bool => ! in_array($request['field'], ContributeCaseFacts::STAY_FIELDS, true)) as $request) {
BookingTask::openOnce($booking, BookingTaskKind::ChangeRequest, 'message:'.$message->id.':'.$request['field'], [
'due_on' => today(),
'note' => 'Wunsch laut E-Mail ('.$request['field'].'): „'.mb_substr($request['evidence'], 0, 200).'“. Nichts wurde geändert.',
]);
}
return $kept;
}
/**
* @param list<array<string, mixed>> $automatic
* @param list<array<string, mixed>> $proposed
* @param list<array<string, mixed>> $changes
*/
private function finish(InboundMessage $message, array $automatic, array $proposed, array $changes, string $intent): void
{
$booking = $message->booking;
$task = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$message->id)->where('status', BookingTaskStatus::Open)->first();
$parts = array_filter([
$automatic !== [] ? count($automatic).' Angabe(n) übernommen' : null,
$proposed !== [] ? count($proposed).' Vorschlag/Vorschläge zu prüfen' : null,
$changes !== [] ? 'Änderungswunsch erkannt' : null,
]);
CaseLog::record($booking, 'mail_in', 'E-Mail ausgewertet: '.($parts === [] ? 'keine Angaben erkannt' : implode(', ', $parts)), actor: CaseLog::SYSTEM);
// Nothing left to look at: a pure answer whose details were all taken over.
if ($proposed === [] && $changes === [] && $automatic !== [] && $intent === 'answer') {
$task?->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => CaseLog::SYSTEM, 'note' => trim($task->note.' · automatisch ausgewertet')])->save();
$message->update(['status' => $message->status === InboundMessage::PORTAL ? InboundMessage::PORTAL : InboundMessage::PROCESSED, 'processed_at' => now()]);
return;
}
$task?->forceFill(['note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – '.(implode(', ', $parts) ?: 'keine Angaben erkannt').'. Im Posteingang ansehen.'])->save();
}
private function meter(): void
{
if (($tenant = Settings::tenant()) !== null) {
ServiceUsage::query()->create(['tenant_id' => $tenant->id, 'service' => TenantServiceKey::AiGuestMail->value, 'quantity' => 1, 'used_at' => now()]);
}
}
}
+7 -8
View File
@@ -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();
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Actions;
use App\Channels\Mail\PortalMail;
use App\Communication\MessageMatcher;
use App\Enums\BookingTaskKind;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\Mailbox;
use App\Process\CaseLog;
use App\Support\Settings;
use Illuminate\Database\UniqueConstraintViolationException;
/**
* The inbox of v0.11 (S2/S3, CH-01, CH-06, CH-08): every message of the landlord's dedicated mailbox is stored first,
* once per Message-ID. Booking notifications of the portals go unchanged through the existing portal path; every other
* message is assigned to a case by the deterministic rules or waits in the inbox for the landlord. A message never
* creates a case by itself. An assigned reply stops the reminders of the case's data request; its details are taken
* over only through the extraction and the common fact intake.
*/
class ReceiveInboundMessage
{
public function __construct(private ProcessPortalMail $portalMail, private MessageMatcher $matcher, private RequestCaseData $requests) {}
public function handle(PortalMail $mail, ?Mailbox $mailbox = null): InboundMessage
{
$existing = InboundMessage::query()->where('message_id', $mail->messageId)->first();
if ($existing !== null) {
return $existing;
}
try {
$message = InboundMessage::query()->create([
'mailbox_id' => $mailbox?->id,
'message_id' => $mail->messageId,
'in_reply_to' => $mail->inReplyTo,
'references' => $mail->references,
'from_address' => mb_strtolower($mail->from),
'from_name' => $mail->fromName,
'to_addresses' => $mail->to,
'subject' => mb_substr($mail->subject, 0, 500),
'body' => $mail->text,
'received_at' => $mail->receivedAt,
// CH §5 / M10: what arrives in test operation is marked as such.
'test_mode' => ! Settings::isLive(),
'status' => InboundMessage::NEW,
]);
} catch (UniqueConstraintViolationException) {
return InboundMessage::query()->where('message_id', $mail->messageId)->firstOrFail();
}
if ($this->portalMail->channelFor($mail->from) !== null) {
// A portal's notification: the existing portal path decides, unchanged (CH-08).
$record = $this->portalMail->handle($mail);
$record?->forceFill(['inbound_message_id' => $message->id])->save();
// CH-09/12: if the notification belongs to a case, the guest details it carries are evaluated for that case.
$bookingId = $record?->blockedPeriod()->value('linked_booking_id');
$message->update(['status' => InboundMessage::PORTAL, 'portal_email_id' => $record?->id, 'booking_id' => $bookingId, 'match_reason' => $bookingId ? 'portal_reference' : null, 'processed_at' => now()]);
return $message;
}
if ($this->isOwn($mail, $mailbox)) {
$message->update(['status' => InboundMessage::IGNORED, 'match_reason' => 'own', 'processed_at' => now()]);
return $message;
}
$match = $this->matcher->match($message);
if ($match['booking'] === null) {
$message->update(['status' => InboundMessage::NEEDS_REVIEW, 'hints' => $match['hints']]);
return $message;
}
$booking = $match['booking'];
$message->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => $match['reason']]);
CaseLog::record($booking, 'mail_in', 'E-Mail des Gastes eingegangen'.($message->test_mode ? ' (im Testbetrieb)' : '').': '.$message->subject, actor: CaseLog::GUEST, at: $message->received_at);
$this->requests->replyReceived($booking);
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$message->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $message->subject, 0, 120).'“ – im Posteingang ansehen; erkannte Angaben werden dort zur Übernahme vorgeschlagen.']);
return $message;
}
/**
* Our own mails (copies, loops) are not guest messages.
*/
private function isOwn(PortalMail $mail, ?Mailbox $mailbox): bool
{
$own = array_filter(array_map(fn (?string $address): string => mb_strtolower(trim((string) $address)), [
$mailbox?->address, config('mail.from.address'), Settings::tenant()?->sender_email,
]));
return in_array(mb_strtolower($mail->from), $own, true);
}
}
+343
View File
@@ -0,0 +1,343 @@
<?php
namespace App\Actions;
use App\Documents\DocumentReleases;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\DataRequestMode;
use App\Enums\DocumentKind;
use App\Enums\FactSource;
use App\Enums\IntakeKind;
use App\Mail\DataRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\DataRequest;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Process\FactContribution;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* The data request of v0.11 (S1, S4, CH-04, CH-15–CH-18): when the next step of a case lacks details, the guest is
* asked – automatically, prepared for the landlord's release, or by the landlord himself, as the case's settings say.
* At most one request runs per case. A partial answer leads to a targeted follow-up question, silence to reminders;
* both have their own limits and counters that are never reset. At the limit the landlord takes over.
*
* The request decides nothing about the case: answers go through the common fact intake, which asks the existing
* process to carry on. It never touches a hold or a deadline of the offer (CH-16/17, architecture test).
*/
class RequestCaseData
{
/** What the details are needed for. */
public const FOR_OFFER = 'offer';
public const FOR_WISH = 'wish_confirmation';
public const FOR_BOOKING = 'booking';
/**
* What the case needs next and which details are missing for it, or null when nothing is to be asked.
*
* @return array{purpose: string, fields: list<string>}|null
*/
public static function needs(Booking $booking): ?array
{
$booking->loadMissing('guest');
if (in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true) || $booking->isInternal()) {
return null;
}
if ($booking->isBinding()) {
// A binding booking (also from a portal, E-036) stays binding; only administrative guest details are asked for.
if ($booking->departure->isPast()) {
return null;
}
$fields = array_values(array_filter(CaseRequirements::missing($booking), fn (string $field): bool => str_starts_with($field, 'guest.')));
return $fields === [] ? null : ['purpose' => self::FOR_BOOKING, 'fields' => $fields];
}
if ($booking->intake === IntakeKind::Booking || $booking->status !== BookingStatus::Reserved || $booking->offer_version > 0) {
return null;
}
$purpose = match (true) {
$booking->process()->preReservation() => self::FOR_OFFER,
$booking->wish_at !== null => self::FOR_WISH,
default => null,
};
if ($purpose === null) {
return null;
}
$fields = CaseRequirements::missing($booking, $purpose === self::FOR_WISH ? CaseRequirements::WISH_CONFIRMATION : CaseRequirements::OFFER);
return $fields === [] ? null : ['purpose' => $purpose, 'fields' => $fields];
}
/**
* Starts the request for the next step if details are missing and none runs yet. Returns the running request.
*/
public function forNextStep(Booking $booking, ?DataRequestMode $mode = null): ?DataRequest
{
$needs = self::needs($booking);
// Without an e-mail address there is no way back to the guest: the case shows "enter the contact details".
if ($needs === null || ! CaseRequirements::isValid('guest.email', $booking->guest?->email)) {
return null;
}
$request = DB::transaction(function () use ($booking, $needs, $mode): DataRequest {
$booking->lockForTransition();
$running = $booking->openDataRequest();
if ($running !== null) {
return $running;
}
$mode ??= $booking->process()->dataRequestMode();
return $booking->dataRequests()->create([
'tenant_id' => $booking->tenant_id,
'status' => match (true) {
$mode === DataRequestMode::Manual => DataRequest::MANUAL,
$mode === DataRequestMode::Automatic && self::mayGoOutAutomatically() => DataRequest::OPEN,
default => DataRequest::DRAFT,
},
'mode' => $mode,
'purpose' => $needs['purpose'],
'fields' => $needs['fields'],
'last_message' => DataRequest::INITIAL,
]);
});
if ($request->wasRecentlyCreated) {
CaseLog::record($booking, 'data_request', match ($request->status) {
DataRequest::OPEN => 'Fehlende Angaben werden beim Gast angefragt',
DataRequest::DRAFT => 'Rückfrage nach fehlenden Angaben vorbereitet – wartet auf Ihre Freigabe',
default => 'Fehlende Angaben: bitte selbst beim Gast nachfragen (Textvorschlag im Vorgang)',
}, data: ['fields' => $request->fields], actor: CaseLog::SYSTEM);
if ($request->status === DataRequest::OPEN) {
$this->send($request, DataRequest::INITIAL);
}
}
return $request;
}
/**
* The landlord releases the prepared question (or asks now although the case is set to manual).
*/
public function approve(DataRequest $request): bool
{
if (! $request->isRunning()) {
return false;
}
if (! CaseRequirements::isValid('guest.email', $request->booking->guest?->email)) {
return false;
}
$kind = $request->last_message === DataRequest::FOLLOWUP ? DataRequest::FOLLOWUP : DataRequest::INITIAL;
$request->update(['status' => DataRequest::OPEN]);
return $this->send($request, $kind);
}
/**
* Sends the question, follow-up or reminder. A failing mail is shown in the case; the landlord takes over.
*/
public function send(DataRequest $request, string $kind): bool
{
$booking = $request->booking()->with(['guest', 'property'])->firstOrFail();
$profile = $booking->process();
$needs = self::needs($booking);
if ($needs === null) {
$this->close($request, DataRequest::COMPLETED, 'alle Angaben da');
return false;
}
$request->fields = $needs['fields'];
if ($kind === DataRequest::FOLLOWUP) {
$request->followups_sent++;
$request->link_version++;
}
if ($kind === DataRequest::REMINDER) {
$request->reminders_sent++;
}
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new DataRequested($booking, $request, $kind, $this->url($request, $booking)));
} catch (Throwable $exception) {
Log::warning('Rückfrage nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$request->forceFill(['status' => DataRequest::MANUAL])->save();
BookingTask::openOnce($booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => 'Die Rückfrage konnte nicht zugestellt werden – bitte die E-Mail-Adresse prüfen oder selbst nachfragen.']);
CaseLog::record($booking, 'data_request', 'Rückfrage konnte nicht zugestellt werden', actor: CaseLog::SYSTEM);
return false;
}
$request->forceFill([
'status' => DataRequest::OPEN,
'last_message' => $kind,
'last_sent_at' => now(),
'response_due_at' => now()->addHours($profile->reminderHours()),
'next_reminder_at' => now()->addHours($profile->reminderHours()),
])->save();
CaseLog::record($booking, 'data_request', match ($kind) {
DataRequest::FOLLOWUP => 'Gezielte Folgefrage an den Gast ('.$request->followups_sent.'.)',
DataRequest::REMINDER => 'Erinnerung an den Gast ('.$request->reminders_sent.'.)',
default => 'Rückfrage an den Gast gesendet',
}.': '.implode(', ', CaseRequirements::labels($request->fields)), actor: CaseLog::SYSTEM);
return true;
}
/**
* Details arrived (any source): the open reminder is cancelled; if everything is there the request ends, otherwise
* a targeted follow-up question follows within its limit (CH-15–17). The landlord's own entries never trigger a
* question to the guest.
*/
public function answered(Booking $booking, FactContribution $contribution, FactSource $source): void
{
$request = $booking->openDataRequest();
if ($request === null) {
return;
}
$needs = self::needs($booking->refresh());
if ($needs === null) {
$this->close($request, DataRequest::COMPLETED, 'alle Angaben da');
return;
}
if ($source->isAuthoritative() && $request->status === DataRequest::OPEN && $request->next_reminder_at === null && $request->followups_sent < $booking->process()->followupsMax()) {
// The landlord took over the guest's e-mail answer and something is still missing: a follow-up question is
// prepared for his release.
$request->forceFill(['status' => DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP, 'fields' => $needs['fields']])->save();
return;
}
if ($source->isAuthoritative() || $request->status !== DataRequest::OPEN || (! $contribution->anyApplied() && ! $contribution->needsReview())) {
$request->update(['fields' => $needs['fields']]);
return;
}
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null, 'fields' => $needs['fields']])->save();
if ($request->followups_sent >= $booking->process()->followupsMax()) {
$this->handOver($request, 'Antwort weiterhin unvollständig – die Grenze der Folgefragen ist erreicht.');
return;
}
if ($request->mode === DataRequestMode::Automatic && self::mayGoOutAutomatically()) {
$this->send($request, DataRequest::FOLLOWUP);
return;
}
$request->forceFill(['status' => $request->mode === DataRequestMode::Manual ? DataRequest::MANUAL : DataRequest::DRAFT, 'last_message' => DataRequest::FOLLOWUP])->save();
CaseLog::record($booking, 'data_request', 'Antwort unvollständig – Folgefrage vorbereitet: '.implode(', ', CaseRequirements::labels($needs['fields'])), actor: CaseLog::SYSTEM);
}
/**
* A reply of the guest arrived (assigned by the inbox): the open reminder is cancelled (CH-17). What it says is
* taken over only through the extraction and the fact intake.
*/
public function replyReceived(Booking $booking): void
{
$request = $booking->openDataRequest();
if ($request?->status !== DataRequest::OPEN) {
return;
}
$request->forceFill(['answered_at' => now(), 'next_reminder_at' => null])->save();
CaseLog::record($booking, 'data_request', 'Antwort des Gastes per E-Mail – Erinnerungen ruhen', actor: CaseLog::SYSTEM);
}
/**
* Due reminders of every running request (scheduler). At the limit the landlord takes over; nothing changes any
* deadline of the case.
*/
public function remindDue(): int
{
$count = 0;
$due = DataRequest::query()->where('status', DataRequest::OPEN)->whereNotNull('next_reminder_at')->where('next_reminder_at', '<=', now())->with('booking')->get();
foreach ($due as $request) {
$booking = $request->booking;
if ($booking === null || self::needs($booking) === null) {
$this->close($request, $booking === null ? DataRequest::STOPPED : DataRequest::COMPLETED, $booking === null ? 'Vorgang entfernt' : 'nichts mehr offen');
continue;
}
if ($request->reminders_sent >= $booking->process()->remindersMax()) {
$this->handOver($request, 'Der Gast hat auf die Rückfrage und '.$request->reminders_sent.' Erinnerung(en) nicht geantwortet.');
continue;
}
$count += $this->send($request, DataRequest::REMINDER) ? 1 : 0;
}
return $count;
}
/**
* Ends the request (all details there, the case ended, or the landlord stopped it).
*/
public function close(DataRequest $request, string $status, string $reason): void
{
if (! $request->isRunning()) {
return;
}
$request->forceFill(['status' => $status, 'closed_at' => now(), 'closed_reason' => $reason, 'next_reminder_at' => null])->save();
BookingTask::query()->where('booking_id', $request->booking_id)->where('kind', BookingTaskKind::GuestUnresponsive)->where('subject', 'r'.$request->id)->where('status', BookingTaskStatus::Open)
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'note' => trim($task->note.' · '.$reason)])->save());
if ($request->booking !== null) {
CaseLog::record($request->booking, 'data_request', 'Rückfrage beendet: '.$reason, actor: CaseLog::actor() ?? CaseLog::SYSTEM);
}
}
/**
* The guest's signed link to the form; it belongs to this request and its current version.
*/
public function url(DataRequest $request, ?Booking $booking = null): string
{
$booking ??= $request->booking;
$parameters = ['booking' => $booking, 'r' => $request->id, 'v' => $request->link_version];
$until = CarbonImmutable::now()->addDays($booking->process()->guestLinkValidDays());
return $booking->website()?->temporarySignedRoute('guest-data.show', $until, $parameters)
?? URL::temporarySignedRoute('guest-data.show', $until, $parameters);
}
/**
* Whether a question may go out without the landlord's click: its texts are released, or mails only reach the test
* recipient anyway (as for the automatic offer).
*/
public static function mayGoOutAutomatically(): bool
{
return DocumentReleases::isReleased(DocumentKind::DataRequest) || ! Settings::isLive();
}
private function handOver(DataRequest $request, string $note): void
{
$request->forceFill(['status' => DataRequest::MANUAL, 'next_reminder_at' => null])->save();
BookingTask::openOnce($request->booking, BookingTaskKind::GuestUnresponsive, 'r'.$request->id, ['due_on' => today(), 'note' => $note]);
CaseLog::record($request->booking, 'data_request', 'Rückfrage an Sie übergeben: '.$note, actor: CaseLog::SYSTEM);
}
}
+7
View File
@@ -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));
@@ -111,6 +117,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'hold_purpose' => Booking::HOLD_OFFER,
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? null,
+9
View File
@@ -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;
@@ -145,6 +146,11 @@ public function handle(Booking $booking, int $version, ?string $ip = null): stri
$this->notify($booking, $outcome);
// v0.11 (B3): the binding confirmation needs every detail – ask the guest for what is missing.
if ($outcome === self::PENDING) {
rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true);
}
return $outcome;
}
@@ -198,6 +204,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).';
}
+2
View File
@@ -97,6 +97,8 @@ public function handle(Property $property, Channel $channel, CarbonImmutable $ar
});
app(CaseAutomation::class)->advance($booking);
// v0.11 (E-036): the booking stays binding; only missing administrative details of a reachable guest are asked for.
rescue(fn () => app(RequestCaseData::class)->forNextStep($booking->fresh()), report: true);
return $booking->refresh();
}
+6 -1
View File
@@ -11,6 +11,7 @@
use App\Models\Channel;
use App\Process\CaseAutomation;
use App\Process\ProcessSettings;
use App\Process\RequestHold;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
@@ -41,8 +42,13 @@ public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutab
}
$profile = $this->settings->resolve($property, $channel, IntakeKind::Inquiry);
// v0.11 (B1): a portal request without the guest's details holds nothing until the details are there; the
// offer hold comes with the offer.
$draft = new Booking(['property_id' => $property->id, 'arrival' => $arrival->toDateString(), 'departure' => $departure->toDateString()]);
$draft->setRelation('guest', null);
return $property->bookings()->create([
...RequestHold::for($draft, $profile),
'status' => BookingStatus::Reserved,
'source' => 'portal',
'intake' => IntakeKind::Inquiry,
@@ -50,7 +56,6 @@ public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutab
'portal_reference' => $reference,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'hold_expires_at' => $profile->preReservation() ? now()->addHours($profile->holdHours()) : null,
'processing_mode' => $processingMode,
'internal_notes' => $notes,
]);
+48
View File
@@ -98,6 +98,48 @@ public function fetch(array $senders): array
return $mails;
}
/**
* Every message of the last days (v0.11 inbox, mailbox mode "full"), left unread. Deduplication happens when the
* messages are stored.
*
* @return list<PortalMail>
*
* @throws ChannelSyncException
*/
public function fetchAll(): array
{
$config = self::configuration();
if ($config === null) {
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
}
try {
$client = (new ClientManager)->make([
'host' => $config['host'], 'port' => $config['port'], 'encryption' => $config['encryption'], 'validate_cert' => true,
'username' => $config['username'], 'password' => $config['password'], 'protocol' => 'imap',
]);
$client->connect();
$messages = $client->getFolderByPath($config['folder'])->query()
->whereSince(CarbonImmutable::today()->subDays((int) config('fewo.mailbox.lookback_days', 3)))
->leaveUnread()
->get();
$mails = [];
foreach ($messages as $message) {
$mails[] = $this->toPortalMail($message);
}
$client->disconnect();
} catch (Throwable $exception) {
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
}
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
Cache::forget(self::key(self::LAST_ERROR_KEY));
return $mails;
}
private function toPortalMail(Message $message): PortalMail
{
$text = $message->getTextBody();
@@ -108,12 +150,18 @@ private function toPortalMail(Message $message): PortalMail
$from = $message->getFrom()->first();
$date = $message->getDate()->first();
$references = preg_split('/\s+/', trim((string) $message->getReferences()?->first())) ?: [];
return new PortalMail(
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
from: (string) ($from->mail ?? ''),
subject: (string) $message->getSubject()->first(),
text: $text,
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
inReplyTo: ($reply = trim((string) $message->getInReplyTo()?->first())) !== '' ? $reply : null,
references: array_values(array_filter($references)),
to: collect($message->getTo()?->all() ?? [])->map(fn ($address): string => mb_strtolower((string) ($address->mail ?? '')))->filter()->values()->all(),
fromName: filled($from->personal ?? null) ? (string) $from->personal : null,
);
}
}
+10 -1
View File
@@ -5,15 +5,24 @@
use Carbon\CarbonImmutable;
/**
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook. The reply references, recipients and the
* sender's name are only filled when the whole mailbox is read (v0.11 inbox).
*/
final readonly class PortalMail
{
/**
* @param list<string> $references
* @param list<string> $to
*/
public function __construct(
public string $messageId,
public string $from,
public string $subject,
public string $text,
public CarbonImmutable $receivedAt,
public ?string $inReplyTo = null,
public array $references = [],
public array $to = [],
public ?string $fromName = null,
) {}
}
@@ -0,0 +1,9 @@
<?php
namespace App\Communication\Extraction;
/**
* The provider rejected the landlord's access (invalid key, no credit, no permission). The message never contains the
* key.
*/
class AccessRejected extends ExtractionFailed {}
+78
View File
@@ -0,0 +1,78 @@
<?php
namespace App\Communication\Extraction;
use App\Enums\TenantServiceKey;
use App\Models\Tenant;
use App\Models\TenantService;
use App\Tenancy\TenantFeatures;
/**
* A landlord's own AI access (bring your own key): provider, key and the two models of the extraction. There is no
* central operator key and no built-in model – without a complete access, or after the provider rejected the key,
* the extraction is off and messages go to the landlord.
*/
final class AiAccess
{
public const OK = 'ok';
public const INVALID = 'invalid';
public function __construct(
public readonly AiProvider $provider,
#[\SensitiveParameter] public readonly string $key,
public readonly string $smallModel,
public readonly string $reviewModel,
) {}
/**
* The usable access of a landlord, or null (service off, incomplete, or rejected by the provider).
*/
public static function for(?Tenant $tenant): ?self
{
if ($tenant === null || ! app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail, $tenant)) {
return null;
}
$service = self::service($tenant);
if ($service === null || $service->check_status === self::INVALID) {
return null;
}
return self::fromService($service);
}
/**
* The access as configured, regardless of the last check (for the check itself).
*/
public static function fromService(TenantService $service): ?self
{
$settings = (array) $service->settings;
$provider = AiProvider::tryFrom((string) ($settings['provider'] ?? ''));
$small = trim((string) ($settings['small_model'] ?? ''));
$review = trim((string) ($settings['review_model'] ?? ''));
if ($provider === null || blank($service->api_key) || $small === '' || $review === '') {
return null;
}
return new self($provider, (string) $service->api_key, $small, $review);
}
public static function service(Tenant $tenant): ?TenantService
{
return TenantService::query()->where('tenant_id', $tenant->id)->where('service', TenantServiceKey::AiGuestMail->value)->first();
}
/**
* The provider rejected the key: the extraction stays off until the landlord saves or checks the access again.
*/
public static function markInvalid(Tenant $tenant, string $message): void
{
self::service($tenant)?->forceFill(['check_status' => self::INVALID, 'check_message' => mb_substr($message, 0, 500), 'checked_at' => now()])->save();
}
public function __debugInfo(): array
{
return ['provider' => $this->provider->value, 'key' => '***', 'smallModel' => $this->smallModel, 'reviewModel' => $this->reviewModel];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Communication\Extraction;
use Filament\Support\Contracts\HasLabel;
/**
* The AI providers a landlord may connect (bring your own key, v0.11). Endpoints are fixed here – no configuration,
* form or environment value can point the extraction at another host.
*/
enum AiProvider: string implements HasLabel
{
case Anthropic = 'anthropic';
case OpenRouter = 'openrouter';
public function getLabel(): string
{
return match ($this) {
self::Anthropic => 'Anthropic (Claude API)',
self::OpenRouter => 'OpenRouter',
};
}
public function endpoint(): string
{
return match ($this) {
self::Anthropic => 'https://api.anthropic.com/v1/messages',
self::OpenRouter => 'https://openrouter.ai/api/v1/chat/completions',
};
}
/**
* Examples for the form – suggestions only, nothing is preset.
*/
public function modelExamples(): string
{
return match ($this) {
self::Anthropic => 'z. B. klein „claude-haiku-5-5“, groß „claude-opus-5-5“',
self::OpenRouter => 'z. B. klein „anthropic/claude-haiku-5-5“, groß „anthropic/claude-opus-5-5“ (Kennung wie bei OpenRouter angezeigt)',
};
}
}
@@ -0,0 +1,11 @@
<?php
namespace App\Communication\Extraction;
use RuntimeException;
/**
* The extraction could not produce a usable result (no key, timeout, refusal, invalid output). The message then
* waits for the landlord – the safe fallback of CH-14.
*/
class ExtractionFailed extends RuntimeException {}
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace App\Communication\Extraction;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Http\Client\Response;
use Illuminate\Support\Facades\Http;
use Throwable;
/**
* The model connection of the extraction with the landlord's own access (bring your own key, v0.11): Anthropic's
* Messages API or OpenRouter's chat completions, both over HTTP to the provider's fixed endpoint (AiProvider), no SDK
* dependency. One call: system prompt, the message, and a JSON schema the answer must follow (structured outputs).
* The key travels only in the request header; it is never part of an exception, a log line or a stored result.
*/
class LlmClient
{
/** Server-side refusal fallback on Anthropic (opt-in default for the Claude Opus family). */
private const ANTHROPIC_FALLBACK_BETA = 'server-side-fallback-2026-07-01';
/**
* @param array<string, mixed> $schema
* @return array{data: array<string, mixed>, model: string, usage: array<string, mixed>}
*
* @throws AccessRejected when the provider rejects the access
* @throws ExtractionFailed for every other unusable outcome
*/
public function structured(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort = 'medium'): array
{
[$headers, $body] = match ($access->provider) {
AiProvider::Anthropic => $this->anthropic($access, $model, $system, $message, $schema, $effort),
AiProvider::OpenRouter => $this->openRouter($access, $model, $system, $message, $schema),
};
try {
$response = Http::withHeaders($headers)
->timeout((int) config('fewo.ai.timeout', 40))
// Only passing problems are repeated; a rejected key or a bad request is not.
->retry(2, 2000, fn (Throwable $exception): bool => $exception instanceof ConnectionException || ($exception instanceof RequestException && in_array($exception->response->status(), [429, 500, 502, 503, 529], true)), throw: false)
->post($access->provider->endpoint(), $body);
} catch (ConnectionException) {
throw new ExtractionFailed('Keine Verbindung zu '.$access->provider->getLabel().'.');
}
if (in_array($response->status(), [401, 402, 403], true)) {
throw new AccessRejected($access->provider->getLabel().' lehnt den Zugang ab ('.$response->status().': '.$this->providerMessage($response, $access).').');
}
if (! $response->successful()) {
throw new ExtractionFailed($access->provider->getLabel().' antwortet mit '.$response->status().' ('.$this->providerMessage($response, $access).').');
}
$payload = (array) $response->json();
$text = $access->provider === AiProvider::Anthropic ? $this->anthropicText($payload) : $this->openRouterText($payload);
$data = json_decode($text, true);
if (! is_array($data)) {
throw new ExtractionFailed('Die Antwort ist kein gültiges JSON.');
}
return ['data' => $data, 'model' => (string) ($payload['model'] ?? $model), 'usage' => (array) ($payload['usage'] ?? [])];
}
/**
* @param array<string, mixed> $schema
* @return array{0: array<string, string>, 1: array<string, mixed>}
*/
private function anthropic(AiAccess $access, string $model, string $system, string $message, array $schema, string $effort): array
{
$headers = ['x-api-key' => $access->key, 'anthropic-version' => (string) config('fewo.ai.anthropic_version'), 'content-type' => 'application/json'];
$body = [
'model' => $model,
'max_tokens' => 4096,
'system' => $system,
'messages' => [['role' => 'user', 'content' => $message]],
'output_config' => ['effort' => $effort, 'format' => ['type' => 'json_schema', 'schema' => $schema]],
];
if (str_starts_with($model, 'claude-opus-')) {
$body['fallbacks'] = 'default';
$headers['anthropic-beta'] = self::ANTHROPIC_FALLBACK_BETA;
}
return [$headers, $body];
}
/**
* @param array<string, mixed> $schema
* @return array{0: array<string, string>, 1: array<string, mixed>}
*/
private function openRouter(AiAccess $access, string $model, string $system, string $message, array $schema): array
{
return [
['Authorization' => 'Bearer '.$access->key, 'content-type' => 'application/json', 'HTTP-Referer' => (string) config('app.url'), 'X-OpenRouter-Title' => 'FewoPortal'],
[
'model' => $model,
'max_tokens' => 4096,
'messages' => [['role' => 'system', 'content' => $system], ['role' => 'user', 'content' => $message]],
'response_format' => ['type' => 'json_schema', 'json_schema' => ['name' => 'extraction', 'strict' => true, 'schema' => $schema]],
// Only providers that honour the schema; otherwise it would merely be a hint.
'provider' => ['require_parameters' => true],
],
];
}
/**
* @param array<string, mixed> $payload
*/
private function anthropicText(array $payload): string
{
match ($payload['stop_reason'] ?? null) {
'refusal' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
'max_tokens' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
default => null,
};
return collect((array) ($payload['content'] ?? []))->where('type', 'text')->pluck('text')->implode('');
}
/**
* @param array<string, mixed> $payload
*/
private function openRouterText(array $payload): string
{
$choice = (array) ($payload['choices'][0] ?? []);
match ($choice['finish_reason'] ?? null) {
'content_filter' => throw new ExtractionFailed('Der Anbieter hat die Auswertung abgelehnt.'),
'length' => throw new ExtractionFailed('Die Antwort ist unvollständig.'),
'error' => throw new ExtractionFailed('Der Anbieter meldet einen Fehler.'),
default => null,
};
return (string) ($choice['message']['content'] ?? '');
}
/**
* The provider's own short message, cut and without anything that looks like a key.
*/
private function providerMessage(Response $response, AiAccess $access): string
{
$message = str_replace($access->key, '***', (string) ($response->json('error.message') ?? $response->json('error.type') ?? ''));
return mb_substr((string) preg_replace('/(sk-[A-Za-z0-9_\-]{6})[A-Za-z0-9_\-]+/', '$1…', $message), 0, 200) ?: 'ohne Angabe';
}
}
@@ -0,0 +1,162 @@
<?php
namespace App\Communication\Extraction;
use App\Models\Booking;
use App\Models\InboundMessage;
use App\Process\CaseRequirements;
/**
* The model side of the extraction (v0.11, CH-14): versioned prompts with defined placeholders, a JSON schema for the
* answer and its validation here (the answer is checked, not trusted). The small model extracts; the review model
* sees the original and the first extraction – both as configured in the landlord's own access. Both only return
* candidates – nothing is stored or changed here.
*/
class MessageExtractor
{
public function __construct(private LlmClient $client) {}
/**
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
*
* @throws ExtractionFailed
*/
public function extract(AiAccess $access, InboundMessage $message, Booking $booking): array
{
return $this->call($access, $access->smallModel, $this->prompt('', $booking), $this->messageText($message), 'medium');
}
/**
* @param array<string, mixed> $first
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
*
* @throws ExtractionFailed
*/
public function review(AiAccess $access, InboundMessage $message, Booking $booking, array $first): array
{
return $this->call($access, $access->reviewModel, $this->prompt('-review', $booking, ['first_extraction' => json_encode($first, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)]), $this->messageText($message), 'high');
}
public static function promptVersion(): string
{
return (string) config('fewo.ai.prompt_version', 'v1');
}
/**
* The prompt of the configured version with every placeholder filled; an unknown placeholder is an error.
*
* @param array<string, string> $extra
*/
public function prompt(string $variant, Booking $booking, array $extra = []): string
{
$path = resource_path('prompts/extraction/'.self::promptVersion().$variant.'.md');
if (! is_file($path)) {
throw new ExtractionFailed('Prompt '.self::promptVersion().$variant.' fehlt.');
}
$values = [
'phase' => match (true) {
$booking->isBinding() => 'binding booking (contract exists; changes are only wishes)',
$booking->offer_version > 0 => 'binding offer sent, not yet accepted',
default => 'non-binding request',
},
'requested_fields' => implode(', ', $booking->openDataRequest()?->fields ?? CaseRequirements::missing($booking)) ?: 'none',
'known_fields' => $this->knownFields($booking),
'today' => now()->toDateString(),
...$extra,
];
$prompt = preg_replace_callback('/\{\{\s*(\w+)\s*\}\}/', function (array $match) use ($values): string {
if (! array_key_exists($match[1], $values)) {
throw new ExtractionFailed('Unbekannter Platzhalter {{'.$match[1].'}}.');
}
return $values[$match[1]];
}, (string) file_get_contents($path));
return (string) $prompt;
}
/**
* @return array<string, mixed>
*/
public static function schema(): array
{
return (array) json_decode((string) file_get_contents(resource_path('prompts/extraction/schema.json')), true);
}
/**
* @return array{data: array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>}, model: string}
*/
private function call(AiAccess $access, string $model, string $system, string $text, string $effort): array
{
$schema = self::schema();
$lastError = null;
// One repetition when the answer does not fit the schema, then the message goes to the landlord.
for ($attempt = 1; $attempt <= 2; $attempt++) {
$result = $this->client->structured($access, $model, $system, $text, $schema, $effort);
$lastError = $this->violation($result['data'], $schema);
if ($lastError === null) {
return ['data' => $result['data'], 'model' => $result['model']];
}
}
throw new ExtractionFailed('Antwort passt nicht zum Schema: '.$lastError);
}
/**
* The first deviation of the answer from the schema, or null.
*
* @param array<string, mixed> $data
* @param array<string, mixed> $schema
*/
private function violation(array $data, array $schema): ?string
{
foreach ($schema['required'] as $key) {
if (! array_key_exists($key, $data)) {
return 'Feld '.$key.' fehlt';
}
}
if (! is_array($data['facts']) || ! is_array($data['change_requests']) || ! is_array($data['uncertainties']) || ! is_string($data['intent'])) {
return 'falsche Typen';
}
if (! in_array($data['intent'], $schema['properties']['intent']['enum'], true)) {
return 'unbekannte Absicht';
}
foreach (['facts', 'change_requests'] as $list) {
$item = $schema['properties'][$list]['items'];
foreach ($data[$list] as $entry) {
if (! is_array($entry) || array_diff($item['required'], array_keys($entry)) !== [] || ! in_array($entry['field'], $item['properties']['field']['enum'], true)) {
return 'ungültiger Eintrag in '.$list;
}
if (! is_string($entry['value']) || ! is_string($entry['evidence']) || ($list === 'facts' && ! is_numeric($entry['confidence']))) {
return 'falscher Typ in '.$list;
}
}
}
return null;
}
private function messageText(InboundMessage $message): string
{
return 'Subject: '.$message->subject."\n\n".mb_substr((string) $message->body, 0, 20000);
}
/**
* Values on file, masked: enough to see whether something differs, not to learn the data.
*/
private function knownFields(Booking $booking): string
{
$known = [];
foreach ([...array_keys(CaseRequirements::FIELDS), ...array_keys(CaseRequirements::OPTIONAL_FIELDS)] as $field) {
$value = (string) CaseRequirements::value($booking, $field);
if ($value === '') {
continue;
}
$known[] = $field.'='.(str_starts_with($field, 'booking.') ? $value : mb_substr($value, 0, 1).str_repeat('*', max(1, mb_strlen($value) - 2)).mb_substr($value, -1));
}
return $known === [] ? 'none' : implode('; ', $known);
}
}
@@ -0,0 +1,155 @@
<?php
namespace App\Communication\Extraction;
use App\Actions\ContributeCaseFacts;
use App\Models\Booking;
use App\Process\CaseRequirements;
use Carbon\CarbonImmutable;
/**
* The programmatic risk check of an extraction (v0.11, CH-14). The model's confidence is no calibrated probability:
* it may trigger a review, never waive one. Criticality comes from the field, the phase and the kind of deviation;
* contradictions and failed plausibility checks call for the review model regardless of the confidence, and are never
* taken over automatically. Thresholds are configured and calibrated with test messages (go-live condition).
*/
class RiskAssessment
{
/** Details whose automatic completion is harmless in every phase. */
private const ADMINISTRATIVE = ['guest.phone', 'booking.arrival_time'];
/**
* Checks every fact and marks why it may not be taken over automatically.
*
* @param array{facts: list<array{field: string, value: string, evidence: string, confidence: float|int}>, change_requests: list<array{field: string, value: string, evidence: string}>, intent: string, uncertainties: list<string>} $extraction
* @return list<array{field: string, value: string, evidence: string, confidence: float, criticality: float, problems: list<string>}>
*/
public function facts(Booking $booking, string $message, array $extraction): array
{
$checked = [];
$values = [];
foreach ($extraction['facts'] as $fact) {
$values[$fact['field']][] = mb_strtolower(trim($fact['value']));
}
foreach ($extraction['facts'] as $fact) {
$field = $fact['field'];
$value = trim($fact['value']);
$problems = [];
if (! CaseRequirements::isValid($field, $value)) {
$problems[] = 'Wert ungültig';
}
if (! $this->evidenceFound($message, $fact['evidence'])) {
$problems[] = 'Belegstelle nicht in der Nachricht';
}
if (count(array_unique($values[$field] ?? [])) > 1) {
$problems[] = 'widersprüchliche Angaben in derselben Nachricht';
}
$current = CaseRequirements::value($booking, $field);
if (CaseRequirements::isValid($field, $current) && mb_strtolower(trim((string) $current)) !== mb_strtolower($value)) {
$problems[] = 'weicht vom gespeicherten Wert ab';
}
$problems = [...$problems, ...$this->plausibility($booking, $field, $value)];
$checked[] = [
'field' => $field,
'value' => $value,
'evidence' => $fact['evidence'],
'confidence' => max(0.0, min(1.0, (float) $fact['confidence'])),
'criticality' => $this->criticality($booking, $field),
'problems' => $problems,
];
}
return $checked;
}
/**
* Whether the review model has to look at the extraction: any contradiction or failed check, any wish to change
* something in a binding phase, an uncertainty the model reported, or criticality × (1 − confidence) above the
* configured threshold.
*
* @param list<array{criticality: float, confidence: float, problems: list<string>}> $facts
* @param array{change_requests: list<mixed>, uncertainties: list<string>} $extraction
*/
public function needsReview(Booking $booking, array $facts, array $extraction): bool
{
if ($extraction['uncertainties'] !== [] || ($extraction['change_requests'] !== [] && $booking->offer_version > 0)) {
return true;
}
$threshold = (float) config('fewo.ai.escalate_above', 0.2);
foreach ($facts as $fact) {
if ($fact['problems'] !== [] || $threshold < $fact['criticality'] * (1 - $fact['confidence'])) {
return true;
}
}
return false;
}
/**
* Whether a checked fact may go to the fact intake automatically: no problem, confident enough, the detail not
* known yet, and no stay detail (those are change requests). The intake applies its own rules on top.
*
* @param array{field: string, confidence: float, problems: list<string>} $fact
*/
public function mayTakeOver(Booking $booking, array $fact): bool
{
return $fact['problems'] === []
&& $fact['confidence'] >= (float) config('fewo.ai.min_confidence', 0.85)
&& ! in_array($fact['field'], ContributeCaseFacts::STAY_FIELDS, true)
&& ! CaseRequirements::isValid($fact['field'], CaseRequirements::value($booking, $fact['field']))
&& (in_array($fact['field'], self::ADMINISTRATIVE, true) || str_starts_with($fact['field'], 'guest.'));
}
public function evidenceFound(string $message, string $evidence): bool
{
$normalise = fn (string $text): string => mb_strtolower(trim((string) preg_replace('/\s+/u', ' ', $text)));
$evidence = $normalise($evidence);
return $evidence !== '' && str_contains($normalise($message), $evidence);
}
private function criticality(Booking $booking, string $field): float
{
return match (true) {
in_array($field, self::ADMINISTRATIVE, true) => 0.3,
in_array($field, ContributeCaseFacts::STAY_FIELDS, true), $field === 'guest.email' => 1.0,
ContributeCaseFacts::isBinding($booking) => 0.8,
default => 0.6,
};
}
/**
* @return list<string>
*/
private function plausibility(Booking $booking, string $field, string $value): array
{
return match ($field) {
'booking.guests' => (int) $value > (int) $booking->property?->max_guests ? ['mehr Personen als die Wohnung fasst'] : [],
'booking.arrival', 'booking.departure' => $this->dateProblems($booking, $field, $value),
default => [],
};
}
/**
* @return list<string>
*/
private function dateProblems(Booking $booking, string $field, string $value): array
{
$date = rescue(fn () => CarbonImmutable::parse($value), null, false);
if ($date === null) {
return ['Datum nicht lesbar'];
}
if ($date->isBefore(CarbonImmutable::today())) {
return ['Datum liegt in der Vergangenheit'];
}
if ($field === 'booking.departure' && $booking->arrival !== null && ! $date->isAfter($booking->arrival)) {
return ['Abreise nicht nach der Anreise'];
}
return [];
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Communication;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\BookingMessage;
use App\Models\InboundMessage;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* Deterministic assignment of an incoming message to a case (v0.11, CH-07, CH-13) – no scoring. A message is
* assigned only by
*
* 1. a known reply reference (In-Reply-To / References of one of our mails),
* 2. our case number together with the case's guest as sender (the number alone is no proof of identity), or
* 3. the combination of sender (the guest's e-mail), property and both dates of exactly one open case of that guest.
*
* One open case of the same sender alone is not enough; it is only shown as a hint. Everything else waits in the inbox
* for the landlord. Being assigned does not yet allow taking anything over.
*/
class MessageMatcher
{
/**
* @return array{booking: ?Booking, reason: ?string, hints: list<array{booking_id: int, reference: string, why: string}>}
*/
public function match(InboundMessage $message): array
{
$sender = mb_strtolower(trim((string) $message->from_address));
$text = $message->subject."\n".$message->body;
$references = array_values(array_filter([$message->in_reply_to, ...((array) $message->references)]));
if ($references !== []) {
$replied = BookingMessage::query()->whereIn('message_id', $references)->whereNotNull('booking_id')->latest('id')->first()?->booking;
if ($replied !== null) {
return ['booking' => $replied, 'reason' => 'reply', 'hints' => []];
}
}
$hints = [];
if (preg_match_all('/\b(20\d{2}-\d{4})\b/', $text, $numbers)) {
foreach (Booking::query()->whereIn('reference', array_unique($numbers[1]))->with('guest')->get() as $booking) {
if ($sender !== '' && mb_strtolower((string) $booking->guest?->email) === $sender) {
return ['booking' => $booking, 'reason' => 'reference_and_sender', 'hints' => []];
}
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'Vorgangsnummer genannt, aber anderer Absender'];
}
}
if ($sender === '') {
return ['booking' => null, 'reason' => null, 'hints' => $hints];
}
$open = Booking::query()
->whereHas('guest', fn ($guest) => $guest->where('email', $sender))
->whereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed])
->whereDate('departure', '>=', CarbonImmutable::today())
->with('property')
->get();
$dates = $this->dates($text);
$singleProperty = Property::query()->count() === 1;
$candidates = $open->filter(fn (Booking $booking): bool => in_array($booking->arrival->toDateString(), $dates, true)
&& in_array($booking->departure->toDateString(), $dates, true)
&& ($singleProperty || mb_stripos($text, (string) $booking->property?->name) !== false));
if ($candidates->count() === 1) {
return ['booking' => $candidates->first(), 'reason' => 'sender_property_dates', 'hints' => []];
}
foreach ($open as $booking) {
$hints[] = ['booking_id' => $booking->id, 'reference' => $booking->reference, 'why' => 'offener Vorgang dieses Absenders ('.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y').')'];
}
return ['booking' => null, 'reason' => null, 'hints' => array_values(array_unique($hints, SORT_REGULAR))];
}
/**
* Dates written in the message (d.m.yyyy, d.m.yy, yyyy-mm-dd).
*
* @return list<string> Y-m-d
*/
public function dates(string $text): array
{
$dates = [];
if (preg_match_all('/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{4}|\d{2})\b/', $text, $german, PREG_SET_ORDER)) {
foreach ($german as [, $day, $month, $year]) {
$year = strlen($year) === 2 ? '20'.$year : $year;
if (checkdate((int) $month, (int) $day, (int) $year)) {
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
}
if (preg_match_all('/\b(20\d{2})-(\d{2})-(\d{2})\b/', $text, $iso, PREG_SET_ORDER)) {
foreach ($iso as [, $year, $month, $day]) {
if (checkdate((int) $month, (int) $day, (int) $year)) {
$dates[] = sprintf('%04d-%02d-%02d', $year, $month, $day);
}
}
}
return array_values(array_unique($dates));
}
}
@@ -39,7 +39,7 @@ public function handle(TenantRunner $runner, PortalIntake $intake): int
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
$succeeded = $runner->each(function (Tenant $tenant) use ($intake, $apply, &$report): void {
$channels = Channel::query()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
$channels = Channel::query()->portals()->when($this->option('channel'), fn ($query, $ids) => $query->whereKey($ids))->orderBy('id')->get();
foreach ($channels as $channel) {
$entries = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
->where('is_representation', false)->whereDate('ends_on', '>', today())->orderBy('starts_on')->get();
@@ -0,0 +1,78 @@
<?php
namespace App\Console\Commands;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\MessageExtractor;
use App\Models\Booking;
use App\Models\InboundMessage;
use App\Models\Property;
use App\Models\Tenant;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
/**
* Measures the extraction on a set of anonymised sample messages (v0.11, M05): wrong values and missed details are
* counted separately – no system guarantees that it finds every detail, so the rate of missed ones is reported, not
* hidden. Calls the configured models (costs money); meant for calibrating prompts and thresholds before go-live.
*/
#[Signature('ai:evaluate {tenant : ID of the landlord whose own AI access is used} {--path= : JSON file with samples}')]
#[Description('Evaluate the guest message extraction against sample messages (wrong values and missed details)')]
class EvaluateExtraction extends Command
{
public function handle(MessageExtractor $extractor): int
{
$path = (string) ($this->option('path') ?: resource_path('prompts/extraction/evaluation/samples.json'));
// Bring your own key: the landlord's own access, as configured (System › KI-Anbindung).
$tenant = Tenant::query()->find((int) $this->argument('tenant'));
$service = $tenant === null ? null : AiAccess::service($tenant);
$access = $service === null ? null : AiAccess::fromService($service);
if ($access === null) {
$this->error('Für diesen Mandanten ist keine vollständige KI-Anbindung gespeichert.');
return self::FAILURE;
}
$samples = (array) json_decode((string) file_get_contents($path), true);
$property = Property::query()->withoutGlobalScopes()->first() ?? new Property(['name' => 'Ferienwohnung', 'max_guests' => 4]);
$totals = ['expected' => 0, 'found' => 0, 'missed' => 0, 'wrong' => 0, 'extra' => 0, 'changes_missed' => 0, 'failed' => 0];
foreach ($samples as $sample) {
$booking = new Booking(['arrival' => now()->addDays(14)->toDateString(), 'departure' => now()->addDays(17)->toDateString(), 'guests' => 2, 'status' => 'reserved']);
$booking->setRelation('property', $property);
$booking->setRelation('guest', null);
$message = new InboundMessage(['subject' => $sample['subject'], 'body' => $sample['body']]);
try {
$result = $extractor->extract($access, $message, $booking)['data'];
} catch (ExtractionFailed $exception) {
$totals['failed']++;
$this->warn("{$sample['id']}: {$exception->getMessage()}");
continue;
}
$found = collect($result['facts'])->mapWithKeys(fn (array $fact): array => [$fact['field'] => mb_strtolower(trim($fact['value']))])->all();
foreach ($sample['expected'] as $field => $value) {
$totals['expected']++;
match (true) {
! isset($found[$field]) => $totals['missed']++,
$found[$field] !== mb_strtolower($value) => $totals['wrong']++,
default => $totals['found']++,
};
}
$totals['extra'] += count(array_diff_key($found, $sample['expected']));
$changes = collect($result['change_requests'])->pluck('field')->all();
$totals['changes_missed'] += count(array_diff($sample['expected_changes'], $changes));
$this->line("{$sample['id']}: ".json_encode(['found' => $found, 'changes' => $changes], JSON_UNESCAPED_UNICODE));
}
$this->table(array_keys($totals), [array_values($totals)]);
$rate = $totals['expected'] > 0 ? round(100 * $totals['missed'] / $totals['expected'], 1) : 0;
$this->info("Übersehene Angaben: {$rate} % · Prompt-Version ".MessageExtractor::promptVersion());
return self::SUCCESS;
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Actions\ExtractMessageFacts;
use App\Models\InboundMessage;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
#[Signature('messages:extract')]
#[Description('Evaluate assigned guest and portal messages (v0.11 extraction) – a limited number per landlord and run')]
class ExtractInboundMessages extends Command
{
public function handle(ExtractMessageFacts $extract, TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant) use ($extract): void {
$messages = InboundMessage::query()
->whereNotNull('booking_id')
->whereNull('extraction_status')
->whereIn('status', [InboundMessage::ASSIGNED, InboundMessage::PORTAL])
->orderBy('received_at')
->limit((int) config('fewo.ai.per_run', 10))
->get();
foreach ($messages as $message) {
try {
$this->line("{$tenant->name}: {$message->subject} → {$extract->handle($message)}");
} catch (Throwable $exception) {
report($exception);
$message->update(['extraction_status' => 'failed']);
}
}
});
return self::SUCCESS;
}
}
+22
View File
@@ -3,6 +3,7 @@
namespace App\Console\Commands;
use App\Actions\ProcessPortalMail;
use App\Actions\ReceiveInboundMessage;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Enums\TenantServiceKey;
@@ -41,6 +42,27 @@ private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMai
return;
}
// v0.11: a dedicated mailbox is read completely; portal notifications still go through the portal path.
$mailbox = $tenant->activeMailbox();
if ($mailbox?->readsEverything()) {
try {
$mails = $reader->fetchAll();
} catch (ChannelSyncException $exception) {
$this->error("{$tenant->name}: {$exception->getMessage()}");
return;
}
foreach ($mails as $mail) {
$message = app(ReceiveInboundMessage::class)->handle($mail, $mailbox);
if ($message->wasRecentlyCreated) {
$this->info("{$tenant->name}: {$message->statusLabel()} ({$message->subject})");
}
}
$mailbox->forceFill(['last_fetched_at' => now()])->save();
return;
}
$senders = Channel::query()->active()->get()
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
->unique()
@@ -0,0 +1,26 @@
<?php
namespace App\Console\Commands;
use App\Actions\RequestCaseData;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('cases:data-requests')]
#[Description('Send due reminders of data requests and hand silent ones over to the landlord – once per landlord (v0.11)')]
class ProcessDataRequests extends Command
{
public function handle(RequestCaseData $requests, TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant) use ($requests): void {
$count = $requests->remindDue();
$this->info("{$tenant->name}: {$count} Erinnerung(en) gesendet.");
});
return self::SUCCESS;
}
}
+6
View File
@@ -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.');
}
+2
View File
@@ -7,6 +7,7 @@
use App\Filament\Pages\PricesAndOffers;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Channels\ChannelResource;
use App\Filament\Resources\Guests\GuestResource;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
@@ -32,6 +33,7 @@ enum AdminMode: string implements HasDescription, HasLabel
GuestResource::class,
BlockedPeriodResource::class,
PricesAndOffers::class,
ChannelResource::class,
];
public function getLabel(): string
+8
View File
@@ -31,6 +31,10 @@ 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';
case GuestUnresponsive = 'guest_unresponsive';
case InboundReview = 'inbound_review';
public function getLabel(): string
{
@@ -51,6 +55,10 @@ 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',
self::GuestUnresponsive => 'Fehlende Angaben selbst beim Gast nachfragen',
self::InboundReview => 'Antwort des Gastes prüfen',
};
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How missing details are requested from the guest (v0.11, CH §1.6) – independent of whether offers go out
* automatically.
*/
enum DataRequestMode: string implements HasLabel
{
case Automatic = 'automatic';
case Approval = 'approval';
case Manual = 'manual';
public function getLabel(): string
{
return match ($this) {
self::Automatic => 'Automatisch beim Gast nachfragen',
self::Approval => 'Rückfrage vorbereiten, Sie geben den Versand frei',
self::Manual => 'Sie fragen selbst nach (Aufgabe mit Textvorschlag)',
};
}
}
+5 -1
View File
@@ -20,6 +20,7 @@ enum DocumentKind: string implements HasLabel
case ExternalRecord = 'external_record';
case StayConfirmation = 'stay_confirmation';
case Internal = 'internal';
case DataRequest = 'data_request';
public function getLabel(): string
{
@@ -30,6 +31,7 @@ public function getLabel(): string
self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)',
self::StayConfirmation => 'Aufenthaltsbestätigung (privat)',
self::Internal => 'Nur intern, kein Dokument an Gäste',
self::DataRequest => 'Rückfrage nach fehlenden Angaben',
};
}
@@ -45,6 +47,7 @@ public function description(): string
self::ExternalRecord => 'Für Buchungen, die beim Portal bereits verbindlich sind: Buchungsdaten und – falls hinterlegt – Ihre Vorlage, ohne erneute Annahme durch den Gast.',
self::StayConfirmation => 'Für private Überlassungen (Familie, Freunde): Bestätigung des Aufenthalts ohne Mietvertrag, nur auf Wunsch.',
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
self::DataRequest => 'E-Mail an den Gast mit der Bitte um fehlende Angaben (Anschrift, Personenzahl …) und einem persönlichen Link zum Ergänzen, dazu Erinnerungen und gezielte Folgefragen. Sie nennt nur eine tatsächlich bestehende vorläufige Reservierung. Im Testbetrieb gehen die Texte auch ohne Freigabe hinaus (nur an die Testadresse).',
};
}
@@ -85,7 +88,7 @@ public function containsContract(): bool
*/
public function isAvailable(): bool
{
return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation], true);
return in_array($this, [self::Offer, self::Information, self::Confirmation, self::ExternalRecord, self::StayConfirmation, self::DataRequest], true);
}
/**
@@ -117,6 +120,7 @@ public function fileName(): string
self::ExternalRecord => 'Buchungsunterlagen',
self::StayConfirmation => 'Aufenthaltsbestaetigung',
self::Internal => 'Intern',
self::DataRequest => 'Rueckfrage',
};
}
}
+38
View File
@@ -0,0 +1,38 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Where a detail of a case came from (v0.11 common fact intake, S5).
*/
enum FactSource: string implements HasLabel
{
case WebsiteForm = 'website_form';
case GuestLink = 'guest_link';
case Email = 'email';
case PortalMail = 'portal_mail';
case Extraction = 'llm';
case Landlord = 'landlord';
public function getLabel(): string
{
return match ($this) {
self::WebsiteForm => '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;
}
}
+3 -1
View File
@@ -15,6 +15,7 @@ enum InboxMessageKind: string implements HasColor, HasLabel
case OfferMailFailed = 'offer_mail_failed';
case OfferRejected = 'offer_rejected';
case SyncFailed = 'sync_failed';
case AiAccessRejected = 'ai_access_rejected';
public function getLabel(): string
{
@@ -24,6 +25,7 @@ public function getLabel(): string
self::OfferMailFailed => 'Angebot nicht zugestellt',
self::OfferRejected => 'Annahme abgewiesen',
self::SyncFailed => 'Kalenderabgleich gestört',
self::AiAccessRejected => 'KI-Anbindung abgelehnt',
};
}
@@ -31,7 +33,7 @@ public function getColor(): string
{
return match ($this) {
self::ChannelConflict, self::SyncFailed => 'danger',
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected, self::AiAccessRejected => 'warning',
};
}
}
+39 -2
View File
@@ -17,6 +17,14 @@ enum ProcessSetting: string
case GuestMessages = 'guest_messages';
case ArrivalInfoDaysBefore = 'arrival_info_days_before';
case ContractTemplate = 'contract_template_id';
case ClarificationHoldAutoMinutes = 'clarification_hold_auto_minutes';
case ClarificationHoldManualMinutes = 'clarification_hold_manual_minutes';
case DataRequest = 'data_request_mode';
case DataRequestRemindersMax = 'data_request_reminders_max';
case DataRequestFollowupsMax = 'data_request_followups_max';
case DataRequestReminderHours = 'data_request_reminder_hours';
case GuestLinkValidDays = 'guest_link_valid_days';
case FormRequiresAddress = 'form_requires_address';
/**
* Built-in default (the behaviour before any landlord setting existed).
@@ -30,6 +38,14 @@ public function default(): string|int|bool|null
self::Documents, self::Payments, self::GuestMessages => Responsibility::Landlord->value,
self::ArrivalInfoDaysBefore => 3,
self::ContractTemplate => null,
self::ClarificationHoldAutoMinutes => 15,
self::ClarificationHoldManualMinutes => 180,
self::DataRequest => DataRequestMode::Approval->value,
self::DataRequestRemindersMax => 2,
self::DataRequestFollowupsMax => 2,
self::DataRequestReminderHours => 24,
self::GuestLinkValidDays => 14,
self::FormRequiresAddress => false,
};
}
@@ -47,6 +63,14 @@ public function question(): string
self::GuestMessages => 'Wer schickt dem Gast Anreise-Informationen und die Bitte um eine Bewertung?',
self::ArrivalInfoDaysBefore => 'Wann gehen die Anreise-Informationen an den Gast?',
self::ContractTemplate => 'Welche Vertragsvorlage wird verwendet?',
self::ClarificationHoldAutoMinutes => 'Wie lange wird der Zeitraum einer unvollständigen Anfrage vorläufig reserviert, wenn automatisch nachgefragt wird (0 = gar nicht)?',
self::ClarificationHoldManualMinutes => 'Wie lange wird der Zeitraum einer unvollständigen Anfrage vorläufig reserviert, wenn Sie die Rückfrage freigeben oder selbst nachfragen (0 = gar nicht)?',
self::DataRequest => 'Wie wird nach fehlenden Angaben gefragt?',
self::DataRequestRemindersMax => 'Wie oft wird höchstens erinnert, wenn der Gast nicht antwortet?',
self::DataRequestFollowupsMax => 'Wie viele gezielte Folgefragen gehen höchstens hinaus, wenn eine Antwort unvollständig ist?',
self::DataRequestReminderHours => 'Nach wie vielen Stunden ohne Antwort wird erinnert?',
self::GuestLinkValidDays => 'Wie lange gilt der Link, über den der Gast Angaben ergänzt?',
self::FormRequiresAddress => 'Muss die vollständige Anschrift schon im Anfrageformular der Webseite angegeben werden?',
};
}
@@ -61,7 +85,9 @@ public function channelIntakes(): array
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate => [IntakeKind::Inquiry, IntakeKind::Booking],
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
self::Documents => [IntakeKind::Booking],
self::ArrivalInfoDaysBefore => [],
self::ArrivalInfoDaysBefore, self::GuestLinkValidDays => [],
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::FormRequiresAddress => [IntakeKind::Inquiry],
self::DataRequest, self::DataRequestRemindersMax, self::DataRequestFollowupsMax, self::DataRequestReminderHours => [IntakeKind::Inquiry, IntakeKind::Booking],
};
}
@@ -85,8 +111,12 @@ public function normalize(mixed $value): string|int|bool|null
return match ($this) {
self::Processing => ($value instanceof ProcessingMode ? $value : ProcessingMode::tryFrom((string) $value))?->value,
self::Documents, self::Payments, self::GuestMessages => ($value instanceof Responsibility ? $value : Responsibility::tryFrom((string) $value))?->value,
self::PreReservation => filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
self::PreReservation, self::FormRequiresAddress => is_bool($value) ? $value : filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE),
self::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
self::DataRequest => ($value instanceof DataRequestMode ? $value : DataRequestMode::tryFrom((string) $value))?->value,
// 0 is a value of its own: no clarification hold, no reminder, no follow-up question.
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes, self::DataRequestRemindersMax, self::DataRequestFollowupsMax => is_numeric($value) ? max(0, (int) $value) : null,
self::DataRequestReminderHours, self::GuestLinkValidDays => is_numeric($value) ? max(1, (int) $value) : null,
};
}
@@ -102,6 +132,13 @@ public function describe(string|int|bool|null $value): string
self::HoldHours => $value.' Stunden',
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
self::ContractTemplate => $value === null ? 'Texte der Webseite' : 'Vorlage Nr. '.$value,
self::ClarificationHoldAutoMinutes, self::ClarificationHoldManualMinutes => (int) $value === 0 ? 'keine vorläufige Reservierung' : $value.' Minuten',
self::DataRequest => DataRequestMode::tryFrom((string) $value)?->getLabel() ?? '–',
self::DataRequestRemindersMax => (int) $value === 0 ? 'keine Erinnerung' : 'höchstens '.$value.' Erinnerung'.((int) $value === 1 ? '' : 'en'),
self::DataRequestFollowupsMax => (int) $value === 0 ? 'keine Folgefrage' : 'höchstens '.$value.' Folgefrage'.((int) $value === 1 ? '' : 'n'),
self::DataRequestReminderHours => 'nach '.$value.' Stunden',
self::GuestLinkValidDays => $value.' Tage',
self::FormRequiresAddress => $value ? 'ja, Pflichtangabe' : 'nein, kann nachgefragt werden',
};
}
}
+7 -5
View File
@@ -31,7 +31,8 @@ public function description(): string
return match ($this) {
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
self::AiGuestMail => 'Antworten und Nachrichten der Gäste auswerten: erkannte Angaben (Anschrift, Telefon …) werden vorgeschlagen und nur nach festen Regeln übernommen; nichts Verbindliches entscheidet die KI.',
self::AiOffers, self::AiMarketing => 'Noch nicht gebaut.',
};
}
@@ -41,8 +42,8 @@ public function description(): string
public function isWired(): bool
{
return match ($this) {
self::PortalSync, self::PortalMail => true,
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
self::PortalSync, self::PortalMail, self::AiGuestMail => true,
self::AiOffers, self::AiMarketing => false,
};
}
@@ -52,11 +53,12 @@ public function isWired(): bool
*/
public function enabledByDefault(): bool
{
return $this->isWired();
// The AI service sends guests' messages to an external provider: only after the operator switched it on.
return $this->isWired() && $this !== self::AiGuestMail;
}
/**
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
* Whether the landlord's own API key is of any use (the guest communication extraction calls out).
*/
public function usesApiKey(): bool
{
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Events;
use App\Enums\FactSource;
use App\Models\Booking;
use App\Process\FactContribution;
use Illuminate\Foundation\Events\Dispatchable;
/**
* Details arrived for a case and went through the common fact intake (after the commit). The data request of the
* case listens to stop reminders or to plan a follow-up question (CH-17).
*/
class CaseFactsContributed
{
use Dispatchable;
public function __construct(
public readonly Booking $booking,
public readonly FactContribution $contribution,
public readonly FactSource $source,
) {}
}
@@ -2,6 +2,7 @@
namespace App\Filament\Forms;
use App\Enums\DataRequestMode;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
@@ -41,6 +42,14 @@ public static function field(string $name, ProcessSetting $setting, string $inhe
ProcessSetting::ContractTemplate => Select::make($name)
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all())
->placeholder($placeholder),
ProcessSetting::ClarificationHoldAutoMinutes, ProcessSetting::ClarificationHoldManualMinutes => TextInput::make($name)->integer()->minValue(0)->maxValue(1440)->suffix('Minuten')->placeholder($placeholder)
->helperText('Nur für Anfragen, denen noch Angaben für ein Angebot fehlen, und nur wenn der Zeitraum frei ist. Endet von selbst und wird durch Rückfragen nicht verlängert. Die Reservierung eines Angebots bleibt davon unberührt.'),
ProcessSetting::DataRequest => Select::make($name)->options(DataRequestMode::class)->placeholder($placeholder)
->helperText('Unabhängig davon, ob Angebote automatisch hinausgehen.'),
ProcessSetting::DataRequestRemindersMax, ProcessSetting::DataRequestFollowupsMax => TextInput::make($name)->integer()->minValue(0)->maxValue(5)->placeholder($placeholder),
ProcessSetting::DataRequestReminderHours => TextInput::make($name)->integer()->minValue(1)->maxValue(336)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::GuestLinkValidDays => TextInput::make($name)->integer()->minValue(1)->maxValue(60)->suffix('Tage')->placeholder($placeholder),
ProcessSetting::FormRequiresAddress => Select::make($name)->options(['1' => 'Ja – ohne vollständige Anschrift kann nicht angefragt werden', '0' => 'Nein – fehlt sie, wird beim Gast nachgefragt'])->placeholder($placeholder),
})->label($setting->question());
}
+196
View File
@@ -0,0 +1,196 @@
<?php
namespace App\Filament\Pages;
use App\Communication\Extraction\AiAccess;
use App\Communication\Extraction\AiProvider;
use App\Communication\Extraction\ExtractionFailed;
use App\Communication\Extraction\LlmClient;
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Tenant;
use App\Models\TenantService;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
use Filament\Schemas\Components\EmbeddedSchema;
use Filament\Schemas\Components\Form;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use UnitEnum;
/**
* "KI-Anbindung" (v0.11, bring your own key): the landlord connects his own AI access for the evaluation of guest
* messages – provider (Anthropic or OpenRouter), key and the two models. The key is stored encrypted and never shown
* again; an empty field keeps it. A check sends a tiny test request to both models. The page only exists when the
* operator switched the service on for this landlord.
*/
class AiConnection extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSparkles;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'KI-Anbindung';
protected static ?string $title = 'KI-Anbindung';
protected static ?string $slug = 'ki-anbindung';
protected static ?int $navigationSort = 3;
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin) && app(TenantFeatures::class)->enabled(TenantServiceKey::AiGuestMail);
}
public function mount(): void
{
$settings = (array) $this->service()?->settings;
// The key is never put into the form.
$this->form->fill([
'provider' => $settings['provider'] ?? null,
'small_model' => $settings['small_model'] ?? null,
'review_model' => $settings['review_model'] ?? null,
'api_key' => null,
]);
}
public function form(Schema $schema): Schema
{
return $schema
->statePath('data')
->components([
Section::make('Ihr Zugang')
->description('Die Auswertung von Gast-Nachrichten nutzt Ihren eigenen Zugang bei einem KI-Anbieter; die Kosten rechnet der Anbieter mit Ihnen ab. Nachrichten werden dafür an den Anbieter übermittelt – bitte Auftragsverarbeitung und Datenschutzhinweise beachten. Ohne gültigen Zugang bleibt jede Nachricht zur Prüfung im Posteingang.')
->columns(2)
->schema([
Select::make('provider')->label('Anbieter')->options(AiProvider::class)->required()->live(),
TextInput::make('api_key')->label('API-Schlüssel')->password()->autocomplete('new-password')->maxLength(500)
->placeholder(fn (): string => filled($this->service()?->api_key) ? 'gespeichert – leer lassen, um ihn zu behalten' : 'noch keiner gespeichert')
->helperText('Wird verschlüsselt gespeichert und nie wieder angezeigt.'),
TextInput::make('small_model')->label('Modell für die erste Auswertung (klein, günstig)')->required()->maxLength(150)
->helperText(fn (Get $get): string => self::provider($get('provider'))?->modelExamples() ?? 'Kennung des Modells beim Anbieter'),
TextInput::make('review_model')->label('Modell für die Prüfung unsicherer Fälle (groß)')->required()->maxLength(150)
->helperText('Wird nur gefragt, wenn eine Angabe widersprüchlich, unplausibel oder unsicher ist.'),
]),
Section::make('Stand')
->schema([Text::make(fn (): string => $this->checkSummary())]),
]);
}
public function content(Schema $schema): Schema
{
return $schema->components([
Form::make([EmbeddedSchema::make('form')])
->id('form')
->livewireSubmitHandler('save')
->footer([Actions::make([
Action::make('save')->label('Speichern')->submit('save'),
Action::make('check')->label('Verbindung prüfen')->color('gray')->icon(Heroicon::OutlinedSignal)->action(fn () => $this->check()),
Action::make('removeKey')->label('Schlüssel entfernen')->color('danger')->requiresConfirmation()
->modalDescription('Danach ist die automatische Auswertung aus, bis ein neuer Schlüssel gespeichert ist.')
->visible(fn (): bool => filled($this->service()?->api_key))
->action(fn () => $this->removeKey()),
])]),
]);
}
public function save(): void
{
$state = $this->form->getState();
$service = $this->service() ?? new TenantService(['tenant_id' => $this->tenant()->id, 'service' => TenantServiceKey::AiGuestMail->value, 'is_enabled' => true]);
$service->settings = ['provider' => self::provider($state['provider'])?->value, 'small_model' => trim((string) $state['small_model']), 'review_model' => trim((string) $state['review_model'])];
if (filled($state['api_key'] ?? null)) {
$service->api_key = trim((string) $state['api_key']);
}
// A changed access is checked again before it counts as rejected.
$service->forceFill(['check_status' => null, 'check_message' => null])->save();
$this->data['api_key'] = null;
Notification::make()->title('Gespeichert')->body(filled($service->api_key) ? 'Bitte „Verbindung prüfen“ ausführen.' : 'Ohne Schlüssel bleibt die Auswertung aus.')->success()->send();
}
/**
* Sends a minimal structured request to both models; the result is stored, the key never shown.
*/
public function check(): void
{
$service = $this->service();
$access = $service === null ? null : AiAccess::fromService($service);
if ($access === null) {
Notification::make()->title('Unvollständig')->body('Bitte Anbieter, Schlüssel und beide Modelle speichern.')->warning()->send();
return;
}
$schema = ['type' => 'object', 'additionalProperties' => false, 'required' => ['ok'], 'properties' => ['ok' => ['type' => 'boolean']]];
try {
foreach ([$access->smallModel, $access->reviewModel] as $model) {
app(LlmClient::class)->structured($access, $model, 'Answer with {"ok": true}.', 'Test', $schema, 'low');
}
} catch (ExtractionFailed $exception) {
$service->forceFill(['check_status' => AiAccess::INVALID, 'check_message' => mb_substr($exception->getMessage(), 0, 500), 'checked_at' => now()])->save();
Notification::make()->title('Prüfung fehlgeschlagen')->body($exception->getMessage())->danger()->send();
return;
}
$service->forceFill(['check_status' => AiAccess::OK, 'check_message' => null, 'checked_at' => now()])->save();
Notification::make()->title('Verbindung in Ordnung')->body('Beide Modelle antworten im erwarteten Format.')->success()->send();
}
public function removeKey(): void
{
$this->service()?->forceFill(['api_key' => null, 'check_status' => null, 'check_message' => null, 'checked_at' => null])->save();
Notification::make()->title('Schlüssel entfernt')->success()->send();
}
private static function provider(mixed $value): ?AiProvider
{
return $value instanceof AiProvider ? $value : AiProvider::tryFrom((string) $value);
}
private function checkSummary(): string
{
$service = $this->service();
if ($service === null || blank($service->api_key)) {
return 'Kein Zugang gespeichert – Nachrichten werden nicht automatisch ausgewertet.';
}
return match ($service->check_status) {
AiAccess::OK => 'Zuletzt erfolgreich geprüft am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr.',
AiAccess::INVALID => 'Abgelehnt am '.$service->checked_at?->format('d.m.Y, H:i').' Uhr: '.$service->check_message.' Die automatische Auswertung ist aus.',
default => 'Gespeichert, noch nicht geprüft.',
};
}
private function service(): ?TenantService
{
return AiAccess::service($this->tenant());
}
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
}
+5 -2
View File
@@ -64,8 +64,11 @@ public function matrix(): array
$settings = app(ProcessSettings::class);
return Property::query()->orderBy('name')->get()->map(function (Property $property) use ($settings): array {
$columns = [['label' => 'Direkte Anfrage (Webseite, Telefon)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)]];
foreach (Channel::query()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
$columns = [
['label' => 'Eigene Webseite – Anfrage', 'profile' => $settings->forWebsite($property)],
['label' => 'Direkte Anfrage (Telefon, E-Mail)', 'profile' => $settings->resolve($property, null, IntakeKind::Inquiry)],
];
foreach (Channel::query()->portals()->where('property_id', $property->id)->orderBy('name')->get() as $channel) {
$columns[] = ['label' => $channel->name.' – Anfrage', 'profile' => $settings->resolve($property, $channel, IntakeKind::Inquiry)];
$columns[] = ['label' => $channel->name.' – feste Buchung', 'profile' => $settings->resolve($property, $channel, IntakeKind::Booking)];
}
+31 -6
View File
@@ -7,6 +7,7 @@
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Mailbox;
use App\Models\Tenant;
use App\Support\Settings;
use App\Tenancy\TenantConfig;
@@ -102,12 +103,14 @@ public function mount(): void
'bank_iban' => $tenant->bank_iban,
'bank_bic' => $tenant->bank_bic,
'tax_note' => $tenant->tax_note,
'mailbox_host' => $tenant->mailbox_host,
'mailbox_port' => $tenant->mailbox_port,
'mailbox_username' => $tenant->mailbox_username,
'mailbox_password' => $tenant->mailbox_password,
'mailbox_encryption' => $tenant->mailbox_encryption,
'mailbox_folder' => $tenant->mailbox_folder,
'mailbox_host' => $tenant->activeMailbox()?->host ?? $tenant->mailbox_host,
'mailbox_port' => $tenant->activeMailbox()?->port ?? $tenant->mailbox_port,
'mailbox_username' => $tenant->activeMailbox()?->username ?? $tenant->mailbox_username,
'mailbox_password' => $tenant->activeMailbox()?->password ?? $tenant->mailbox_password,
'mailbox_encryption' => $tenant->activeMailbox()?->encryption ?? $tenant->mailbox_encryption,
'mailbox_folder' => $tenant->activeMailbox()?->folder ?? $tenant->mailbox_folder,
'mailbox_address' => $tenant->activeMailbox()?->address,
'mailbox_mode' => $tenant->activeMailbox()?->mode ?? Mailbox::PORTAL_ONLY,
'reminder_interval_days' => $tenant->reminder_interval_days,
'digest_daily' => $tenant->digest_daily,
'digest_weekly' => $tenant->digest_weekly,
@@ -249,6 +252,12 @@ public function form(Schema $schema): Schema
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
->placeholder('SSL'),
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
Select::make('mailbox_mode')->label('Was wird gelesen?')
->options([Mailbox::PORTAL_ONLY => 'Nur Buchungsmails der Portale (wie bisher)', Mailbox::FULL => 'Alle Nachrichten (eigenes Postfach für die Gästekommunikation)'])
->required()
->helperText('„Alle Nachrichten“ nur für ein Postfach, das ausschließlich für Anfragen und Gästeantworten dient: Antworten und Gast-Mails werden dann den Vorgängen zugeordnet oder im Posteingang zur Klärung gezeigt.'),
TextInput::make('mailbox_address')->label('Adresse dieses Postfachs (für Antworten der Gäste)')->email()->maxLength(190)
->helperText('Rückfragen nennen diese Adresse als Antwortadresse, damit die Antwort hier ankommt.'),
]),
Section::make('Fristen und Grenzen')
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
@@ -329,6 +338,22 @@ public function save(): void
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
]);
// v0.11 (CH-05): the active mailbox record leads; it is kept in step with the fields above.
$mailbox = $tenant->activeMailbox() ?? new Mailbox(['is_active' => true]);
$mailbox->forceFill(['tenant_id' => $tenant->id])->fill([
'host' => $data['mailbox_host'] ?? null,
'port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
'username' => $data['mailbox_username'] ?? null,
'password' => $data['mailbox_password'] ?? null,
'encryption' => $data['mailbox_encryption'] ?? null,
'folder' => $data['mailbox_folder'] ?? null,
'address' => $data['mailbox_address'] ?? null,
'mode' => $data['mailbox_mode'] ?? Mailbox::PORTAL_ONLY,
]);
if ($mailbox->exists || filled($mailbox->host)) {
$mailbox->save();
}
app(TenantConfig::class)->refresh();
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
@@ -147,7 +147,7 @@ public static function portalActions(): array
->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.$block->occupationKind()->getLabel().' · '.($block->reason ?? 'Kalenderbelegung').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all();
}),
Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt')
->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
->options(fn (BlockedPeriod $record): array => Channel::query()->portals()->where('property_id', $record->property_id)->pluck('name', 'id')->all())
->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'),
])
->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void {
@@ -47,7 +47,7 @@ protected function handleRecordCreation(array $data): Model
$channel = filled($data['channel_id'] ?? null) ? Channel::query()->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, [
@@ -9,6 +9,7 @@
use App\Actions\EndInternalCase;
use App\Actions\ProvideGuestContact;
use App\Actions\RecordPortalAmounts;
use App\Actions\RequestCaseData;
use App\Actions\SendBookingDocuments;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
@@ -37,6 +38,7 @@
use App\Models\BookingTask;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\DataRequest;
use App\Models\Extra;
use App\Models\User;
use App\Pricing\PrivateStayPrice;
@@ -44,6 +46,8 @@
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use App\Support\Countries;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
@@ -128,6 +132,8 @@ protected function getHeaderActions(): array
$this->closeStayAction(),
$this->settleAction(),
$this->requestContactAction(),
$this->approveDataRequestAction(),
$this->stopDataRequestAction(),
AssignGuestAction::make(),
$this->confirmAction(),
$this->sendDocumentsAction(),
@@ -291,10 +297,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 +313,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 +338,65 @@ 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);
}
/**
* v0.11 data request: send the prepared question (or ask now although the case is set to asking by hand).
*/
private function approveDataRequestAction(): Action
{
return Action::make('approveDataRequest')
->label('Rückfrage an den Gast senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->openDataRequest()?->status, [DataRequest::DRAFT, DataRequest::MANUAL], true) && filled($this->record->guest?->email))
->modalHeading('Fehlende Angaben beim Gast anfragen')
->modalDescription(function (): string {
$request = $this->record->openDataRequest();
$state = $this->record->clarificationState();
return 'Der Gast erhält eine E-Mail mit einem persönlichen Link und wird gebeten um: '.implode(', ', CaseRequirements::labels((array) $request?->fields)).'. '
.match ($state['state']) {
'active' => 'Die Mail nennt die vorläufige Reservierung bis '.$state['until']->format('d.m.Y, H:i').' Uhr.',
'expired' => 'Die Mail sagt, dass die vorläufige Reservierung abgelaufen ist.',
default => $this->record->isBinding() ? 'Die Mail sagt, dass die Buchung verbindlich bleibt.' : 'Die Mail sagt, dass der Zeitraum noch nicht reserviert ist.',
}
.(RequestCaseData::mayGoOutAutomatically() ? '' : ' Hinweis: Der Text der Rückfrage ist noch eine Arbeitsfassung (So arbeite ich › Dokumente); mit „Senden“ bestätigen Sie ihn für diesen Vorgang.');
})
->modalSubmitActionLabel('Senden')
->action(function (RequestCaseData $requests): void {
$request = $this->record->openDataRequest();
$sent = $request !== null && $requests->approve($request);
$this->record->refresh();
$sent
? Notification::make()->title('Rückfrage gesendet')->success()->send()
: Notification::make()->title('Nicht gesendet')->body('Bitte die E-Mail-Adresse des Gastes prüfen – oder es fehlt inzwischen nichts mehr.')->danger()->send();
});
}
private function stopDataRequestAction(): Action
{
return Action::make('stopDataRequest')
->label('Rückfrage beenden')
->icon(Heroicon::OutlinedNoSymbol)
->color('gray')
->visible(fn (): bool => $this->record->openDataRequest() !== null)
->requiresConfirmation()
->modalDescription('Es gehen keine Erinnerungen und Folgefragen mehr hinaus. Die fehlenden Angaben tragen Sie dann selbst ein.')
->action(function (RequestCaseData $requests): void {
$requests->close($this->record->openDataRequest(), DataRequest::STOPPED, 'von Ihnen beendet');
$this->record->refresh();
Notification::make()->title('Rückfrage beendet')->success()->send();
});
}
private function requestContactAction(): Action
{
return Action::make('requestContact')
@@ -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;
@@ -120,7 +121,7 @@ public static function configure(Schema $schema): Schema
Select::make('channel_id')
->label(fn (Get $get): string => $get('kind') === self::EXTERNAL ? 'Gebucht über' : 'Über ein Portal (optional)')
->placeholder('Direkt – kein Portal')
->options(fn (Get $get): array => Channel::query()->where('property_id', $get('property_id'))->orderBy('name')->pluck('name', 'id')->all())
->options(fn (Get $get): array => Channel::query()->portals()->where('property_id', $get('property_id'))->orderBy('name')->pluck('name', 'id')->all())
->required($is(self::EXTERNAL)),
TextInput::make('portal_reference')->label('Buchungsnummer im Portal')->maxLength(100)->visible($is(self::EXTERNAL)),
EuroInput::make('portal_total')
@@ -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?')
@@ -91,7 +91,7 @@ public static function configure(Table $table, ?int $guestId = null): Table
...collect(BookingStatus::cases())->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all(),
'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed',
]),
SelectFilter::make('channel')->label('Buchungskanal')->options(fn (): array => Channel::query()->orderBy('name')->pluck('name', 'id')->all()),
SelectFilter::make('channel')->label('Buchungskanal')->options(fn (): array => Channel::query()->portals()->orderBy('name')->pluck('name', 'id')->all()),
Filter::make('period')->label('Anreise im Zeitraum')->schema([
DatePicker::make('arrival_from')->label('Anreise ab'),
DatePicker::make('arrival_until')->label('Anreise bis'),
@@ -29,11 +29,11 @@ class ChannelResource extends Resource
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
protected static ?string $navigationLabel = 'Kalenderabgleich (iCal)';
protected static ?string $navigationLabel = 'Kanäle';
protected static ?string $modelLabel = 'iCal-Verbindung';
protected static ?string $modelLabel = 'Kanal';
protected static ?string $pluralModelLabel = 'Kalenderabgleich (iCal)';
protected static ?string $pluralModelLabel = 'Kanäle (Webseite, Portale, iCal)';
protected static ?int $navigationSort = 4;
@@ -6,6 +6,7 @@
use App\Actions\ConfigureChannel;
use App\Channels\ChannelSyncException;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Channel;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\EditRecord;
@@ -18,8 +19,8 @@ class EditChannel extends EditRecord
protected function getHeaderActions(): array
{
return [
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record])),
Action::make('analyze')->label('Kalender analysieren')->action(function (AnalyzeChannelCalendar $analyze): void {
Action::make('rules')->label('Regeln & Exportfelder')->url(fn (): string => ChannelResource::getUrl('rules', ['record' => $this->record]))->visible(fn (): bool => $this->record->isPortal()),
Action::make('analyze')->label('Kalender analysieren')->visible(fn (): bool => $this->record->isPortal())->action(function (AnalyzeChannelCalendar $analyze): void {
try {
$analyze->handle($this->record);
$this->redirect(ChannelResource::getUrl('rules', ['record' => $this->record]));
@@ -37,6 +38,13 @@ protected function mutateFormDataBeforeFill(array $data): array
protected function handleRecordUpdate(Model $record, array $data): Model
{
// The own website's entry only keeps its settings; there is no connection to configure.
if ($record instanceof Channel && $record->isWebsite()) {
$record->update(['process_overrides' => $data['process_overrides'] ?? []]);
return $record;
}
return app(ConfigureChannel::class)->handle($record->property, $data, $record);
}
@@ -3,20 +3,44 @@
namespace App\Filament\Resources\Channels\Pages;
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Pages\HandlingSettings;
use App\Filament\Resources\Channels\ChannelResource;
use App\Models\Channel;
use App\Models\Property;
use Filament\Actions\Action;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Icons\Heroicon;
/**
* The channel manager (v0.11, E-037): the own website and every portal of the landlord in one list. The landlord's
* defaults for all channels stay on "So arbeite ich"; each channel only keeps its deviations.
*/
class ListChannels extends ListRecords
{
use ListsCurrentProperty;
protected static string $resource = ChannelResource::class;
public function mount(): void
{
parent::mount();
// Every property has its website entry (created by the migration; new properties get it here).
Property::query()->get()->each(fn (Property $property): Channel => Channel::websiteOf($property));
}
public function getSubheading(): ?string
{
return 'Alle Eingangskanäle an einer Stelle: Ihre eigene Webseite und die Portale. Was für alle Kanäle gilt, stellen Sie unter „Ihre Standards“ ein; hier steht nur, was ein Kanal anders macht.';
}
protected function getHeaderActions(): array
{
return [
CreateAction::make()->label('iCal-Verbindung anlegen'),
Action::make('defaults')->label('Ihre Standards (alle Kanäle)')->icon(Heroicon::OutlinedAdjustmentsHorizontal)->color('gray')
->url(fn (): string => HandlingSettings::getUrl()),
CreateAction::make()->label('Portal (iCal-Verbindung) anlegen'),
];
}
}
@@ -39,77 +39,110 @@ public static function configure(Schema $schema, bool $selectProperty = false):
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
->default(fn (): ?int => app(CurrentProperty::class)->id())
->disabled(fn (?Channel $record): bool => $record !== null)->dehydrated()->columnSpanFull()] : []),
TextEntry::make('export_url')
->label('Eigener iCal-Exportlink')
->state(fn (?Channel $record): ?string => $record?->exportUrl())
->visible(fn (?Channel $record): bool => $record?->exists ?? false)
->copyable()
->copyMessage('Exportlink kopiert')
->wrap()
->extraAttributes(['style' => 'overflow-wrap:anywhere'])
->columnSpanFull(),
TextInput::make('name')
->label('Name der Kalenderverbindung')
->placeholder('z. B. FeWo-direkt')
->required()
->maxLength(100),
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
Select::make('booking_model')->label('Was kommt über dieses Portal?')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'),
Select::make('case_intake')
->label('Erkannte Buchungen automatisch als Vorgang übernehmen?')
->options(CaseIntakeMode::class)
->default(CaseIntakeMode::Off)
->required()
->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.')
->columnSpanFull(),
...self::processSections(),
Select::make('connector')
->label('Kalenderanbindung')
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.')
->options($registry->options())
->default('ical')
->live()
->required(),
Group::make()
->columns(2)
->columnSpanFull()
->schema(fn (Get $get): array => filled($get('connector')) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
Toggle::make('import_enabled')->label('Import aktiviert')->default(false)
->helperText('Abruf durch FewoPortal alle fünf Minuten, sofern der Kanal aktiv ist.'),
Toggle::make('export_enabled')->label('Export aktiviert')->default(false)
->helperText('Ausgeschaltet bleibt der letzte gültige Export eingefroren erreichbar. Ohne Stand: HTTP 503, kein leerer Kalender.'),
Select::make('export_mode')->label('Exportmodus')->options(ChannelExportMode::class)->default(ChannelExportMode::Test)->required()
->helperText('Testbetrieb exportiert keine Fremdbelegungen und gewährleistet keine vollständige kanalübergreifende Sperrung. Regulär nur nach bewusster Freigabe wählen.')
->columnSpanFull(),
TextInput::make('external_poll_minutes')->label('Erwarteter externer Abrufabstand (Minuten)')
->integer()->minValue(1)->maxValue(43200)
->helperText('Nur eine Annahme zum Portal; verändert weder unseren Abruf noch bestätigt sie eine Übernahme.'),
Select::make('echo_behavior')->label('Beobachtetes Rückkopplungsverhalten')->options(ChannelEchoBehavior::class)->default(ChannelEchoBehavior::Unverified)->required()->columnSpanFull()
->helperText('Bei Weitergabe mit neuen UIDs bleiben neue Importereignisse bis zur persönlichen Klärung vom Export ausgeschlossen. Sie sperren intern weiterhin.'),
Textarea::make('echo_notes')->label('Nachweis / Beobachtung zum Rückkopplungsverhalten')->maxLength(4000)->columnSpanFull(),
DateTimePicker::make('portal_verified_at')->label('Tatsächliche Übernahme im Portal zuletzt persönlich geprüft')->seconds(false)
->helperText('Nur nach Sichtkontrolle im Portal eintragen. Wird durch einen Feedabruf nicht automatisch gesetzt.'),
Textarea::make('operating_notes')->label('Zusätzliche Anforderungen dieses Portals')->maxLength(4000)->columnSpanFull()
->helperText('Zum Beispiel eine zusätzliche Bestätigung, dass der Belegungskalender gepflegt ist.'),
TextInput::make('settings.email_senders')
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
->maxLength(500)
->columnSpanFull(),
Toggle::make('requires_manual_blocking')
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
->live()
->columnSpanFull(),
TextInput::make('manage_url')
->label('Link zum Kalender im Vermieterbereich')
->url()
->maxLength(2048)
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
->columnSpanFull(),
->visible(fn (?Channel $record): bool => ! ($record?->isWebsite() ?? false))
->schema([
TextEntry::make('export_url')
->label('Eigener iCal-Exportlink')
->state(fn (?Channel $record): ?string => $record?->exportUrl())
->visible(fn (?Channel $record): bool => $record?->exists ?? false)
->copyable()
->copyMessage('Exportlink kopiert')
->wrap()
->extraAttributes(['style' => 'overflow-wrap:anywhere'])
->columnSpanFull(),
TextInput::make('name')
->label('Name der Kalenderverbindung')
->placeholder('z. B. FeWo-direkt')
->required()
->maxLength(100),
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
Select::make('booking_model')->label('Was kommt über dieses Portal?')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'),
Select::make('case_intake')
->label('Erkannte Buchungen automatisch als Vorgang übernehmen?')
->options(CaseIntakeMode::class)
->default(CaseIntakeMode::Off)
->required()
->helperText('Zuerst „Beobachten“: Dann entsteht nichts, aber das Eingangsprotokoll (Expertenansicht) zeigt, welche Vorgänge entstanden wären. Unklare Belegungen und Meldungen zu gebuchten Vorgängen erscheinen unter „Zu erledigen“. Unterlagen gehen nie ohne Ihre Freigabe hinaus.')
->columnSpanFull(),
...self::processSections(),
Select::make('connector')
->label('Kalenderanbindung')
->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.')
->options($registry->options())
->default('ical')
->live()
->required(),
Group::make()
->columnSpanFull()
->schema(fn (Get $get): array => isset($registry->connectors()[$get('connector')]) ? $registry->connectors()[$get('connector')]::settingsSchema() : []),
Toggle::make('import_enabled')->label('Import aktiviert')->default(false)
->helperText('Abruf durch FewoPortal alle fünf Minuten, sofern der Kanal aktiv ist.'),
Toggle::make('export_enabled')->label('Export aktiviert')->default(false)
->helperText('Ausgeschaltet bleibt der letzte gültige Export eingefroren erreichbar. Ohne Stand: HTTP 503, kein leerer Kalender.'),
Select::make('export_mode')->label('Exportmodus')->options(ChannelExportMode::class)->default(ChannelExportMode::Test)->required()
->helperText('Testbetrieb exportiert keine Fremdbelegungen und gewährleistet keine vollständige kanalübergreifende Sperrung. Regulär nur nach bewusster Freigabe wählen.')
->columnSpanFull(),
TextInput::make('external_poll_minutes')->label('Erwarteter externer Abrufabstand (Minuten)')
->integer()->minValue(1)->maxValue(43200)
->helperText('Nur eine Annahme zum Portal; verändert weder unseren Abruf noch bestätigt sie eine Übernahme.'),
Select::make('echo_behavior')->label('Beobachtetes Rückkopplungsverhalten')->options(ChannelEchoBehavior::class)->default(ChannelEchoBehavior::Unverified)->required()->columnSpanFull()
->helperText('Bei Weitergabe mit neuen UIDs bleiben neue Importereignisse bis zur persönlichen Klärung vom Export ausgeschlossen. Sie sperren intern weiterhin.'),
Textarea::make('echo_notes')->label('Nachweis / Beobachtung zum Rückkopplungsverhalten')->maxLength(4000)->columnSpanFull(),
DateTimePicker::make('portal_verified_at')->label('Tatsächliche Übernahme im Portal zuletzt persönlich geprüft')->seconds(false)
->helperText('Nur nach Sichtkontrolle im Portal eintragen. Wird durch einen Feedabruf nicht automatisch gesetzt.'),
Textarea::make('operating_notes')->label('Zusätzliche Anforderungen dieses Portals')->maxLength(4000)->columnSpanFull()
->helperText('Zum Beispiel eine zusätzliche Bestätigung, dass der Belegungskalender gepflegt ist.'),
TextInput::make('settings.email_senders')
->label('Absender der Buchungs-E-Mails (Schnellerkennung)')
->helperText('Komma-getrennt, z. B. „fewo-direkt.de, vrbo.com“. Buchungsbestätigungen dieser Absender werden sofort gesperrt.')
->maxLength(500)
->columnSpanFull(),
Toggle::make('requires_manual_blocking')
->label('Zusätzlich von Hand sperren (Sofortbuchung)')
->helperText('Bei jeder Belegung über andere Wege entsteht eine Aufgabe „Im Portal sperren“ – für Portale, die unseren Kalender zu selten abholen.')
->live()
->columnSpanFull(),
TextInput::make('manage_url')
->label('Link zum Kalender im Vermieterbereich')
->url()
->maxLength(2048)
->visible(fn (Get $get): bool => (bool) $get('requires_manual_blocking'))
->columnSpanFull(),
]),
...self::websiteSections(),
]);
}
/**
* The own website's entry (v0.11 channel manager): only the settings of requests from the website. Empty fields
* follow the defaults (System › So arbeite ich); there is no calendar connection.
*
* @return list<Section>
*/
private static function websiteSections(): array
{
$defaults = (array) (Settings::tenant()?->process_defaults ?? []);
$inherited = function (ProcessSetting $setting) use ($defaults): string {
$value = $setting->normalize($defaults[$setting->value] ?? null) ?? $setting->default();
return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value);
};
$settings = array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array(IntakeKind::Inquiry, $setting->channelIntakes(), true)));
return [
Section::make('Anfragen über die eigene Webseite')
->description('Nur ausfüllen, was für Anfragen über Ihre Webseite anders sein soll als in Ihren Standardeinstellungen (System › So arbeite ich). Telefon- und E-Mail-Anfragen folgen weiter den Standardeinstellungen.')
->columns(2)
->columnSpanFull()
->visible(fn (?Channel $record): bool => $record?->isWebsite() ?? false)
->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settings, $inherited)),
];
}
/**
* What a contract template brings along, shown under the template choice.
*/
@@ -127,7 +160,7 @@ private static function processSections(): array
return $setting === ProcessSetting::ContractTemplate ? 'Vorlage der Wohnung' : $setting->describe($value);
};
$settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array($intake, $setting->channelIntakes(), true)));
$settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => $setting !== ProcessSetting::FormRequiresAddress && in_array($intake, $setting->channelIntakes(), true)));
return [
Section::make('Anfragen über dieses Portal')
@@ -46,6 +46,7 @@ public static function configure(Table $table, ?Property $owner = null): Table
TextColumn::make('property.name')->label('Wohnung')->visible($owner === null)->searchable()->color('gray')->wrap(),
TextColumn::make('channel_state')->label('Status')->badge()->wrap()
->state(fn (Channel $record): string => match (true) {
$record->isWebsite() => 'Eigene Webseite – nur Einstellungen',
! $record->importsOccupations() => $record->status->getLabel(),
$record->last_error !== null => 'Importfehler',
$record->last_success_at === null => 'Erster Import ausstehend',
@@ -53,6 +54,7 @@ public static function configure(Table $table, ?Property $owner = null): Table
default => $record->status->getLabel(),
})
->color(fn (Channel $record): string => match (true) {
$record->isWebsite() => 'info',
! $record->is_active => 'gray',
! $record->importsOccupations() => 'success',
$record->last_error !== null => 'danger',
@@ -62,12 +64,12 @@ public static function configure(Table $table, ?Property $owner = null): Table
})
->description(fn (Channel $record): ?string => $record->review_count || count($record->sync_warnings ?? []) ? 'Prüffälle: '.$record->review_count.' · Hinweise: '.count($record->sync_warnings ?? []) : null)
->tooltip(fn (Channel $record): ?string => $record->last_error),
TextColumn::make('directions')->label('Richtungen')->color('gray')->wrap()
TextColumn::make('directions')->label('Richtungen')->color('gray')->wrap()->hidden(fn (?Channel $record): bool => $record?->isWebsite() ?? false)
->state(fn (Channel $record): string => ($record->importsOccupations() ? 'Import aktiv' : 'Import aus').' · '.($record->exportsOccupations() ? 'Export aktiv' : ($record->export_snapshot_at ? 'Export eingefroren' : 'Export aus'))),
TextColumn::make('last_sync')->label('Letzter Sync-Lauf')->wrap()
TextColumn::make('last_sync')->label('Letzter Sync-Lauf')->wrap()->hidden(fn (?Channel $record): bool => $record?->isWebsite() ?? false)
->state(fn (Channel $record): string => 'Letzter Sync: '.($record->last_synced_at?->format('d.m.Y H:i') ?? 'noch kein Lauf'))
->description(fn (Channel $record): ?string => $record->last_error !== null ? 'Letzter Lauf mit Fehler' : null),
TextColumn::make('last_export_request')->label('Letzter Kalenderabruf')->wrap()->color('gray')
TextColumn::make('last_export_request')->label('Letzter Kalenderabruf')->wrap()->color('gray')->hidden(fn (?Channel $record): bool => $record?->isWebsite() ?? false)
->state(fn (Channel $record): string => 'Letzter Abruf: '.($record->last_export_requested_at?->format('d.m.Y H:i') ?? 'noch keiner'))
->tooltip('Empfangener Aufruf dieses Kanalfeeds. Client und tatsächliche Übernahme im Portal sind damit nicht bestätigt.'),
])->space(2),
@@ -78,7 +80,7 @@ public static function configure(Table $table, ?Property $owner = null): Table
->successNotificationTitle('iCal-Verbindung angelegt – Exportlink automatisch erzeugt'),
] : [])
->recordActions([
Action::make('exportLink')->label('Exportlink')->icon(Heroicon::OutlinedLink)->button()
Action::make('exportLink')->label('Exportlink')->icon(Heroicon::OutlinedLink)->button()->visible(fn (Channel $record): bool => $record->isPortal())
->modalDescription('Diese Adresse erlaubt den Kalenderabruf. Nur dem vorgesehenen Portal geben. Ein Abruf beweist keine tatsächliche Übernahme.')
->schema([
TextEntry::make('export_url')->label('Vertrauliche Kalenderadresse')->state(fn (Channel $record): string => $record->exportUrl())->copyable()->wrap()->extraAttributes(['style' => 'overflow-wrap:anywhere']),
@@ -162,7 +164,7 @@ public static function configure(Table $table, ?Property $owner = null): Table
TextEntry::make('warnings'),
]),
]),
])->label('Weitere Aktionen')->icon(Heroicon::OutlinedEllipsisVertical),
])->label('Weitere Aktionen')->icon(Heroicon::OutlinedEllipsisVertical)->visible(fn (Channel $record): bool => $record->isPortal()),
]);
}
}
@@ -68,7 +68,7 @@ public static function form(Schema $schema): Schema
->label('Zusatzleistung / Portal')
->options(fn (Get $get): array => match ($get('condition_type')) {
ContractAnnex::EXTRA => Extra::query()->orderBy('name')->pluck('name', 'id')->all(),
ContractAnnex::CHANNEL => Channel::query()->orderBy('name')->pluck('name', 'id')->all(),
ContractAnnex::CHANNEL => Channel::query()->portals()->orderBy('name')->pluck('name', 'id')->all(),
default => [],
})
->visible(fn (Get $get): bool => in_array($get('condition_type'), [ContractAnnex::EXTRA, ContractAnnex::CHANNEL], true))
@@ -0,0 +1,228 @@
<?php
namespace App\Filament\Resources\InboundMessages;
use App\Actions\ContributeCaseFacts;
use App\Actions\CreateReservation;
use App\Actions\RequestCaseData;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\FactSource;
use App\Exceptions\ReservationException;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\InboundMessages\Pages\ListInboundMessages;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\InboundMessage;
use App\Models\Property;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Process\CaseRequirements;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* The inbox of v0.11 (CH-06, "Kommunikations-Klärungsansicht"): messages of the guest communication mailbox, with
* hints from known senders. The landlord assigns a message to a case, makes a new request out of it, or ignores it.
* Nothing here changes a booking by itself.
*/
class InboundMessageResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = InboundMessage::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedInboxArrowDown;
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $navigationLabel = 'Posteingang';
protected static ?string $modelLabel = 'Nachricht';
protected static ?string $pluralModelLabel = 'Posteingang';
protected static ?int $navigationSort = 7;
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = InboundMessage::query()->where('status', InboundMessage::NEEDS_REVIEW)->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function table(Table $table): Table
{
return $table
->defaultSort('received_at', 'desc')
->emptyStateHeading('Keine Nachrichten')
->emptyStateDescription('Sobald ein Postfach im Modus „Alle Nachrichten“ eingerichtet ist (System › Betrieb), erscheinen Gast-Mails hier.')
->columns([
TextColumn::make('received_at')->label('Eingang')->dateTime('d.m.Y H:i')->sortable(),
TextColumn::make('from_address')->label('Von')->description(fn (InboundMessage $record): ?string => $record->from_name)->searchable(),
TextColumn::make('subject')->label('Betreff')->wrap()->searchable(),
TextColumn::make('status')->label('Stand')->badge()->formatStateUsing(fn (InboundMessage $record): string => $record->statusLabel())
->color(fn (string $state): string => match ($state) {
InboundMessage::NEEDS_REVIEW => 'warning',
InboundMessage::ASSIGNED => 'info',
InboundMessage::PROCESSED, InboundMessage::PORTAL => 'success',
default => 'gray',
}),
TextColumn::make('booking.reference')->label('Vorgang')->url(fn (InboundMessage $record): ?string => $record->booking ? BookingResource::getUrl('view', ['record' => $record->booking]) : null),
IconColumn::make('test_mode')->label('Testbetrieb')->boolean()->trueIcon(Heroicon::OutlinedBeaker)->falseIcon(null)->tooltip('Im Testbetrieb eingegangen'),
])
->filters([
SelectFilter::make('status')->label('Stand')->options([
InboundMessage::NEEDS_REVIEW => 'zu klären', InboundMessage::ASSIGNED => 'zugeordnet', InboundMessage::PROCESSED => 'erledigt',
InboundMessage::PORTAL => 'Portal-Mail', InboundMessage::IGNORED => 'ignoriert',
]),
])
->recordActions([
Action::make('read')->label('Lesen')->icon(Heroicon::OutlinedEye)->button()
->modalHeading(fn (InboundMessage $record): string => (string) $record->subject)
->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->modalWidth('3xl')
->schema([
TextEntry::make('from')->label('Von')->state(fn (InboundMessage $record): string => trim(($record->from_name ? $record->from_name.' · ' : '').$record->from_address)),
TextEntry::make('hints_text')->label('Hinweise')->state(fn (InboundMessage $record): string => collect((array) $record->hints)->map(fn (array $hint): string => $hint['reference'].': '.$hint['why'])->implode(' · ') ?: 'keine')
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW),
TextEntry::make('proposals_text')->label('Erkannte Angaben (KI-Vorschläge)')
->state(fn (InboundMessage $record): HtmlString => new HtmlString(collect((array) ($record->extraction['proposed'] ?? []))
->map(fn (array $fact): string => e(CaseRequirements::label($fact['field']).': „'.$fact['value'].'“').($fact['problems'] !== [] ? ' <em>('.e(implode(', ', $fact['problems'])).')</em>' : ' <em>(unsicher)</em>'))
->implode('<br>') ?: '–'))
->visible(fn (InboundMessage $record): bool => ($record->extraction['proposed'] ?? []) !== []),
TextEntry::make('applied_text')->label('Automatisch übernommen')
->state(fn (InboundMessage $record): string => collect((array) ($record->extraction['applied'] ?? []))->map(fn (array $fact): string => CaseRequirements::label($fact['field']).': „'.$fact['value'].'“')->implode(' · '))
->visible(fn (InboundMessage $record): bool => ($record->extraction['applied'] ?? []) !== []),
TextEntry::make('body_text')->label('Nachricht')->state(fn (InboundMessage $record): HtmlString => new HtmlString(nl2br(e((string) $record->body)))),
]),
Action::make('assign')->label('Vorgang zuordnen')->icon(Heroicon::OutlinedLink)
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
->schema([
Select::make('booking_id')->label('Vorgang')->required()->searchable()
->options(fn (InboundMessage $record): array => self::caseOptions($record)),
])
->action(function (InboundMessage $record, array $data, RequestCaseData $requests): void {
$booking = Booking::query()->findOrFail($data['booking_id']);
$record->update(['status' => InboundMessage::ASSIGNED, 'booking_id' => $booking->id, 'match_reason' => 'landlord']);
CaseLog::record($booking, 'mail_in', 'E-Mail von Ihnen zugeordnet: '.$record->subject);
$requests->replyReceived($booking);
BookingTask::openOnce($booking, BookingTaskKind::InboundReview, 'm'.$record->id, ['due_on' => today(), 'note' => '„'.mb_substr((string) $record->subject, 0, 120).'“ – im Posteingang ansehen.']);
Notification::make()->title('Zugeordnet')->success()->send();
}),
Action::make('createInquiry')->label('Als neue Anfrage anlegen')->icon(Heroicon::OutlinedPlus)
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
->modalDescription('Es entsteht eine unverbindliche Anfrage wie über die Webseite; der Gast erhält die übliche Eingangsbestätigung bzw. Rückfrage. Termine und Personenzahl bitte aus der Nachricht übernehmen.')
->fillForm(fn (InboundMessage $record): array => [
'property_id' => Property::query()->orderBy('id')->value('id'),
'email' => $record->from_address,
'first_name' => str($record->from_name ?? '')->before(' ')->toString(),
'last_name' => str($record->from_name ?? '')->after(' ')->toString(),
'guests' => 2,
])
->schema([
Select::make('property_id')->label('Wohnung')->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())->required(),
DatePicker::make('arrival')->label('Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->required()->after('arrival'),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->required(),
TextInput::make('first_name')->label('Vorname')->required(),
TextInput::make('last_name')->label('Nachname')->required(),
TextInput::make('email')->label('E-Mail')->email()->required(),
])
->action(function (InboundMessage $record, array $data, CreateReservation $create): void {
try {
$booking = $create->handle(Property::query()->findOrFail($data['property_id']), new StayRequest(CarbonImmutable::parse($data['arrival']), CarbonImmutable::parse($data['departure']), (int) $data['guests']),
['first_name' => $data['first_name'], 'last_name' => $data['last_name'], 'email' => $data['email']], mb_substr((string) $record->body, 0, 2000), source: 'email');
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$record->update(['status' => InboundMessage::PROCESSED, 'booking_id' => $booking->id, 'match_reason' => 'new_request', 'processed_at' => now()]);
Notification::make()->title('Anfrage '.$booking->reference.' angelegt')->success()->send();
}),
Action::make('applyProposals')->label('Vorschläge übernehmen')->icon(Heroicon::OutlinedCheckBadge)
->visible(fn (InboundMessage $record): bool => $record->booking_id !== null && ($record->extraction['proposed'] ?? []) !== [])
->modalDescription('Nur übernehmen, was Sie in der Nachricht selbst geprüft haben. Zeitraum und Personenzahl ändern Sie über „Buchung ändern“ bzw. ein neues Angebot.')
->schema([
CheckboxList::make('fields')->label('Angaben')->required()
->options(fn (InboundMessage $record): array => collect((array) ($record->extraction['proposed'] ?? []))
->reject(fn (array $fact): bool => in_array($fact['field'], ContributeCaseFacts::STAY_FIELDS, true))
->mapWithKeys(fn (array $fact): array => [$fact['field'] => CaseRequirements::label($fact['field']).': „'.$fact['value'].'“'])->all()),
])
->action(function (InboundMessage $record, array $data, ContributeCaseFacts $facts): void {
$chosen = collect((array) ($record->extraction['proposed'] ?? []))->whereIn('field', $data['fields']);
$result = $facts->handle($record->booking, $chosen->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['value']])->all(), FactSource::Landlord, [
'inbound_message_id' => $record->id,
'reference' => 'message-landlord:'.$record->id,
'evidence' => $chosen->mapWithKeys(fn (array $fact): array => [$fact['field'] => $fact['evidence']])->all(),
]);
$record->update(['extraction' => [...(array) $record->extraction, 'proposed' => collect((array) ($record->extraction['proposed'] ?? []))->whereNotIn('field', $data['fields'])->values()->all()]]);
Notification::make()->title('Übernommen')->body($result->summary())->success()->send();
}),
ActionGroup::make([
Action::make('done')->label('Als erledigt markieren')->icon(Heroicon::OutlinedCheck)
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::ASSIGNED)
->action(function (InboundMessage $record): void {
$record->update(['status' => InboundMessage::PROCESSED, 'processed_at' => now()]);
BookingTask::query()->where('booking_id', $record->booking_id)->where('kind', BookingTaskKind::InboundReview)->where('subject', 'm'.$record->id)->where('status', BookingTaskStatus::Open)
->get()->each(fn (BookingTask $task): bool => $task->forceFill(['status' => BookingTaskStatus::Done, 'completed_at' => now(), 'completed_by' => auth()->user()?->name])->save());
}),
Action::make('ignore')->label('Ignorieren')->icon(Heroicon::OutlinedEyeSlash)->color('gray')
->visible(fn (InboundMessage $record): bool => $record->status === InboundMessage::NEEDS_REVIEW)
->action(fn (InboundMessage $record) => $record->update(['status' => InboundMessage::IGNORED, 'processed_at' => now()])),
]),
]);
}
/**
* Cases to assign a message to: the hints first, then the open cases.
*
* @return array<int, string>
*/
public static function caseOptions(InboundMessage $message): array
{
$hinted = collect((array) $message->hints)->pluck('booking_id')->all();
return Booking::query()->with('guest')
->where(fn (Builder $query) => $query->whereKey($hinted)->orWhereNotIn('status', [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed]))
->orderByRaw('CASE WHEN id IN ('.(implode(',', array_map('intval', $hinted)) ?: '0').') THEN 0 ELSE 1 END')->orderBy('arrival')
->limit(100)->get()
->mapWithKeys(fn (Booking $booking): array => [$booking->id => $booking->reference.' · '.$booking->guestName().' · '.$booking->arrival->format('d.m.').'–'.$booking->departure->format('d.m.Y')])
->all();
}
public static function getPages(): array
{
return ['index' => ListInboundMessages::route('/')];
}
}
@@ -0,0 +1,16 @@
<?php
namespace App\Filament\Resources\InboundMessages\Pages;
use App\Filament\Resources\InboundMessages\InboundMessageResource;
use Filament\Resources\Pages\ListRecords;
class ListInboundMessages extends ListRecords
{
protected static string $resource = InboundMessageResource::class;
public function getSubheading(): ?string
{
return 'Nachrichten aus Ihrem Postfach für die Gästekommunikation. Zugeordnet wird nur über einen sicheren Bezug (Antwort auf unsere Mail, Vorgangsnummer und Absender, oder Absender mit Wohnung und Zeitraum). Alles andere wartet hier auf Sie; eine Nachricht legt nie selbst einen Vorgang an.';
}
}
@@ -70,7 +70,7 @@ public static function table(Table $table): Table
TextColumn::make('missing')->label('Fehlt noch')->state(fn (IntakeObservation $record): string => implode(', ', (array) $record->missing))->placeholder('–')->wrap()->toggleable(isToggledHiddenByDefault: true),
])
->filters([
SelectFilter::make('channel_id')->label('Portal')->options(fn (): array => Channel::query()->orderBy('name')->pluck('name', 'id')->all()),
SelectFilter::make('channel_id')->label('Portal')->options(fn (): array => Channel::query()->portals()->orderBy('name')->pluck('name', 'id')->all()),
SelectFilter::make('outcome')->label('Ergebnis')->options(IntakeOutcome::class),
SelectFilter::make('applied')->label('Ausgeführt')->options(['1' => 'ja', '0' => 'nur protokolliert']),
]);
@@ -217,7 +217,7 @@ public static function classificationAction(): Action
->visible(fn (Get $get): bool => in_array($get('occupation_kind'), [OccupationKind::Block, OccupationKind::Block->value], true)),
Select::make('origin_channel_id')->label('Buchungskanal, sofern persönlich bekannt')->placeholder('Unbekannt')
->helperText('Privat bezeichnet den fachlichen Ursprung. Der Importkanal bleibt als Kalenderquelle erhalten.')
->options(fn (BlockedPeriod $record): array => ['private' => 'Privat'] + Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all()),
->options(fn (BlockedPeriod $record): array => ['private' => 'Privat'] + Channel::query()->portals()->where('property_id', $record->property_id)->pluck('name', 'id')->all()),
])->action(function (BlockedPeriod $record, array $data, ClassifyPortalOccupation $classify): void {
$private = ($data['origin_channel_id'] ?? null) === 'private';
$classify->handle($record, $data['occupation_kind'] instanceof OccupationKind ? $data['occupation_kind'] : OccupationKind::from($data['occupation_kind']), ! $private && filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null, [
+1 -1
View File
@@ -25,7 +25,7 @@ class ChannelController extends Controller
{
public function feed(string $token, ICalExport $feed, Request $request): Response
{
$channel = Channel::query()->where(fn ($query) => $query->where('export_token', $token)
$channel = Channel::query()->portals()->where(fn ($query) => $query->where('export_token', $token)
->orWhere(fn ($previous) => $previous->where('previous_export_token', $token)->where('previous_export_token_expires_at', '>', now())))->firstOrFail();
abort_unless($channel->servesItsLandlord(), 404);
@@ -0,0 +1,150 @@
<?php
namespace App\Http\Controllers;
use App\Actions\ContributeCaseFacts;
use App\Actions\RequestCaseData;
use App\Enums\BookingStatus;
use App\Enums\FactSource;
use App\Models\Booking;
use App\Models\CaseFact;
use App\Models\DataRequest;
use App\Process\CaseRequirements;
use App\Support\Countries;
use DateTimeInterface;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\URL;
use Illuminate\View\View;
/**
* The guest's page to complete missing details (v0.11, CH-18, signed link from the data request): no account, the link
* belongs to one case, one request and its current version. Opening it changes nothing; it shows only the details that
* are asked for and what the guest gave for this case himself. Sending goes through the common fact intake – the same
* form twice is harmless, a differing value never overwrites a stored one, and nothing binding happens here.
*/
class GuestDataController extends Controller
{
public function show(Request $request, Booking $booking): View
{
$booking->loadMissing(['guest', 'property']);
[$dataRequest, $problem] = $this->current($request, $booking);
$fields = $problem === null ? $this->fields($dataRequest, $booking) : [];
return view('guest-data', [
'booking' => $booking,
'problem' => $problem,
'fields' => $fields,
'values' => $this->ownValues($booking, $fields),
'clarification' => $booking->clarificationState(),
'purpose' => $dataRequest?->purpose,
'submitUrl' => $problem === null ? $this->signed($booking, 'guest-data.submit', now()->addHour(), $dataRequest) : null,
]);
}
public function submit(Request $request, Booking $booking, ContributeCaseFacts $facts): RedirectResponse
{
$booking->loadMissing('guest');
[$dataRequest, $problem] = $this->current($request, $booking);
$back = $dataRequest !== null ? $this->signed($booking, 'guest-data.show', now()->addDays(2), $dataRequest) : url()->previous();
if ($problem !== null) {
return redirect()->to($back)->with('guest-data.error', $problem);
}
$fields = $this->fields($dataRequest, $booking);
$rules = [];
foreach ($fields as $field) {
$rules[$this->input($field)] = match ($field) {
'guest.country' => ['nullable', 'in:'.implode(',', array_keys(Countries::options()))],
'guest.email' => ['nullable', 'email', 'max:255'],
'booking.guests' => ['nullable', 'integer', 'min:1', 'max:'.$booking->property->max_guests],
default => ['nullable', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'],
};
}
$input = $request->validate($rules, [], collect($fields)->mapWithKeys(fn (string $field): array => [$this->input($field) => CaseRequirements::label($field)])->all());
$given = collect($fields)->mapWithKeys(fn (string $field): array => [$field => $input[$this->input($field)] ?? null])->filter(fn (mixed $value): bool => filled($value))->all();
if ($given === []) {
return redirect()->to($back)->with('guest-data.error', 'Bitte füllen Sie mindestens eines der Felder aus.');
}
$result = $facts->handle($booking, $given, FactSource::GuestLink, [
'reference' => 'link:r'.$dataRequest->id.':v'.$dataRequest->link_version.':'.hash('sha256', json_encode($given)),
'actor' => 'Gast über den Ergänzungslink',
]);
$booking->refresh();
$stillMissing = RequestCaseData::needs($booking)['fields'] ?? [];
return redirect()->to($back)->with('guest-data.success', match (true) {
$result->isEmpty() => 'Diese Angaben liegen uns bereits vor – vielen Dank.',
$result->needsReview() => 'Vielen Dank! Einige Angaben weichen von unseren Unterlagen ab; wir prüfen sie und melden uns bei Bedarf.',
$stillMissing !== [] => 'Vielen Dank! Es fehlen noch: '.implode(', ', CaseRequirements::labels($stillMissing)).'.',
default => 'Vielen Dank – Ihre Angaben sind vollständig. Wir melden uns in Kürze per E-Mail.',
});
}
/**
* The request this link belongs to and why the link cannot be used (or null).
*
* @return array{0: ?DataRequest, 1: ?string}
*/
private function current(Request $request, Booking $booking): array
{
$dataRequest = $booking->dataRequests()->whereKey((int) $request->query('r'))->first();
if ($dataRequest === null) {
return [null, 'Dieser Link gehört nicht zu dieser Anfrage.'];
}
if ((int) $request->query('v') !== $dataRequest->link_version) {
return [$dataRequest, 'Dieser Link ist nicht mehr aktuell – wir haben Ihnen inzwischen eine neuere Nachricht gesendet. Bitte verwenden Sie den Link aus der neuesten E-Mail.'];
}
if (RequestCaseData::needs($booking) === null) {
return [$dataRequest, in_array($booking->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true)
? 'Diese Anfrage ist abgeschlossen. Gern können Sie über unsere Webseite neu anfragen.'
: 'Vielen Dank – uns liegen alle Angaben vor. Sie müssen nichts weiter tun.'];
}
return [$dataRequest, null];
}
/**
* The details asked for now, plus the phone number as an optional extra.
*
* @return list<string>
*/
private function fields(?DataRequest $dataRequest, Booking $booking): array
{
$needed = RequestCaseData::needs($booking)['fields'] ?? (array) $dataRequest?->fields;
return array_values(array_unique([...$needed, ...(blank($booking->guest?->phone) ? ['guest.phone'] : [])]));
}
/**
* Pre-filled values: only what this guest gave for this case himself (minimal insight, CH-18), and Germany as a
* changeable default of the country (B4).
*
* @param list<string> $fields
* @return array<string, string>
*/
private function ownValues(Booking $booking, array $fields): array
{
$own = CaseFact::query()->where('booking_id', $booking->id)->whereIn('field', $fields)
->whereIn('source', [FactSource::GuestLink, FactSource::WebsiteForm])->whereIn('outcome', [CaseFact::APPLIED, CaseFact::CONFIRMED])
->orderBy('id')->get()->mapWithKeys(fn (CaseFact $fact): array => [$fact->field => (string) $fact->value])->all();
return in_array('guest.country', $fields, true) && ! isset($own['guest.country']) ? [...$own, 'guest.country' => Countries::DEFAULT] : $own;
}
private function input(string $field): string
{
return str_replace('.', '_', $field);
}
private function signed(Booking $booking, string $name, DateTimeInterface $expiration, DataRequest $dataRequest): string
{
$parameters = ['booking' => $booking, 'r' => $dataRequest->id, 'v' => $dataRequest->link_version];
return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters)
?? URL::temporarySignedRoute($name, $expiration, $parameters);
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Listeners;
use App\Actions\RequestCaseData;
use App\Events\CaseFactsContributed;
use App\Models\CaseFact;
use Throwable;
/**
* After details arrived for a case, the running data request learns about it: reminders stop, a follow-up question is
* planned or the request ends (CH-17). A problem here never undoes the details that were taken over.
*/
class ContinueDataRequest
{
public function __construct(private RequestCaseData $requests) {}
public function handle(CaseFactsContributed $event): void
{
try {
$this->requests->answered($event->booking, $event->contribution, $event->source);
// Now the guest can be written to: ask for what is still missing (e.g. a portal booking's address).
if (in_array('guest.email', $event->contribution->fields(CaseFact::APPLIED), true) && $event->booking->openDataRequest() === null) {
$this->requests->forNextStep($event->booking->refresh());
}
} catch (Throwable $exception) {
report($exception);
}
}
}
+14
View File
@@ -15,6 +15,18 @@
*/
class LogBookingMail
{
/**
* The Message-ID header as sent (not the transport's id), with angle brackets as replies quote it.
*/
public static function messageId(MessageSent $event): ?string
{
// The raw message as it went out carries the header; the transport's own id may differ (SMTP queue ids).
$raw = $event->sent->getSymfonySentMessage()->getMessage()->toString();
$headers = substr($raw, 0, (int) (strpos($raw, "\r\n\r\n") ?: strlen($raw)));
return preg_match('/^Message-ID:\s*(<[^>\r\n]+>)/mi', $headers, $match) ? $match[1] : null;
}
public function handle(MessageSent $event): void
{
try {
@@ -33,6 +45,8 @@ public function handle(MessageSent $event): void
'booking_id' => $booking->id,
'audience' => $audience,
'subject' => mb_substr((string) $event->message->getSubject(), 0, 255),
// v0.11: the Message-ID lets a reply be assigned to its case (CH-13, "bekannter Antwortbezug").
'message_id' => rescue(fn (): ?string => self::messageId($event), null, false),
'sent_at' => now(),
]);
} catch (Throwable) {
+24 -5
View File
@@ -6,7 +6,6 @@
use App\Actions\RequestMarketingConsent;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ReferralSource;
use App\Exceptions\ReservationException;
use App\Models\Booking;
@@ -17,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;
@@ -65,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;
@@ -106,13 +109,23 @@ 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).
*/
#[Computed]
public function reservesDates(): bool
{
return app(ProcessSettings::class)->resolve($this->property, null, IntakeKind::Inquiry)->preReservation();
return app(ProcessSettings::class)->forWebsite($this->property)->preReservation();
}
/**
@@ -262,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],
@@ -329,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.');
@@ -354,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',
];
}
+66
View File
@@ -0,0 +1,66 @@
<?php
namespace App\Mail;
use App\Actions\RequestCaseData;
use App\Models\Booking;
use App\Models\DataRequest;
use App\Process\CaseRequirements;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Mail\Mailables\Address;
use Illuminate\Mail\Mailables\Content;
use Illuminate\Mail\Mailables\Envelope;
use Illuminate\Queue\SerializesModels;
/**
* The question for missing details (v0.11, S4): first question, targeted follow-up or reminder, with the guest's link.
* What it says about the dates follows the real state of the case at the moment of sending (CH §2a table): no hold,
* a clarification hold until its real end, an expired one, or a booking that is already binding – never the
* configured value. The guest may also simply answer the e-mail.
*/
class DataRequested extends Mailable
{
use Queueable, SerializesModels;
/** @var array{state: 'none'|'active'|'expired', until: ?CarbonImmutable} */
public array $clarification;
/** @var list<string> */
public array $missing;
public function __construct(public Booking $booking, public DataRequest $request, public string $kind, public string $url)
{
$this->clarification = $booking->clarificationState();
$this->missing = CaseRequirements::labels($request->fields);
}
public function envelope(): Envelope
{
$subject = $this->request->purpose === RequestCaseData::FOR_BOOKING ? 'Ihre Buchung '.$this->booking->reference : 'Ihre Anfrage '.$this->booking->reference;
return new Envelope(
subject: match ($this->kind) {
DataRequest::REMINDER => 'Erinnerung – '.$subject.': Es fehlen noch Angaben',
DataRequest::FOLLOWUP => $subject.': Noch eine kurze Rückfrage',
default => $subject.': Bitte ergänzen Sie Ihre Angaben',
},
// Answers go to the dedicated mailbox when one is read completely (v0.11 inbox), so they reach the case.
replyTo: [new Address(self::replyAddress(), config('fewo.owner.name'))],
);
}
public static function replyAddress(): string
{
$mailbox = Settings::tenant()?->activeMailbox();
return $mailbox?->readsEverything() && filled($mailbox->address) ? (string) $mailbox->address : (string) config('fewo.owner.email');
}
public function content(): Content
{
return new Content(markdown: 'mail.data-requested');
}
}
+5 -1
View File
@@ -22,7 +22,11 @@ public function __construct(public Booking $booking) {}
public function envelope(): Envelope
{
return new Envelope(
subject: 'Ihre Anfrage '.$this->booking->reference.($this->booking->isHoldActive() ? ' – Termin vorgemerkt, Angebot folgt' : ' – Eingang bestätigt, Angebot folgt'),
subject: 'Ihre Anfrage '.$this->booking->reference.match (true) {
$this->booking->isHoldActive() && $this->booking->hold_purpose === Booking::HOLD_CLARIFICATION => ' – Eingang bestätigt, vorläufig reserviert',
$this->booking->isHoldActive() => ' – Termin vorgemerkt, Angebot folgt',
default => ' – Eingang bestätigt, Angebot folgt',
},
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
);
}
+40
View File
@@ -18,6 +18,7 @@
use App\Process\CaseRecorder;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Database\Factories\BookingFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
@@ -71,6 +72,7 @@
'balance_due_on',
'contract_path',
'hold_expires_at',
'hold_purpose',
'offer_version',
'offer_sent_at',
'offer_message',
@@ -118,6 +120,12 @@ class Booking extends Model
public const DIRECT_SOURCES = ['website', 'manual', 'phone', 'direct', 'email', 'internal'];
/** The hold of a request or an offer (unchanged behaviour of v0.10). */
public const HOLD_OFFER = 'offer';
/** The short hold of an incomplete request while details are fetched (v0.11, E-033). */
public const HOLD_CLARIFICATION = 'clarification';
public function isDirect(): bool
{
return $this->import_channel_id === null && $this->origin_channel_id === null && in_array($this->source, self::DIRECT_SOURCES, true);
@@ -511,11 +519,43 @@ public function canBeArchived(): bool
|| ($this->departure->isPast() && in_array($this->status, BookingStatus::occupying(), true));
}
/** @return HasMany<DataRequest, $this> */
public function dataRequests(): HasMany
{
return $this->hasMany(DataRequest::class)->latest('id');
}
/**
* The request for missing details that still runs (at most one per case, CH-17).
*/
public function openDataRequest(): ?DataRequest
{
return $this->dataRequests()->whereIn('status', DataRequest::RUNNING)->first();
}
public function isHoldActive(): bool
{
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
}
/**
* The real state of the clarification hold, for what the guest may be told (v0.11, CH §2a table): none (setting 0,
* not qualified, or no clarification at all), active until a real point in time, or expired. Only this – never the
* configured value – may be put into a message.
*
* @return array{state: 'none'|'active'|'expired', until: ?CarbonImmutable}
*/
public function clarificationState(): array
{
if ($this->hold_purpose !== self::HOLD_CLARIFICATION || $this->hold_expires_at === null) {
return ['state' => 'none', 'until' => null];
}
return $this->isHoldActive()
? ['state' => 'active', 'until' => $this->hold_expires_at]
: ['state' => 'expired', 'until' => $this->hold_expires_at];
}
/**
* The website this stay belongs to, regardless of which landlord is current.
*/
+1 -1
View File
@@ -11,7 +11,7 @@
/**
* An e-mail that went out for a booking (communication log). Only subject and audience are kept.
*/
#[Fillable(['booking_id', 'audience', 'subject', 'sent_at'])]
#[Fillable(['booking_id', 'audience', 'subject', 'message_id', 'sent_at'])]
class BookingMessage extends Model
{
public $timestamps = false;
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Models;
use App\Enums\FactSource;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One detail that arrived for a case, with its source and what became of it (v0.11, S5). Only appended, never
* changed: the evidence behind the values in guests and bookings.
*/
#[Fillable(['booking_id', 'field', 'value', 'previous_value', 'source', 'inbound_message_id', 'evidence', 'confidence', 'outcome', 'fingerprint', 'actor', 'created_at'])]
class CaseFact extends Model
{
use BelongsToTenant;
public const UPDATED_AT = null;
public const APPLIED = 'applied';
public const CONFIRMED = 'confirmed';
public const CONFLICT = 'conflict';
public const CHANGE_REQUEST = 'change_request';
public const REJECTED = 'rejected';
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'value' => 'encrypted',
'previous_value' => 'encrypted',
'evidence' => 'encrypted',
'source' => FactSource::class,
'confidence' => 'float',
'created_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Booking, $this>
*/
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',
};
}
}
+52 -5
View File
@@ -24,20 +24,26 @@
use Illuminate\Support\Str;
/**
* A sales channel (portal) of a property. Our system leads: occupations are imported from the
* channel and every channel gets its own export feed without its own occupations.
* A sales channel of a property. A portal (kind "portal"): our system leads, occupations are imported from the
* channel and every channel gets its own export feed without its own occupations. The own website (kind "website",
* v0.11 channel manager) only carries the settings for requests from the website: it is never synchronised,
* exported, monitored or given blocking tasks, and cases from the website stay direct (A1) without a channel.
*/
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides', 'case_intake'])]
#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id', 'contract_template_reservation_id', 'process_overrides', 'case_intake', 'kind'])]
#[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])]
class Channel extends Model
{
/** @use HasFactory<ChannelFactory> */
use BelongsToTenant, HasFactory;
public const KIND_PORTAL = 'portal';
public const KIND_WEBSITE = 'website';
protected $attributes = [
'status' => 'setup', 'booking_model' => 'mixed', 'import_enabled' => false,
'export_enabled' => false, 'export_mode' => 'test',
'echo_behavior' => 'unverified', 'case_intake' => 'off',
'echo_behavior' => 'unverified', 'case_intake' => 'off', 'kind' => self::KIND_PORTAL,
];
protected static function booted(): void
@@ -138,7 +144,48 @@ public function tasks(): HasMany
#[Scope]
protected function active(Builder $query): Builder
{
return $query->where('is_active', true)->where('status', ChannelStatus::Active);
return $query->where('is_active', true)->where('status', ChannelStatus::Active)->where('kind', self::KIND_PORTAL);
}
/**
* Portals only (active or not) – everything except the own website's settings entry.
*
* @param Builder<Channel> $query
* @return Builder<Channel>
*/
#[Scope]
protected function portals(Builder $query): Builder
{
return $query->where('kind', self::KIND_PORTAL);
}
public function isWebsite(): bool
{
return $this->kind === self::KIND_WEBSITE;
}
public function isPortal(): bool
{
return ! $this->isWebsite();
}
/**
* The settings entry of the property's own website, created on first use.
*/
public static function websiteOf(Property $property): self
{
return self::withoutGlobalScopes()->firstOrCreate(
['property_id' => $property->id, 'kind' => self::KIND_WEBSITE],
['tenant_id' => $property->tenant_id, 'name' => 'Eigene Webseite', 'connector' => self::KIND_WEBSITE, 'status' => ChannelStatus::Active, 'booking_model' => ChannelBookingModel::Inquiry],
);
}
/**
* The settings entry of the property's own website if there is one (no write, for resolving settings).
*/
public static function existingWebsiteOf(Property $property): ?self
{
return self::withoutGlobalScopes()->where('property_id', $property->id)->where('kind', self::KIND_WEBSITE)->first();
}
public function connector(): ChannelConnector
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Models;
use App\Enums\DataRequestMode;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* One coherent request for missing details of a case (v0.11, CH-16/17): at most one is open per case. Follow-up
* questions and reminders have separate counters that a partial answer never resets; the answer deadline is not a
* reservation deadline.
*/
#[Fillable(['booking_id', 'status', 'mode', 'purpose', 'fields', 'followups_sent', 'reminders_sent', 'link_version', 'last_message', 'last_sent_at', 'response_due_at', 'next_reminder_at', 'answered_at', 'closed_at', 'closed_reason'])]
class DataRequest extends Model
{
use BelongsToTenant;
/** Prepared, waits for the landlord's release. */
public const DRAFT = 'draft';
/** Sent; the guest is asked and may be reminded. */
public const OPEN = 'open';
/** The landlord asks himself (no automatic message), or the limits were reached. */
public const MANUAL = 'manual';
/** Every requested detail is there. */
public const COMPLETED = 'completed';
/** Ended without the details (case closed, landlord stopped it). */
public const STOPPED = 'stopped';
/** Statuses of a request that still runs. */
public const RUNNING = [self::DRAFT, self::OPEN, self::MANUAL];
/** First question. */
public const INITIAL = 'initial';
/** Targeted follow-up question after a partial or unclear answer. */
public const FOLLOWUP = 'followup';
/** Reminder when no answer came. */
public const REMINDER = 'reminder';
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'mode' => DataRequestMode::class,
'fields' => 'array',
'last_sent_at' => 'immutable_datetime',
'response_due_at' => 'immutable_datetime',
'next_reminder_at' => 'immutable_datetime',
'answered_at' => 'immutable_datetime',
'closed_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Booking, $this>
*/
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
public function isRunning(): bool
{
return in_array($this->status, self::RUNNING, true);
}
public function statusLabel(): string
{
return match ($this->status) {
self::DRAFT => 'Rückfrage vorbereitet – wartet auf Ihre Freigabe',
self::OPEN => 'beim Gast angefragt',
self::MANUAL => 'von Ihnen nachzufragen',
self::COMPLETED => 'alle Angaben da',
default => 'beendet',
};
}
}
+72
View File
@@ -0,0 +1,72 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A message read from the landlord's mailbox (v0.11, S2/S3), stored before anything is done with it. It is assigned
* to a case only by a reliable reference (CH-13); otherwise it waits in the inbox for the landlord. Being assigned is
* not yet permission to take anything over.
*/
#[Fillable(['mailbox_id', 'message_id', 'in_reply_to', 'references', 'from_address', 'from_name', 'to_addresses', 'subject', 'body', 'received_at', 'test_mode', 'status', 'booking_id', 'match_reason', 'hints', 'portal_email_id', 'extraction_status', 'extraction', 'processed_at'])]
class InboundMessage extends Model
{
use BelongsToTenant;
public const NEW = 'new';
/** Assigned to a case by a reliable reference. */
public const ASSIGNED = 'assigned';
/** Waits for the landlord: no or no reliable reference, or contradicting hints. */
public const NEEDS_REVIEW = 'needs_review';
/** A portal notification, handled by the existing portal path. */
public const PORTAL = 'portal';
public const IGNORED = 'ignored';
/** Done: details taken over or decided by the landlord. */
public const PROCESSED = 'processed';
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'body' => 'encrypted',
'references' => 'array',
'to_addresses' => 'array',
'hints' => 'array',
'extraction' => 'array',
'test_mode' => 'boolean',
'received_at' => 'immutable_datetime',
'processed_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Booking, $this>
*/
public function booking(): BelongsTo
{
return $this->belongsTo(Booking::class);
}
public function statusLabel(): string
{
return match ($this->status) {
self::ASSIGNED => 'einem Vorgang zugeordnet',
self::NEEDS_REVIEW => 'zu klären',
self::PORTAL => 'Portal-Mail',
self::IGNORED => 'ignoriert',
self::PROCESSED => 'erledigt',
default => 'neu',
};
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Models;
use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Model;
/**
* A landlord's IMAP mailbox (v0.11, CH-05). Several may exist, one is active. "portal_only" reads the portals'
* booking notifications as before; "full" reads every message of a mailbox dedicated to guest communication.
*/
#[Fillable(['label', 'host', 'port', 'encryption', 'username', 'password', 'folder', 'address', 'mode', 'is_active', 'last_fetched_at'])]
#[Hidden(['password'])]
class Mailbox extends Model
{
use BelongsToTenant;
public const PORTAL_ONLY = 'portal_only';
public const FULL = 'full';
/**
* @return array<string, string>
*/
protected function casts(): array
{
return [
'password' => 'encrypted',
'is_active' => 'boolean',
'port' => 'integer',
'last_fetched_at' => 'immutable_datetime',
];
}
public function readsEverything(): bool
{
return $this->mode === self::FULL;
}
/**
* Connection data in the form the reader expects, or null when it is not usable.
*
* @return array{host: string, port: int, encryption: string, username: string, password: ?string, folder: string}|null
*/
public function connection(): ?array
{
if (blank($this->host) || blank($this->username)) {
return null;
}
return [
'host' => (string) $this->host,
'port' => (int) ($this->port ?: 993),
'encryption' => (string) ($this->encryption ?: 'ssl'),
'username' => (string) $this->username,
'password' => $this->password,
'folder' => (string) ($this->folder ?: 'INBOX'),
];
}
}
+4 -1
View File
@@ -132,9 +132,12 @@ public function blockedPeriods(): HasMany
/**
* @return HasMany<Channel, $this>
*/
/**
* The portals of the property (the own website's settings entry is not a portal).
*/
public function channels(): HasMany
{
return $this->hasMany(Channel::class);
return $this->hasMany(Channel::class)->where('kind', Channel::KIND_PORTAL);
}
/**
+14
View File
@@ -123,6 +123,12 @@ public function serviceUsages(): HasMany
*/
public function mailbox(): ?array
{
// v0.11: the active mailbox record leads; the tenant columns remain the fallback until every system migrated.
$mailbox = $this->activeMailbox();
if ($mailbox !== null) {
return $mailbox->connection();
}
if (blank($this->mailbox_host) || blank($this->mailbox_username)) {
return null;
}
@@ -137,6 +143,14 @@ public function mailbox(): ?array
];
}
/**
* The landlord's active mailbox (at most one, CH-05).
*/
public function activeMailbox(): ?Mailbox
{
return Mailbox::query()->withoutGlobalScopes()->where('tenant_id', $this->id)->where('is_active', true)->orderBy('id')->first();
}
public function isLive(): bool
{
return $this->operating_mode === 'live';
+6 -3
View File
@@ -7,10 +7,11 @@
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A service the operator switched on for a landlord. The own API key is optional and stored encrypted;
* an empty key means that the operator's key applies (no service calls it yet).
* A service the operator switched on for a landlord. A service that calls an external provider uses the landlord's
* own access (bring your own key, v0.11): the key is stored encrypted and never shown again; provider and models are
* in settings, the result of the last check beside them.
*/
#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key'])]
#[Fillable(['tenant_id', 'service', 'is_enabled', 'api_key', 'settings', 'check_status', 'check_message', 'checked_at'])]
class TenantService extends Model
{
/** @var list<string> */
@@ -24,6 +25,8 @@ protected function casts(): array
return [
'is_enabled' => 'boolean',
'api_key' => 'encrypted',
'settings' => 'array',
'checked_at' => 'immutable_datetime',
];
}
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace App\Policies;
use App\Enums\Permission;
/**
* The inbox of guest messages belongs to handling the bookings.
*/
class InboundMessagePolicy extends RolePolicy
{
protected function permission(): Permission
{
return Permission::Bookings;
}
}
+31 -5
View File
@@ -20,6 +20,7 @@
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\ChannelTask;
use App\Models\DataRequest;
use App\Pricing\CaseMoney;
use App\Support\Money;
use Carbon\CarbonImmutable;
@@ -64,14 +65,32 @@ 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) : [];
$request = $booking->openDataRequest();
$asked = $booking->contact_requested_at !== null || $request?->status === DataRequest::OPEN;
$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)).($request !== null ? ' · '.$request->statusLabel() : ($asked ? ' · beim Gast angefragt' : '')),
$booking->contact_requested_at !== null => 'beim Gast erfragt am '.$booking->contact_requested_at->format('d.m.Y'),
default => 'fehlt noch',
};
// A prepared data request waits for the landlord's release: that is the next step, otherwise entering the details.
$draft = $needsDetails && $request?->status === DataRequest::DRAFT;
$activities[] = new Activity('contact', $title, $later($draft ? ActivityState::Open : $state), $detail, $state === ActivityState::Done ? null : ($draft ? 'approveDataRequest' : 'provideContact'));
}
if ($inquiry && ! $profile->preReservation() && $booking->offer_version === 0) {
@@ -213,6 +232,12 @@ public static function for(Booking $booking): array
$activities[] = $profile->guestMessages() === Responsibility::Portal
? new Activity('arrival_info', 'Anreise-Informationen an den Gast', ActivityState::External, 'durch '.($booking->processChannel()?->name ?? 'das Portal').' (angekündigt) – eine Zustellung ist damit nicht nachgewiesen')
: new Activity('arrival_info', 'Anreise-Informationen an den Gast (automatisch)', $later($booking->arrival_info_sent_at !== null ? ActivityState::Done : ActivityState::Later), $booking->arrival_info_sent_at ? 'gesendet am '.$booking->arrival_info_sent_at->format('d.m.Y') : $profile->arrivalInfoDaysBefore().' Tage vor Anreise');
// v0.11: a binding booking (also from a portal) stays binding; missing administrative details are asked for
// alongside, after the steps of the booking itself.
if ($binding && ($bookingRequest = $booking->openDataRequest()) !== null) {
$activities[] = new Activity('data_request', 'Fehlende Angaben beim Gast anfragen', $later($bookingRequest->status === DataRequest::OPEN ? ActivityState::Waiting : ActivityState::Open),
implode(', ', CaseRequirements::labels($bookingRequest->fields)).' · '.$bookingRequest->statusLabel(), $bookingRequest->status === DataRequest::OPEN ? null : 'approveDataRequest');
}
$activities[] = new Activity('stay', 'Aufenthalt', $later(match (true) {
$left => ActivityState::Done,
$arrived => ActivityState::Waiting,
@@ -322,6 +347,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();
+138
View File
@@ -0,0 +1,138 @@
<?php
namespace App\Process;
use App\Models\Booking;
/**
* The details a case needs before an action (v0.11, G2a / E-032 / CH §1.3). The one place that knows the required
* details: before an own binding offer and before the binding confirmation of a booking wish the contracting party's
* first and last name, e-mail, full postal address including the country, the number of guests and the dates must be
* there. The information "unter Vorbehalt" needs none of them beyond what it needs today (B3). A missing address is
* a blocker that cannot be confirmed away.
*
* A pre-filled country of a form counts only when the guest sent it (B4); an empty field is never assumed.
*/
final class CaseRequirements
{
/** Own binding offer (A1/A2). */
public const OFFER = 'offer';
/** Binding confirmation of a booking wish after an information without hold (package 7). */
public const WISH_CONFIRMATION = 'wish_confirmation';
/** @var array<string, string> 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<string> 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<string> $fields
* @return list<string>
*/
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,
};
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Process;
use App\Models\CaseFact;
/**
* What became of the details given for a case in one contribution (v0.11, S5).
*/
final class FactContribution
{
/**
* @param list<CaseFact> $facts recorded facts (duplicates of an earlier contribution are not recorded again)
*/
public function __construct(public readonly array $facts = []) {}
/**
* @return list<string> 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);
}
}
+46
View File
@@ -3,6 +3,7 @@
namespace App\Process;
use App\Enums\CaseType;
use App\Enums\DataRequestMode;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
@@ -23,6 +24,9 @@ final class ProcessProfile
public const CHANNEL = 'channel';
/** The own website's entry of the channel manager (v0.11). */
public const WEBSITE = 'website';
/** Fixed by the case type (A6), not settable. */
public const CASE_TYPE = 'case_type';
@@ -104,6 +108,47 @@ public function arrivalInfoDaysBefore(): int
return max(1, (int) $this->value(ProcessSetting::ArrivalInfoDaysBefore));
}
public function dataRequestMode(): DataRequestMode
{
return DataRequestMode::tryFrom((string) $this->value(ProcessSetting::DataRequest)) ?? DataRequestMode::Approval;
}
/**
* Minutes of the clarification hold of an incomplete request (E-033): the value for automatic requests when the
* guest is asked automatically, otherwise the one for release or manual requests. 0 = no hold.
*/
public function clarificationHoldMinutes(): int
{
$setting = $this->dataRequestMode() === DataRequestMode::Automatic ? ProcessSetting::ClarificationHoldAutoMinutes : ProcessSetting::ClarificationHoldManualMinutes;
return max(0, (int) $this->value($setting));
}
public function remindersMax(): int
{
return max(0, (int) $this->value(ProcessSetting::DataRequestRemindersMax));
}
public function followupsMax(): int
{
return max(0, (int) $this->value(ProcessSetting::DataRequestFollowupsMax));
}
public function reminderHours(): int
{
return max(1, (int) $this->value(ProcessSetting::DataRequestReminderHours));
}
public function guestLinkValidDays(): int
{
return max(1, (int) $this->value(ProcessSetting::GuestLinkValidDays));
}
public function formRequiresAddress(): bool
{
return (bool) $this->value(ProcessSetting::FormRequiresAddress);
}
public function contractTemplateId(): ?int
{
$value = $this->value(ProcessSetting::ContractTemplate);
@@ -120,6 +165,7 @@ public static function sourceLabel(string $source): string
self::TENANT => 'Ihre Standardeinstellung',
self::PROPERTY => 'Abweichung der Wohnung',
self::CHANNEL => 'Abweichung des Portals',
self::WEBSITE => 'Einstellung der eigenen Webseite',
self::CASE_TYPE => 'fest für diese Vorgangsart',
'migration' => 'aus dem bisherigen Stand übernommen',
default => 'Grundeinstellung',
+16 -5
View File
@@ -28,7 +28,7 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
$levels = [
ProcessProfile::TENANT => $this->tenantDefaults($property->tenant_id),
ProcessProfile::PROPERTY => $propertyLevel,
ProcessProfile::CHANNEL => $intake === IntakeKind::Internal || $channel === null ? [] : (array) (($channel->process_overrides ?? [])[$intake->value] ?? []),
($channel?->isWebsite() ? ProcessProfile::WEBSITE : ProcessProfile::CHANNEL) => $intake === IntakeKind::Internal || $channel === null ? [] : (array) (($channel->process_overrides ?? [])[$intake->value] ?? []),
];
$values = [];
@@ -38,7 +38,7 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
$sources[$setting->value] = ProcessProfile::SYSTEM;
foreach ($levels as $level => $settings) {
if ($level === ProcessProfile::CHANNEL && ! in_array($intake, $setting->channelIntakes(), true)) {
if (in_array($level, [ProcessProfile::CHANNEL, ProcessProfile::WEBSITE], true) && ! in_array($intake, $setting->channelIntakes(), true)) {
continue;
}
$value = $setting->normalize($settings[$setting->value] ?? null);
@@ -65,7 +65,16 @@ public function resolve(Property $property, ?Channel $channel, IntakeKind $intak
$documents = Responsibility::from((string) $values[ProcessSetting::Documents->value]);
$payments = Responsibility::from((string) $values[ProcessSetting::Payments->value]);
return new ProcessProfile($intake, ProcessProfile::caseTypeFor($intake, $channel !== null, $documents, $payments), $values, $sources);
return new ProcessProfile($intake, ProcessProfile::caseTypeFor($intake, $channel?->isPortal() ?? false, $documents, $payments), $values, $sources);
}
/**
* Settings of a request from the own website: the website's entry of the channel manager is its channel level
* (the case itself stays direct, without a channel).
*/
public function forWebsite(Property $property, IntakeKind $intake = IntakeKind::Inquiry): ProcessProfile
{
return $this->resolve($property, Channel::existingWebsiteOf($property), $intake);
}
/**
@@ -76,7 +85,9 @@ public function forBooking(Booking $booking): ProcessProfile
// The case's own landlord counts, whichever landlord is current (e.g. a case written by the system).
$property = $booking->property ?? Property::withoutGlobalScope('tenant')->findOrFail($booking->property_id);
return $this->resolve($property, $booking->processChannel(), $booking->intake ?? self::intakeFor($booking));
$channel = $booking->processChannel() ?? ($booking->source === 'website' ? Channel::existingWebsiteOf($property) : null);
return $this->resolve($property, $channel, $booking->intake ?? self::intakeFor($booking));
}
/**
@@ -100,7 +111,7 @@ public function tenantDefaults(?int $tenantId): array
public static function intakeFor(Booking $booking): IntakeKind
{
$channel = $booking->processChannel();
if ($channel === null) {
if ($channel === null || $channel->isWebsite()) {
return IntakeKind::Inquiry;
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Process;
use App\Models\Booking;
use Carbon\CarbonImmutable;
/**
* What a new request holds when it comes in (v0.11, B1, E-033):
*
* - complete for an offer: the offer hold exactly as before (if the settings reserve at all);
* - incomplete, but with property, dates and a usable e-mail address (V1): only the clarification hold of its data
* request mode, 0 = none;
* - otherwise nothing.
*
* A request answered with an information "unter Vorbehalt" (no offer hold) needs no details first and holds nothing,
* as before. The free calendar was checked by the caller under its lock.
*/
final class RequestHold
{
/**
* @param Booking $draft the new case, not yet stored, with its guest relation
* @return array{hold_expires_at: ?CarbonImmutable, hold_purpose: string}
*/
public static function for(Booking $draft, ProcessProfile $profile): array
{
if (! $profile->preReservation()) {
return ['hold_expires_at' => null, 'hold_purpose' => Booking::HOLD_OFFER];
}
if (CaseRequirements::isComplete($draft)) {
return ['hold_expires_at' => now()->addHours($profile->holdHours())->toImmutable(), 'hold_purpose' => Booking::HOLD_OFFER];
}
$minutes = $profile->clarificationHoldMinutes();
if ($minutes === 0 || ! CaseRequirements::qualifiesForClarificationHold($draft)) {
return ['hold_expires_at' => null, 'hold_purpose' => Booking::HOLD_CLARIFICATION];
}
return ['hold_expires_at' => now()->addMinutes($minutes)->toImmutable(), 'hold_purpose' => Booking::HOLD_CLARIFICATION];
}
}
+44
View File
@@ -0,0 +1,44 @@
<?php
namespace App\Support;
/**
* Countries guests usually come from, as ISO 3166-1 alpha-2 codes (the guest record stores the code). Forms may
* pre-select Germany; it counts as given only because the guest or the landlord sends it (v0.11 B4).
*/
class Countries
{
public const DEFAULT = 'DE';
/**
* @return array<string, string> 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);
}
}
+17
View File
@@ -104,6 +104,23 @@
| Mailbox that receives the portals' booking notifications (fast path for portal bookings).
| Read via IMAP every minute; messages are left unread. Empty host = disabled.
*/
/*
| v0.11 extraction of guest messages (CH-14): a small model extracts, rules check, a larger model reviews risky
| results. Thresholds are starting values to be calibrated with representative messages (go-live condition).
*/
// Provider, key and models are each landlord's own (System › KI-Anbindung); endpoints are fixed in
// App\Communication\Extraction\AiProvider. Here only the technical limits.
'ai' => [
'anthropic_version' => env('FEWO_AI_ANTHROPIC_VERSION', '2026-10-21'),
'timeout' => (int) env('FEWO_AI_TIMEOUT', 40),
'prompt_version' => env('FEWO_AI_PROMPT_VERSION', 'v1'),
// Escalate to the review model when criticality × (1 − confidence) exceeds this value.
'escalate_above' => (float) env('FEWO_AI_ESCALATE_ABOVE', 0.2),
// Minimum confidence of the final result for taking a detail over automatically.
'min_confidence' => (float) env('FEWO_AI_MIN_CONFIDENCE', 0.85),
'per_run' => (int) env('FEWO_AI_PER_RUN', 10),
],
'mailbox' => [
'host' => env('FEWO_MAILBOX_HOST'),
'port' => (int) env('FEWO_MAILBOX_PORT', 993),
@@ -0,0 +1,54 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
/**
* Prozessarchitektur v0.11, channel manager (E-037): every channel is managed in one place, including the own
* website. A channel is a portal (as before) or the settings entry of the property's website; the website entry is
* never synchronised, exported or monitored. Each existing property gets its website entry.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('channels', function (Blueprint $table) {
$table->string('kind', 20)->default('portal')->after('property_id');
$table->index(['property_id', 'kind']);
});
foreach (DB::table('properties')->get(['id', 'tenant_id']) as $property) {
$exists = DB::table('channels')->where('property_id', $property->id)->where('kind', 'website')->exists();
if ($exists) {
continue;
}
DB::table('channels')->insert([
'tenant_id' => $property->tenant_id,
'property_id' => $property->id,
'kind' => 'website',
'name' => 'Eigene Webseite',
'connector' => 'website',
'export_token' => Str::random(48),
'is_active' => true,
'status' => 'active',
'booking_model' => 'inquiry',
'created_at' => now(),
'updated_at' => now(),
]);
}
}
public function down(): void
{
DB::table('channels')->where('kind', 'website')->delete();
Schema::table('channels', function (Blueprint $table) {
$table->dropIndex(['property_id', 'kind']);
$table->dropColumn('kind');
});
}
};
@@ -0,0 +1,60 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Prozessarchitektur v0.11, common fact intake (S5, CH-03): every detail that arrives for a case – from the website
* form, the guest's link, an e-mail, a portal mail, the extraction or the landlord – is recorded with its source and
* what became of it (taken over, confirmed, conflict, change request, rejected). The data itself stays in guests and
* bookings; this is the evidence. Bookings get the purpose of their hold (offer as before, or clarification).
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('case_facts', function (Blueprint $table) {
$table->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');
}
};
@@ -0,0 +1,53 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Prozessarchitektur v0.11, data request (S1/S4, CH-15–CH-18): one coherent request for missing details of a case –
* first question, targeted follow-up questions and reminders with their own counters that are never reset, the answer
* deadline (which is not a reservation deadline) and the version of the guest's link.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('data_requests', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('booking_id')->constrained()->cascadeOnDelete();
$table->string('status', 20);
$table->string('mode', 20);
$table->string('purpose', 30);
$table->json('fields');
$table->unsignedTinyInteger('followups_sent')->default(0);
$table->unsignedTinyInteger('reminders_sent')->default(0);
$table->unsignedSmallInteger('link_version')->default(1);
$table->string('last_message', 20)->nullable();
$table->dateTime('last_sent_at')->nullable();
$table->dateTime('response_due_at')->nullable();
$table->dateTime('next_reminder_at')->nullable();
$table->dateTime('answered_at')->nullable();
$table->dateTime('closed_at')->nullable();
$table->string('closed_reason')->nullable();
$table->timestamps();
$table->index(['booking_id', 'status']);
$table->index(['status', 'next_reminder_at']);
});
Schema::table('booking_messages', function (Blueprint $table) {
$table->string('message_id')->nullable()->after('subject')->index();
});
}
public function down(): void
{
Schema::table('booking_messages', function (Blueprint $table) {
$table->dropColumn('message_id');
});
Schema::dropIfExists('data_requests');
}
};
@@ -0,0 +1,97 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
/**
* Prozessarchitektur v0.11, communication handler inbox (CH-01, CH-05, CH-06):
*
* - mailboxes: the data model allows several per landlord; at go-live one is active. Mode "portal_only" reads only the
* portals' senders as before; "full" reads every message of a dedicated mailbox. The existing mailbox of each
* landlord is taken over unchanged as "portal_only" (the tenant columns stay readable until production migrated).
* - inbound_messages: every message read in "full" mode, stored before it is processed, deduplicated per landlord by
* its Message-ID, with the case it was assigned to (or why it waits for clarification) and the test-mode mark.
*/
return new class extends Migration
{
public function up(): void
{
Schema::create('mailboxes', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->string('label')->default('Postfach');
$table->string('host', 190)->nullable();
$table->unsignedSmallInteger('port')->nullable();
$table->string('encryption', 10)->nullable();
$table->string('username', 190)->nullable();
$table->text('password')->nullable();
$table->string('folder', 190)->nullable();
$table->string('address')->nullable();
$table->string('mode', 20)->default('portal_only');
$table->boolean('is_active')->default(true);
$table->dateTime('last_fetched_at')->nullable();
$table->timestamps();
});
foreach (DB::table('tenants')->whereNotNull('mailbox_host')->get() as $tenant) {
DB::table('mailboxes')->insert([
'tenant_id' => $tenant->id,
'label' => 'Postfach',
'host' => $tenant->mailbox_host,
'port' => $tenant->mailbox_port,
'encryption' => $tenant->mailbox_encryption,
'username' => $tenant->mailbox_username,
// Same application key, same encrypted value.
'password' => $tenant->mailbox_password,
'folder' => $tenant->mailbox_folder,
'mode' => 'portal_only',
'is_active' => true,
'created_at' => now(),
'updated_at' => now(),
]);
}
Schema::create('inbound_messages', function (Blueprint $table) {
$table->id();
$table->foreignId('tenant_id')->nullable()->constrained()->cascadeOnDelete();
$table->foreignId('mailbox_id')->nullable()->constrained()->nullOnDelete();
$table->string('message_id');
$table->string('in_reply_to')->nullable();
$table->text('references')->nullable();
$table->string('from_address')->nullable();
$table->string('from_name')->nullable();
$table->text('to_addresses')->nullable();
$table->string('subject', 500)->nullable();
$table->longText('body')->nullable();
$table->dateTime('received_at');
$table->boolean('test_mode')->default(false);
$table->string('status', 20);
$table->foreignId('booking_id')->nullable()->constrained()->nullOnDelete();
$table->string('match_reason', 40)->nullable();
$table->json('hints')->nullable();
$table->unsignedBigInteger('portal_email_id')->nullable();
$table->string('extraction_status', 20)->nullable();
$table->json('extraction')->nullable();
$table->dateTime('processed_at')->nullable();
$table->timestamps();
$table->unique(['tenant_id', 'message_id']);
$table->index(['status', 'extraction_status']);
});
Schema::table('portal_emails', function (Blueprint $table) {
$table->unsignedBigInteger('inbound_message_id')->nullable()->index();
});
}
public function down(): void
{
Schema::table('portal_emails', function (Blueprint $table) {
$table->dropColumn('inbound_message_id');
});
Schema::dropIfExists('inbound_messages');
Schema::dropIfExists('mailboxes');
}
};
@@ -0,0 +1,29 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
/**
* Prozessarchitektur v0.11, bring your own key: each landlord configures the AI access of his guest message extraction
* himself – provider, the two models and the result of the last check. The key itself stays in the encrypted api_key.
*/
return new class extends Migration
{
public function up(): void
{
Schema::table('tenant_services', function (Blueprint $table) {
$table->json('settings')->nullable()->after('api_key');
$table->string('check_status', 20)->nullable()->after('settings');
$table->string('check_message', 500)->nullable()->after('check_status');
$table->dateTime('checked_at')->nullable()->after('check_message');
});
}
public function down(): void
{
Schema::table('tenant_services', function (Blueprint $table) {
$table->dropColumn(['settings', 'check_status', 'check_message', 'checked_at']);
});
}
};
@@ -0,0 +1,59 @@
# v0.11 – Fachliche Abnahme auf dem Testsystem (stommer.info)
**Zweck:** Abnahme des integrierten v0.11-MVP ohne manuelle Ersatzschritte, im Testbetrieb. · **Voraussetzung:** Auslieferung des Stands aus `feature/aufenthalt` auf das Testsystem (nach Abstimmung mit dem Betreiber) und die externen Dienste aus §1. · Bericht: [Umsetzungsergebnis v0.11](../Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md)
---
## 1. Benötigte externe Dienste (vom Betreiber bereitzustellen)
| Dienst | Wofür | Einrichtung |
|---|---|---|
| **Eigenes IMAP-Postfach** für die Gästekommunikation, z. B. `anfragen@…` bei Strato | Antworten der Gäste und Portal-Mails lesen (CH-01, CH-05) | Zugangsdaten unter System › Betrieb; „Was wird gelesen?“ = „Alle Nachrichten“; „Adresse dieses Postfachs“ = die Postfachadresse. Das Postfach darf nur für Anfragen und Antworten dienen. |
| **SMTP** (wie bei T23) | Rückfragen und Angebote versenden | ist eingerichtet; Testbetrieb lässt nur die Testadresse zu |
| **Eigener KI-Zugang des Mandanten** (Anthropic oder OpenRouter, Bring your own key) | Auswertung der Antworten (CH-14) | Betreiberbereich › Mandant › Dienste: „KI: Gästekommunikation“ einschalten. Danach in der Verwaltung des Mandanten **System › KI-Anbindung**: Anbieter, API-Schlüssel, Modell für die erste Auswertung und für die Prüfung eintragen, „Verbindung prüfen“. Kein zentraler Schlüssel nötig. |
| **Testpostfach**, das die Testadresse empfängt und von dem aus geantwortet werden kann | Rückfragen empfangen und beantworten | System › Betrieb › Testadresse |
| Scheduler (n8n, vorhanden) | `channels:fetch-mail` jede Minute, `cases:data-requests` und `messages:extract` alle fünf Minuten | läuft über den vorhandenen Auslöser; nichts zu tun |
**Datenschutz im Test:** Es gehen echte Nachrichtentexte an den KI-Anbieter. Für die Abnahme bitte nur Testnachrichten ohne echte Gastdaten verwenden (Go-live-Bedingung G4/G5).
## 2. Testkonfiguration
1. **System › Betrieb:**
- Betriebsart „Testbetrieb“;
- Testadresse = Testpostfach;
- Postfach wie in §1.
2. **So arbeite ich:**
- Bearbeitung „Automatisch weiterbearbeiten“;
- „Wie wird nach fehlenden Angaben gefragt?“ = „Automatisch beim Gast nachfragen“;
- Dokumente: Rückfrage bleibt als Arbeitsfassung, im Testbetrieb geht sie trotzdem hinaus.
3. **Kanäle › Eigene Webseite:** zunächst nichts ändern, die Standards gelten. Für Fall 7 vorübergehend die Klärungsreservierung „automatisch“ auf `0` setzen.
4. **Kanäle › FeWo-direkt:** Absender der Buchungs-E-Mails eingetragen (z. B. `fewo-direkt.de`).
5. **Preise:** Für die Testzeiträume sind Saisons hinterlegt (Lücke Januar bis März 2027 vorher schließen, siehe Status vom 02.11.2026).
6. **KI-Anbindung:** „Verbindung prüfen“ zeigt „Verbindung in Ordnung“. Gegenprobe: einen falschen Schlüssel speichern und prüfen. Erwartet wird „Prüfung fehlgeschlagen“, die Auswertung ist aus, und Nachrichten bleiben im Posteingang. Danach den richtigen Schlüssel wieder eintragen.
7. **Wirksame Einstellungen** (Expertenansicht) prüfen: In der Spalte „Eigene Webseite – Anfrage“ stehen 15 Minuten (automatisch) bzw. 180 Minuten (Freigabe) und der Rückfragemodus „Automatisch“.
## 3. Drehbuch (etwa 90 Minuten)
Bei jedem Fall gilt: Im Vorgang › Ablauf und im Verlauf muss sichtbar sein, was geschah. Alle Mails gehen nur an die Testadresse; der Verlauf vermerkt „im Testbetrieb an die Testadresse“.
| # | Ablauf | Erwartung |
|---|---|---|
| **1** | Auf der Webseite anfragen: Name, E-Mail, **ohne Anschrift** (M01, M11). | Vorgang „Anfrage“, oben „Angaben für das Angebot vervollständigen“. Kalender für 15 Minuten belegt. Die Rückfrage-Mail nennt „zur Klärung bis <Uhrzeit> vorläufig reserviert“ und „noch kein verbindliches Angebot“. Kein Angebot; auch „Angebot senden“ von Hand wird mit „fehlen noch Angaben“ abgelehnt. |
| **2** | Im Testpostfach auf die Rückfrage **antworten**: „Lindenallee 12, 10115 Berlin“ (M02 E-Mail, CH-13 Antwortbezug). | Spätestens nach einer Minute steht die Nachricht im Posteingang als „einem Vorgang zugeordnet“ (Testbetrieb markiert), die Erinnerung ruht. Nach höchstens fünf Minuten ist sie ausgewertet: Anschrift übernommen (Herkunft „aus einer Nachricht erkannt (KI)“). Das Land kam schon aus dem Formular. Danach geht automatisch das **Angebot** hinaus, Reservierung 48 Stunden. |
| **3** | Zweite Anfrage ohne Anschrift. Den **Link** „Angaben ergänzen“ öffnen, nur die Straße senden, dann den Rest; das Formular zweimal absenden; einen älteren Link öffnen (M02 Link, M03, M09). | Nach der Teilantwort kommt eine gezielte Folgefrage mit neuem Link; der alte Link sagt „nicht mehr aktuell“. Doppeltes Absenden erzeugt nichts doppelt. Danach geht das Angebot hinaus. |
| **4** | Dritte Anfrage ohne Anschrift; nicht antworten. Im Vorgang die nächste Erinnerung ablesen. Zum Abkürzen „Wie oft wird höchstens erinnert?“ = 1 und „Nach wie vielen Stunden …“ = 1 setzen (M08). | Nach einer Stunde kommt eine Erinnerung, nach einer weiteren Stunde die Aufgabe „Fehlende Angaben selbst beim Gast nachfragen“. Die Klärungsreservierung ist nach 15 Minuten abgelaufen und wurde durch nichts verlängert; der Vorgang bleibt offen. |
| **5** | Vom Testpostfach eine **neue Mail ohne Bezug** an das Postfach senden: „Haben Sie im Dezember frei?“ (M04). | Posteingang „zu klären“, kein Vorgang. „Als neue Anfrage anlegen“ erzeugt die Anfrage; sie fragt nach der Anschrift. |
| **6** | Auf eine Rückfrage antworten: „Telefon 0171 1234567. Können wir einen Tag länger bleiben?“ (M05, M06). | Telefon übernommen. Aufgabe „Änderungswunsch des Gastes prüfen“; der Zeitraum ist **unverändert**. Optional: `php artisan ai:evaluate <Mandanten-ID>` ausführen (nutzt den Zugang des Mandanten) und notiert die Rate übersehener Angaben. |
| **7** | Klärungsreservierung „automatisch“ der Webseite auf `0`, erneut ohne Anschrift anfragen (M11, M12). | Kein Kalendereintrag. Die Rückfrage sagt „noch nicht für Sie reserviert“, ohne Reservierungsbehauptung. Danach den Wert zurücksetzen. |
| **8** | Portalbuchung: FeWo-direkt-Buchungsmail an das Postfach weiterleiten bzw. die vorhandene Testmail aus T04 verwenden (M07, M12, E-036). | Wie bisher: Sperre bzw. Vorgang „Beim Portal fest gebucht“. Keine Klärungsreservierung, kein Angebot. Fehlt nur die Anschrift, heißt die Rückfrage „Ihre Buchung ist verbindlich bestätigt …“. iCal-Abgleich läuft unverändert. |
| **9** | **Regression v0.10:** Drehbuch der Gesamtabnahme v0.10 §8 in Kurzform (Annahme, Auskunft und Buchungswunsch, Ändern, Storno, Aufenthalt) (M10). | Unverändert; neu ist nur, dass Angebot und Wunschbestätigung die vollständige Anschrift verlangen. |
## 4. Abnahmeprotokoll
Je Fall festhalten:
- bestanden / nicht bestanden;
- Uhrzeit;
- Vorgangsnummer;
- gegebenenfalls ein Screenshot unter `Abnahme/<Datum>/`.
Offene Befunde gehen in den Status. Die Freigabe zum Live-Betrieb setzt zusätzlich die Go-live-Bedingungen G1–G8 voraus (Umsetzungsergebnis §7).
@@ -0,0 +1,142 @@
# Umsetzungsergebnis v0.11 – integrierter MVP
**Stand:** 03.11.2026 · **Branch:** `feature/aufenthalt` · **Commits:** 799869c (U1), ccac78a (U2), 37f48de (U3), e4a3cb7 (U4), dff9e23 (U5), 4170e3b (U6), 73c0a71 (Integrationstest)
**Status:**
- umgesetzt und automatisiert getestet;
- **noch nicht** auf dem Testsystem: Auslieferung, Postfach und KI-Schlüssel stimmt der Betreiber vorher ab;
- keine Produktivauslieferung, kein Merge nach `main`.
Bezug:
- [Umsetzungsplan](V011_UMSETZUNGSPLAN.md)
- [Zielarchitektur](V011_TECHNISCHE_ZIELARCHITEKTUR.md)
- [Abnahme auf dem Testsystem](../Abnahme/V011_ABNAHME_TESTSYSTEM.md)
- normativ: [Communication Handler](../Querschnitt/Datenbeschaffung_und_Communication_Handler.md)
---
## 1. Ergebnis in Kürze
- Alle sechs Pakete sind umgesetzt; ein durchgehender Integrationstest deckt die ganze Kette ab: Website-Anfrage ohne Anschrift → Klärungsreservierung → Rückfrage per Mail → Antwort des Gastes per E-Mail → Zuordnung über den Antwortbezug → KI-Auswertung → Fakteneingang → automatisches Angebot mit unverändertem Angebots-Hold → Annahme → verbindliche Buchung.
- **Tests:** 766 grün, vorher 702. Neu sind 64 Tests in 8 Dateien; 11 bestehende Testdateien wurden angepasst (Anschriften in Testdaten, siehe §5).
- Die Architekturgrenzen sind eingehalten:
- keine zweite Ablaufsteuerung (`CaseAutomation`/`CaseActivities` bleiben führend);
- Angebots-Hold und Annahmefristen unverändert;
- iCal-Pfad und Portal-Schnellweg unverändert;
- extern verbindliche Buchungen bleiben verbindlich;
- die KI ändert nichts selbst.
- Ein Architekturtest prüft, dass nur die bestehenden Reservierungsschritte Fristen schreiben.
## 2. Was gebaut wurde
| Paket | Inhalt | Wichtigste Dateien |
|---|---|---|
| U1 | Webseite als Kanal (`channels.kind`), neue Prozessparameter, „Kanäle“ in der einfachen Ansicht, „Wirksame Einstellungen“ mit Webseiten-Spalte | `ProcessSetting`, `ProcessSettings::forWebsite`, `Channel`, `ChannelForm`, `ListChannels` |
| U2 | Angebots-Gate G2a (vor Angebot und Wunschbestätigung, nicht vor Auskunft), gemeinsamer Fakteneingang mit Herkunft (`case_facts`), Land als ISO-Code | `CaseRequirements`, `ContributeCaseFacts`, `CaseFact`, `DocumentComposer`, `SendOffer`, `DecideBookingWish` |
| U3 | Klärungsreservierung (`hold_purpose`), Ablauf ohne Vorgangsende, Angebot danach nur bei freiem Zeitraum | `RequestHold`, `CreateReservation`, `TakeOverPortalInquiry`, `ExpireReservations`, `Booking::clarificationState` |
| U4 | Beschaffungsvorgang mit Rückfrage, Folgefrage, Erinnerung, Grenzen; Mail nach tatsächlichem Sperrstatus; signierter Ergänzungslink | `RequestCaseData`, `DataRequest`, `DataRequested`, `GuestDataController`, `cases:data-requests` |
| U5 | Postfächer (`mailboxes`), Nachrichteneingang (`inbound_messages`), Zuordnung nach CH-13, „Posteingang“, Message-ID der ausgehenden Mails | `ReceiveInboundMessage`, `MessageMatcher`, `InboundMessageResource`, `MailboxReader::fetchAll`, `LogBookingMail` |
| U6 | KI-Kaskade (klein → Regeln → groß), Prompts v1, Schema, Vorschläge im Posteingang, Messbefehl; **BYOK** je Mandant (Anthropic oder OpenRouter, Seite „KI-Anbindung“, Verbindungsprüfung) | `ExtractMessageFacts`, `MessageExtractor`, `RiskAssessment`, `LlmClient`, `messages:extract`, `ai:evaluate` |
**Migrationen** (alle rückwärtskompatibel, keine wurde auf einem Server ausgeführt):
- `2026_11_06_090000` Kanalart;
- `…100000` Faktenprotokoll, Hold-Zweck, `guests.country` ohne Standardwert;
- `…110000` Beschaffungsvorgänge und Message-ID;
- `…120000` Postfächer und Nachrichteneingang;
- `…130000` KI-Zugang je Mandant (BYOK).
## 3. Rückverfolgbarkeit
| Anforderung | Umsetzung | Nachweis (Test) |
|---|---|---|
| **CH-01** IMAP-Eingang, Antworten erkennen | Postfachmodus „alle Nachrichten“, `ReceiveInboundMessage` | `GuestMailInboxTest::test_the_mailbox_is_kept_as_a_record_and_full_mode_reads_every_message`, `V011EndToEndTest` |
| **CH-02** Inhalte, auch unstrukturiert; E-Mail als Rückkanal | Extraktion aus Betreff und Text; Antwortadresse = eigenes Postfach | `MessageExtractionTest`, `V011EndToEndTest` |
| **CH-03** kontrollierte Ergänzung, kein blindes Überschreiben | `ContributeCaseFacts` (fehlend → übernehmen, abweichend → Prüfaufgabe, Vermieterin maßgeblich) | `CaseFactIntakeTest::test_missing_values_are_taken_over…` |
| **CH-04** regelbasierte Rückfragen je Modus | `RequestCaseData` automatisch / Freigabe / manuell | `DataRequestTest` (drei Modi) |
| **CH-05** Modell für mehrere Postfächer, eines aktiv | `mailboxes`, `Tenant::activeMailbox` | `GuestMailInboxTest` |
| **CH-06** Erfassen, Doppelverarbeitung, Klärungsansicht, keine Vorgänge aus allgemeinen Mails | `inbound_messages` (eindeutig je Message-ID), „Posteingang“ | `GuestMailInboxTest::test_a_message_is_stored_once…`, `…the_landlord_assigns_a_message_or_makes_a_new_request_of_it` |
| **CH-07/13** deterministische Zuordnung; Nummer allein kein Identitätsnachweis; ein offener Vorgang des Absenders allein genügt nicht | `MessageMatcher` | `GuestMailInboxTest` (Antwortbezug, Nummer + Absender, Absender + Wohnung + Zeitraum, mehrdeutig) |
| **CH-08** Portalparser bleiben | Portal-Absender laufen unverändert durch `ProcessPortalMail` | `GuestMailInboxTest::test_a_portal_notification_goes_through_the_unchanged_portal_path`, `PortalMailTest` unverändert grün |
| **CH-09/12** Portal-Mail mit Gastdaten, beliebige Reihenfolge | Portal-Mail mit Vorgangsbezug wird ausgewertet (Quelle Portal-Mail) | `CaseFactIntakeTest` (Portal ergänzt Personenzahl), `CaseIntakeTest` unverändert grün |
| **CH-10** keine pauschale Rangfolge | Regel je Feld und Phase statt Quellenrang | `CaseFactIntakeTest` |
| **CH-11** iCal-Abgleich unverändert | keine Änderung an Sync, Regeln, Export | Kanal- und Sync-Tests unverändert grün |
| **CH-14** zweistufige KI, Kritikalität im Programm, Konfidenz nicht maßgeblich; austauschbare Modellanbindung | `RiskAssessment`, `ExtractMessageFacts`, `AiAccess`, `AiProvider` | `MessageExtractionTest` (Widerspruch trotz Konfidenz 0,99 → Prüfung, keine Übernahme), `AiAccessTest` (BYOK, OpenRouter, abgelehnter Schlüssel, feste Endpunkte) |
| **CH-15/16/17** Rückfrage, Folgefrage, Erinnerung; Zähler ohne Reset; Grenzen; eine offene Rückfrage | `DataRequest`, `RequestCaseData::answered/remindDue` | `DataRequestTest::test_reminders_follow_their_limit…`, `…partly_and_then_fully` |
| **CH-18** signierter, versionierter Link, Lesen schreibt nicht, idempotent | `GuestDataController` | `DataRequestTest::test_foreign_outdated_and_unsigned_links_change_nothing` |
| **S1–S6** | `RequestCaseData` (S1), `ReceiveInboundMessage` (S2), `MessageMatcher` und Extraktion (S3), `DataRequested` und Link (S4), `ContributeCaseFacts` (S5), `CaseAutomation::advance` (S6) | `V011EndToEndTest` |
| **E-032 / G2a** Pflichtangaben, Anschrift nicht übergehbar | `CaseRequirements`, Blocker in `SendOffer`, `AutoOffer`, `DocumentComposer`, `DecideBookingWish` | `CaseFactIntakeTest` (M01, B3, B4) |
| **E-033 / G1a** Klärungsreservierung 15/180 min, `0` | `RequestHold` | `ClarificationHoldTest` |
| **E-034** Texte nach tatsächlichem Sperrstatus | `DataRequested`, Eingangsbestätigung, Linkseite | `DataRequestTest::test_the_texts_follow_the_real_state_of_the_hold` |
| **E-035** gemeinsamer Fakteneingang, KI nur Kandidaten | `ContributeCaseFacts`, `ExtractMessageFacts` | `MessageExtractionTest` |
| **E-036** extern verbindliche Buchung geschützt | nie Klärungsreservierung; Rückfrage nur administrativ | `ClarificationHoldTest`, `DataRequestTest`, `V011EndToEndTest` |
| **E-037** zentraler Kanalmanager | „Kanäle“ mit Webseite und Portalen | `ChannelManagerTest` |
| **E-038** Änderungswunsch nur erfassen | Aufgabe „Änderungswunsch prüfen“, Buchung unverändert | `CaseFactIntakeTest` (M06-Kern), `MessageExtractionTest::test_a_wish_to_change_the_stay_is_only_a_request` |
| **B1–B4** (Betreiber 03.11.2026) | wie entschieden | `ClarificationHoldTest`, `CaseFactIntakeTest` |
### Abnahmefälle M01–M12
| M | Automatisiert | Auf dem Testsystem |
|---|---|---|
| M01 | `CaseFactIntakeTest::test_a_request_without_address_gets_no_offer…` | Drehbuch Fall 1 |
| M02 | `DataRequestTest` (Link, teilweise und vollständig), `V011EndToEndTest` (E-Mail) | Fälle 2, 3 |
| M03 | `CaseFactIntakeTest`, `DataRequestTest` (doppeltes Absenden), `GuestMailInboxTest` (gleiche Mail) | Fall 3 |
| M04 | `GuestMailInboxTest` | Fall 5 |
| M05 | `MessageExtractionTest`, `ai:evaluate` | Fall 6 (Messlauf mit echtem Modell) |
| M06 | `MessageExtractionTest`, `CaseFactIntakeTest` | Fall 6 |
| M07 | `GuestMailInboxTest` (Portalpfad), `CaseIntakeTest` | Fall 8 |
| M08 | `DataRequestTest` | Fall 4 |
| M09 | `DataRequestTest` | Fall 3 |
| M10 | `GuestMailInboxTest`, `V011EndToEndTest`, `MailTestModeGateTest` | alle Fälle (Testbetrieb) |
| M11 | `DataRequestTest`, `ClarificationHoldTest` | Fall 1 und 7 |
| M12 | `ChannelManagerTest`, `V011EndToEndTest` | Fälle 7 und 8 |
## 4. Technische Entscheidungen in der Umsetzung
Sie stehen in der freigegebenen Zielarchitektur oder präzisieren sie.
1. **Webseite als Kanal:**
- Je Wohnung gibt es einen Eintrag `kind = website`, nur für Einstellungen.
- `active()` und `Property::channels()` liefern nur Portale. Damit bleibt der Eintrag aus Sync, Export, Überwachung und Sperraufgaben heraus.
- Telefon- und E-Mail-Anfragen haben bewusst keinen eigenen Kanal; für sie gelten die Mandantenstandards (R02).
2. **Land:**
- `guests.country` hatte den Datenbankstandard „DE“. Neue Gäste haben jetzt kein Land, bis eine Quelle es nennt (B4).
- Bestehende Gäste behalten ihr „DE“, weil sich nicht feststellen lässt, ob es bestätigt war.
3. **Keine Rückfrage ohne E-Mail-Adresse:** Der Vorgang zeigt „Kontaktdaten eintragen“. Sobald die Adresse eingetragen ist, startet die Rückfrage nach dem, was noch fehlt.
4. **Rückfragetexte:** eigene Dokumentart „Rückfrage nach fehlenden Angaben“. Im Live-Betrieb geht sie ohne Freigabe nicht automatisch hinaus, sondern wartet auf einen Klick. Im Testbetrieb geht sie hinaus, aber nur an die Testadresse; so verhält sich auch das automatische Angebot.
5. **Antwortadresse:** Rückfragen nennen das eigene Postfach als Antwortadresse, wenn es im Modus „alle Nachrichten“ läuft. Alle anderen Mails behalten die bisherige Antwortadresse.
6. **Zuordnung direkter Gast-Mails:**
- Absender + Wohnung + beide Termine eines einzigen offenen Vorgangs.
- Hat der Mandant nur eine Wohnung, ist die Wohnung damit bestimmt. Bei mehreren muss der Wohnungsname in der Nachricht stehen.
7. **Portalanfragen (A2) ohne Gastdaten** reservieren beim Eingang nichts mehr: B1 gilt auch für sie. Die Angebots-Reservierung entsteht wie bisher mit dem Angebot.
8. **KI:**
- **Bring your own key:** Jeder Mandant wählt unter „System › KI-Anbindung“ Anbieter (Anthropic oder OpenRouter), Schlüssel, kleines und großes Modell. Es gibt keinen zentralen Schlüssel und keine Modellkennung im Code; die Endpunkte sind fest je Anbieter (`AiProvider`).
- Ein abgelehnter Schlüssel (401/402/403) schaltet die Auswertung für den Mandanten ab und meldet es; die Nachrichten bleiben im Posteingang (Test `AiAccessTest`).
- OpenRouter wird genutzt, weil der Betreiber es ausdrücklich vorgibt. Es ist ein OpenAI-kompatibler Zugang; erzwungen werden das Schema (`strict`) und nur Anbieter, die es unterstützen (`provider.require_parameters`).
- Bei Anthropic ist für Modelle der Opus-Familie der serverseitige Fallback bei Ablehnung aktiv (`fallbacks: "default"`). Eine Ablehnung gilt trotzdem als Fehlschlag, und die Nachricht geht an die Vermieterin.
- Die Anbindung läuft laut Plan über den HTTP-Client. Ein offizielles PHP-SDK gibt es; seine Aufnahme wäre eine Abhängigkeitsänderung und bräuchte eine Freigabe.
- Die Prompt-Anweisungen sind englisch, Werte und Oberfläche deutsch.
- Bekannte Werte gehen nur maskiert an den Anbieter.
9. **Takt:** Postfach jede Minute (Rückblick drei Tage, Deduplizierung je Message-ID), Erinnerungen und Auswertung alle fünf Minuten. Die Auswertung blockiert den Portal-Schnellweg also nicht.
10. **Kontaktdialog der Vermieterin:** Die Daten laufen über den Fakteneingang. Der Schalter „automatisch weitermachen“ behält seine bisherige Fortsetzungslogik, weil sie Portalbuchungen bindet. Konflikt K2 ist damit gelöst; die Doppelung der Fortsetzung (Auditbefund L3) besteht nur noch an dieser einen Stelle.
## 5. Anpassungen bestehender Tests
- **11 bestehende Testdateien:**
- 10 erhielten in ihren Testdaten eine vollständige Anschrift mit Land, weil Angebote sie jetzt voraussetzen (G2a). Die Prüfaussagen blieben gleich.
- `TenantSettingsTest` kennt den neuen verdrahteten Dienst.
- Keine bestehende Prüfaussage wurde abgeschwächt.
## 6. Einschränkungen
- **Nicht real geprüft:** IMAP gegen ein echtes Postfach und Aufrufe des echten KI-Dienstes. Automatisiert sind beide ersetzt (Mock, HTTP-Fake). Die echte Integrationsprüfung gehört zur Abnahme auf dem Testsystem.
- **Kalibrierung:** Der mitgelieferte Messsatz hat erst 4 Nachrichten. Schwellen (Eskalation 0,2, Mindestkonfidenz 0,85) und Prompt v1 sind Startwerte.
- **Texte** der Rückfrage, Folgefrage, Erinnerung und der Linkseite sind Arbeitsfassungen ohne rechtliche Freigabe.
- **Aufbewahrung:** Nachrichtentexte und Faktwerte sind verschlüsselt gespeichert, werden aber noch nicht vom Anonymisierungslauf erfasst. Eine Löschfrist ist nicht beschlossen.
- **KI-Zugang:** nur über die Seite „KI-Anbindung“ des Mandanten (BYOK); ein zentraler Schlüssel ist nicht vorgesehen.
- **Postfach-Zugangsdaten** werden auf „System › Betrieb“ gepflegt und in den Postfach-Datensatz übernommen. Die alten Mandantenspalten bleiben bis zur Produktivmigration als Rückfall.
- **Plus-Adressen** werden nicht genutzt; die Zuordnung läuft über Message-ID und Vorgangsnummer.
- Nicht Teil des MVP laut v0.11: parallele Angebote, automatische Vertragsänderungen und Teilstorno, mehrere aktive Postfächer, Messenger, generative Antworten, Gastkonto.
## 7. Go-live-Bedingungen
G1 Texte rechtlich freigeben · G2 endgültige Werte je Kanal (Rückfragemodus, Intervalle, Grenzen, Klärungsminuten) · G3 eigenes Postfach je Mandant, Zustellung der Antworten geprüft · G4 Datenschutz: Lesen aller Mails, Lösch- und Aufbewahrungsfristen inklusive Nachrichteneingang, Datenschutzhinweise · G5 KI-Anbieter: Auftragsverarbeitung, Speicherort, Kosten · G6 Kalibrierung mit repräsentativen anonymisierten Nachrichten, Rate übersehener Angaben akzeptiert · G7 Kriterien für verlässliche Portal-Mails · G8 Sicherheitsprüfung von Gastlink und Posteingang; Abnahme M01–M12 auf dem Testsystem; Regression v0.10.
@@ -0,0 +1,145 @@
# v0.11 – Soll-Ist-Analyse des Anwendungscodes
**Stand:** 03.11.2026 · **Codebasis:** Branch `feature/aufenthalt`, Commit 9a9e5e1 (identisch mit dem Stand des Testsystems plus Spezifikation v0.11), 702 Tests grün · **Grundlage:** normative v0.11 unter `docs/Prozessarchitektur/` (führend: [Communication Handler](../Querschnitt/Datenbeschaffung_und_Communication_Handler.md), [Konfiguration und Wirksamkeit](../KONFIGURATION_UND_WIRKSAMKEIT.md), [Entscheidungen](../Entscheidungen.md) E-032 bis E-038) · **Status:** Analyse, keine Implementierung.
Weitere Dokumente: [Technische Zielarchitektur](V011_TECHNISCHE_ZIELARCHITEKTUR.md) · [Umsetzungsplan](V011_UMSETZUNGSPLAN.md)
Klassen der Bewertung: **umgesetzt** · **anzupassen** (vorhanden, deckt die Anforderung aber nicht) · **neu** · **zu klären** · **nicht MVP**.
---
## 1. Ergebnis in Kürze
- Der v0.10-Kern trägt die v0.11 ohne Umbau. Das betrifft die Aktivitäten (`CaseActivities`), das Weiterführen (`CaseAutomation`), das eingefrorene Profil (`ProcessSettings` und `ProcessProfile`), Verlauf, Aufgaben, Testbetrieb und das Muster der signierten, versionierten Gastlinks. Keine der v0.11-Anforderungen verlangt eine zweite Ablaufsteuerung.
- **Vollständig neu** sind der Communication Handler, also ausgehende Rückfragen, Ergänzungslink, Erinnerungen, allgemeiner IMAP-Eingang und Zuordnung, sowie die KI-Extraktion und die Klärungsreservierung.
- **Anzupassen** sind die Angebotsvoraussetzungen (die Anschrift ist heute kein Gate), die Datenübernahme (sie überschreibt heute ohne Herkunft), der Postfachabruf (heute nur Portal-Absender), die Konfiguration (die eigene Webseite ist kein Kanal) und die Einstellungsübersicht.
- **Drei Stellen im Code stehen der v0.11 direkt entgegen** (§3): die Reservierung bei Eingang unvollständiger Anfragen, die überschreibende Kontaktübernahme und die Vorgangsart-Ableitung, falls die Webseite ein Kanal wird.
## 2. Ist-Zustand der untersuchten Komponenten
### 2.1 Vorgangskern und Fortsetzung
| Komponente | Ist | Bewertung für v0.11 |
|---|---|---|
| [CaseActivities](../../../app/Process/CaseActivities.php) | Leitet alle Aktivitäten aus dem Zustand ab; `next()` liefert den großen Schalter. Die Aktivität „contact“ prüft nur, ob eine E-Mail-Adresse da ist (Z. 64–75). | Trägt. Informationsbedarf je Aktivität fehlt (nur E-Mail). |
| [CaseAutomation](../../../app/Process/CaseAutomation.php) | `advance()` führt nur im automatischen Modus weiter: Angebot bzw. Auskunft für Anfragen, Unterlagen für verbindliche Buchungen (Z. 26–61). `documentBlockers()` kennt Gast, E-Mail und Preis (Z. 67–74). | Trägt als S6. Wird an mehreren Stellen einzeln aufgerufen ([RecordPortalAmounts](../../../app/Actions/RecordPortalAmounts.php) Z. 65, [TakeOverExternalBooking](../../../app/Actions/TakeOverExternalBooking.php) Z. 99, [TakeOverPortalInquiry](../../../app/Actions/TakeOverPortalInquiry.php) Z. 59, [ViewBooking](../../../app/Filament/Resources/Bookings/Pages/ViewBooking.php) Moduswechsel), [CreateReservation](../../../app/Actions/CreateReservation.php) ruft `AutoOffer` direkt. [ProvideGuestContact](../../../app/Actions/ProvideGuestContact.php) enthält eine eigene Kopie der Fortsetzung (Z. 56–89). |
| Phasen P1/P2/P3 | Implizit über `BookingStatus`: `Reserved` = P1, `OfferSent` = P2, `BookingStatus::occupying()` = P3. | Ausreichend; kein neuer Status nötig. |
| [CaseLog](../../../app/Process/CaseLog.php), [BookingTask](../../../app/Models/BookingTask.php) | Verlauf mit Akteur; Aufgaben mit Arten (`BookingTaskKind`) und `openOnce`. | Wiederverwendbar für Rückfrage-Freigabe, Konflikt und Änderungswunsch. |
### 2.2 Eingang, Reservierung, Angebot
| Komponente | Ist | Bewertung |
|---|---|---|
| [BookingRequest](../../../app/Livewire/BookingRequest.php) (Webformular) | Pflicht: Zeitraum, Personen, Vor-/Nachname, E-Mail, Einwilligung. Anschrift optional (Z. 332–334). Bot-Schutz vorhanden. | Erfüllt „unvollständige Anfrage zulässig“. |
| [CreateReservation](../../../app/Actions/CreateReservation.php) | Prüft die Verfügbarkeit, legt `Reserved` an und setzt **bei jeder Anfrage** `hold_expires_at = jetzt + Angebots-Haltefrist` (Standard 48 h), wenn „Angebotsreservierung ja“ gilt (Z. 98). | **Konflikt K1**, siehe §3. |
| [SendOffer](../../../app/Actions/SendOffer.php) | Prüft erneut die Verfügbarkeit (Z. 87), setzt die Angebotsfrist neu (Z. 113), versioniert, signierter Link mit Ablauf. | Bleibt unverändert (Architekturgrenze 3). |
| [AutoOffer](../../../app/Actions/AutoOffer.php) | Blocker u. a. „nicht mehr vorgemerkt“, wenn der Hold abgelaufen ist (Z. 56–57). | Anzupassen für Anfragen nach abgelaufener Klärungsreservierung. |
| [ExpireReservations](../../../app/Actions/ExpireReservations.php) | Setzt jede Anfrage mit abgelaufenem Hold auf `Expired` (Z. 18–35). | Anzupassen: Eine abgelaufene Klärungsreservierung darf den Vorgang nicht beenden (CH §4 Nr. 6). |
| [DocumentComposer](../../../app/Documents/DocumentComposer.php) | Harte Blocker: Gast, E-Mail und Preis (Z. 193–199). Eine fehlende Anschrift fällt nur als **bestätigbarer** Hinweis über leere Vertragsplatzhalter auf (Z. 214–217). | **G2a fehlt**: Die Anschrift ist übergehbar (M01 nicht erfüllt). |
| [Booking::occupying](../../../app/Models/Booking.php) (Z. 310) und [AvailabilityChecker](../../../app/Availability/AvailabilityChecker.php) | Halte-Status mit `hold_expires_at > now` belegen den Kalender und gehen in den iCal-Export ([ICalFeed](../../../app/Channels/ICal/ICalFeed.php) Z. 27). Holds erzeugen **keine** manuellen Portalaufgaben ([BookingObserver](../../../app/Observers/BookingObserver.php) nur `occupying()`-Status). | Mechanik für die Klärungsreservierung wiederverwendbar; es fehlt nur die Unterscheidung des Zwecks. |
| Paket 7 ([SendInformation](../../../app/Actions/SendInformation.php), [SubmitBookingWish](../../../app/Actions/SubmitBookingWish.php), [InformationController](../../../app/Http/Controllers/InformationController.php)) | Signierter, versionierter Link; „Lesen schreibt nicht“; idempotente Übernahme; erneute Prüfung in einer Transaktion. | Vorlage für den Ergänzungslink (CH-18). |
### 2.3 Gastdaten
| Komponente | Ist | Bewertung |
|---|---|---|
| [Guest](../../../app/Models/Guest.php) | Kartei je Mandant und E-Mail: Name, Kontakt, Straße, PLZ, Ort, Land. Wird von mehreren Vorgängen geteilt. | Ziel der Datenübernahme bleibt die Kartei; die Herkunft je Angabe fehlt. |
| `CreateReservation::guestFor` (Z. 119ff.) | Ergänzt nur leere Felder; abweichende Angaben gehen als Text in die internen Notizen, die Kartei bleibt unverändert. | Gute Teilumsetzung von CH-03 (nur für das Webformular). |
| [ProvideGuestContact](../../../app/Actions/ProvideGuestContact.php) | Überschreibt Kartenwerte ohne Abgleich und Herkunft (Z. 51). | **Konflikt K2** mit CH-03 („nicht blind überschreiben“). |
| „Gast um Kontaktdaten bitten“ ([ViewBooking](../../../app/Filament/Resources/Bookings/Pages/ViewBooking.php) Z. 334ff.) | Vermerkt nur `contact_requested_at` und liefert einen Text zum Kopieren. | Keine Rückfrage im Sinne von CH-04/CH-15. |
### 2.4 E-Mail und Portale
| Komponente | Ist | Bewertung |
|---|---|---|
| Versand | Laravel-Mailer; die Schranke [EnforceMailTestMode](../../../app/Listeners/EnforceMailTestMode.php) leitet im Testbetrieb alles an die Testadresse; [LogBookingMail](../../../app/Listeners/LogBookingMail.php) schreibt `BookingMessage` (nur Betreff und Empfängerkreis, **keine Message-ID**). | Wiederverwendbar; für die Antwortzuordnung fehlt die Message-ID. |
| [MailboxReader](../../../app/Channels/Mail/MailboxReader.php) | IMAP über `webklex/php-imap`; fragt **nur die Absender bekannter Portale** ab (Z. 79), lässt Mails ungelesen, Rückblick 3 Tage. Zugangsdaten als Spalten am Mandanten ([Tenant::mailbox](../../../app/Models/Tenant.php) Z. 124), also nur ein Postfach. | Allgemeiner Eingang (CH-01, CH-06) fehlt; Datenmodell für mehrere Postfächer (CH-05) fehlt. |
| [ProcessPortalMail](../../../app/Actions/ProcessPortalMail.php) | Doppelte Verarbeitung je `message_id` ausgeschlossen (Z. 38); Kanal anhand des Absenders (Z. 108); Parser → Sperre, Freigabe oder `PortalIntake`. | Bleibt (CH-08); fehlt: Übergabe von Gastangaben an den Fakteneingang (CH-09/12). |
| [PortalMailParser](../../../app/Channels/Mail/PortalMailParser.php) | Liefert Typ (Buchung, Storno, Anfrage, unbekannt), Termine und Referenz (Z. 36–57); keine Gastdaten, keine Änderung. | Bleibt; Gastdaten künftig über die Extraktion. |
| [PortalIntake](../../../app/Channels/Intake/PortalIntake.php) | Zuordnung über Referenz und, bei gleichem Portal, gleichen Nächten und ohne Widerspruch, über die Termine (Z. 326ff.). | **Erfüllt CH-13** (iCal-vor-Mail ist ausdrücklich zugelassen). Der frühere Auditbefund L8 ist durch die v0.11 erledigt. |
| iCal ([SyncChannel](../../../app/Actions/SyncChannel.php), [ICalConnector](../../../app/Channels/ICal/ICalConnector.php), Regeln, Export) | Eigenständig, fünf Minuten, Regeln je Kanal. | Bleibt unverändert (Grenze 4). |
### 2.5 Konfiguration
| Komponente | Ist | Bewertung |
|---|---|---|
| [ProcessSetting](../../../app/Enums/ProcessSetting.php) | Acht Einstellungen mit Standard, Frage, erlaubten Eingangsarten je Kanal und Normalisierung. | Erweiterbar um die v0.11-Parameter, ohne neues Konfigurationsmodell. |
| [ProcessSettings](../../../app/Process/ProcessSettings.php) | Vererbung System → Mandant (`tenants.process_defaults`) → Wohnung (`properties.process_overrides`) → Kanal je Eingangsart (`channels.process_overrides`). Ohne Kanal gilt keine Kanalebene (Z. 31). | Trägt E-029. Die **eigene Webseite hat keine Kanalebene**. |
| [ProcessProfile::caseTypeFor](../../../app/Process/ProcessProfile.php) | A1 oder A2 je nachdem, **ob es einen Kanal gibt** (Z. 53). | **Konflikt K3**, wenn die Webseite ein Kanal-Datensatz wird. |
| [Channel](../../../app/Models/Channel.php) | Je Wohnung; Portal mit iCal-Anbindung, Buchungsmodell, Regeln, Export, Prozessabweichungen. Etwa 15 operative Stellen arbeiten mit `active()`-Kanälen (Sync, Postfach-Absender, Überwachung, Sperraufgaben, `CalendarClearance`). | Grundlage des Kanalmanagers; ein Webseiten-Datensatz darf in diese Abläufe nicht hineinlaufen. |
| Oberflächen | „So arbeite ich“ ([HandlingSettings](../../../app/Filament/Pages/HandlingSettings.php)) für Mandantenstandards; Portale ([ChannelForm](../../../app/Filament/Resources/Channels/Schemas/ChannelForm.php) Z. 133–144) nur in der Expertenansicht; Wohnungsabweichungen; [EffectiveSettings](../../../app/Filament/Pages/EffectiveSettings.php) mit Herkunft je Wert. | Drei Orte; die Webseite fehlt. „Wirksame Einstellungen“ ist der vorgesehene Herkunftsnachweis (§3a). |
### 2.6 KI-Infrastruktur
| Komponente | Ist | Bewertung |
|---|---|---|
| Pakete | Keine LLM-Anbindung, kein SDK ([composer.json](../../../composer.json)). Laravel-HTTP-Client vorhanden. | Neu. Ohne neue Abhängigkeit über den HTTP-Client möglich. |
| [TenantServiceKey](../../../app/Enums/TenantServiceKey.php) | Dienst `ai_guest_mail` („KI: Gästekommunikation“) ist vorgesehen, aber `isWired() = false`; Schlüssel je Mandant in [TenantService](../../../app/Models/TenantService.php) (`api_key`), Verbrauch in [ServiceUsage](../../../app/Models/ServiceUsage.php). | Schalter, Schlüssel und Verbrauchszählung sind wiederverwendbar. |
| Betrieb | `QUEUE_CONNECTION=sync`, keine Worker auf Strato; Postfachabruf jede Minute über den Scheduler. | LLM-Aufrufe müssen begrenzt im Scheduler laufen und dürfen den Portal-Schnellweg nicht verzögern. |
## 3. Konflikte zwischen Code und v0.11
| # | Stelle | Konflikt | Folge für die Planung |
|---|---|---|---|
| **K1** | [CreateReservation](../../../app/Actions/CreateReservation.php) Z. 98, [TakeOverPortalInquiry](../../../app/Actions/TakeOverPortalInquiry.php) Z. 53 | Heute reserviert **jede** Anfrage beim Eingang für die volle Angebots-Haltefrist, auch eine unvollständige. Die v0.11 verlangt für unvollständige Anfragen stattdessen die kurze Klärungsreservierung (P01 Nr. 4: „Erst wenn die Angebots-Gates erfüllt sind, greift die unveränderte bestehende Angebots-Haltefrist“). | Für **unvollständige** Anfragen ändert sich das Eingangsverhalten; vollständige Anfragen und `SendOffer` bleiben unverändert. Folge für die eigene Webseite: Solange die Anschrift im Formular optional ist, erhalten die meisten Webseiten-Anfragen künftig 15 bzw. 180 Minuten statt 48 Stunden (vom Betreiber bestätigt, Umsetzungsplan B1/B2). |
| **K2** | [ProvideGuestContact](../../../app/Actions/ProvideGuestContact.php) Z. 51 | Überschreibt vorhandene Gastdaten ohne Abgleich; CH-03 und S5 verbieten blindes Überschreiben. | Die Übernahme läuft künftig über den Fakteneingang; die Eingabe der Vermieterin bleibt maßgeblich, aber mit Herkunft und Verlauf. |
| **K3** | [ProcessProfile](../../../app/Process/ProcessProfile.php) Z. 53, `Booking::isDirect()` | Würde die Webseite ein gewöhnlicher Kanal mit `origin_channel_id`, würden Webseiten-Anfragen A2 statt A1 und verlören „direkt“. | Die Webseite wird ein Kanal-Datensatz eigener Art **nur für die Konfiguration**; Vorgänge behalten `source = website` ohne Kanalbezug (Zielarchitektur §4). |
| K4 | Betreiberäußerung vom 02.11. („Gast soll alle seine Daten ansehen“) im historischen [Entscheidungspapier](ENTSCHEIDUNGSPAPIER_EINGANG_UND_GASTLINK.md) | CH-18 verlangt „minimale Dateneinsicht“. | **Es gilt die v0.11**: Der Link zeigt nur die für den Vorgang relevanten Angaben. Hinweis an den Betreiber, falls die frühere Äußerung weiter gewollt ist. |
| K5 | Entscheidungspapier: „Ändern vor Annahme → geändertes Angebot“, „Teilstorno“ | E-038 und CH §5: Änderungswünsche im MVP nur erkennen und manuell bearbeiten. | Es gilt die v0.11; nicht Teil der Planung. |
## 4. Abweichungsmatrix
| Anforderung (v0.11) | Ist | Abweichung | Betroffene Komponenten | Maßnahme | Paket |
|---|---|---|---|---|---|
| **G2a / E-032 / CH §1.3** Pflichtangaben vor eigenem Angebot und vor verbindlicher Wunschbestätigung (B3), Anschrift inkl. Land (B4) nicht übergehbar | teilweise | Anschrift, Personenzahl und vollständiger Name sind kein harter Blocker; die Anschrift lässt sich von Hand bestätigen; die Wunschbestätigung prüft keine Gastangaben | `DocumentComposer::commonFindings`, `SubmitBookingWish::findings`, `DecideBookingWish`, `CaseAutomation::documentBlockers`, `AutoOffer` | Anforderungsprüfung je Aktion; harter Blocker. Die Auskunft unter Vorbehalt bleibt ohne Gate | U2 |
| Informationsbedarf je nächster Aktivität (CH §4 Nr. 1, P04) | teilweise | Nur „E-Mail fehlt“; keine Feldliste je Aktion | `CaseActivities` (contact), `CaseAutomation` | `CaseRequirements` als einzige Quelle; Aktivität „Angaben vervollständigen“ | U2 |
| **S5 / CH-03** gemeinsamer Fakteneingang mit Herkunft, Ergänzung, Widerspruch, Änderungswunsch | fehlt | Keine Herkunft je Angabe; Überschreiben (K2); kein Änderungswunsch | `ProvideGuestContact`, `CreateReservation::guestFor`, neues `case_facts` | `ContributeCaseFacts` mit Feldklassen und Phasenregel | U2 |
| **S6** idempotente Neubewertung | teilweise | Mehrfacher, uneinheitlicher Einstieg; Kopie in `ProvideGuestContact` | `CaseAutomation::advance` und Aufrufer | Ein Einstieg nach jeder Übernahme | U2 |
| P03 administrative Ergänzung nach Vertragsschluss | fehlt | — | Fakteneingang | Feldklasse „administrativ“ auch in P3 übernehmen | U2 |
| E-038 Änderungswunsch erkennen, nicht ausführen | fehlt | — | Fakteneingang, `BookingTask` | Aufgabe „Änderungswunsch prüfen“; keine Änderung | U2 |
| **E-033 / G1a** Klärungsreservierung V0/V1, `0` möglich, 15/180 min | fehlt | K1; kein Zweck am Hold; `ExpireReservations` beendet den Vorgang | `CreateReservation`, `TakeOverPortalInquiry`, `ExpireReservations`, `AutoOffer`, `Booking` | Spalte `hold_purpose`; Eingangslogik für unvollständige Anfragen | U3 |
| Angebots-Vorreservierung unverändert | umgesetzt | — | `SendOffer`, `CreateReservation` (vollständige Anfragen) | Regressionstests | U3 |
| Kurzblock verlängert sich nicht durch Nachrichten | fehlt (nicht anwendbar) | — | Klärungsreservierung, Datenbeschaffung | Kein Schreibzugriff des Handlers auf `hold_expires_at` | U3/U4 |
| **E-036** extern verbindliche Buchung bleibt trotz fehlender Daten verbindlich | umgesetzt | — | `TakeOverExternalBooking`, `PortalIntake` | Regressionstest; Klärungsreservierung nie für `IntakeKind::Booking` | U3 |
| **S1 / CH-04** Kommunikationsauftrag nach Modus automatisch/Freigabe/manuell | fehlt | Nur Kopiertext | neu: Beschaffungsvorgang | `data_requests` und Aktion `RequestCaseData` | U4 |
| **S4 / E-034** zustandsabhängige Texte nach **tatsächlichem** Sperrstatus | fehlt | — | neue Mailables | Textbausteine aus dem realen `hold_expires_at`/`hold_purpose` | U4 |
| **CH-18** signierter Ergänzungslink, Lesen schreibt nicht, idempotent | fehlt | Muster vorhanden (P7) | neue Route und Controller | Nach P7-Muster mit eigener Version | U4 |
| **CH-15/16/17** Rückfrage, Folgefrage, Erinnerung; eine offene Rückfrage; Zähler ohne Reset; Obergrenzen | fehlt | — | Beschaffungsvorgang, Scheduler | Zähler und Plan am Beschaffungsvorgang | U4 |
| **CH-01/05/06** IMAP-Eingang, Deduplizierung, ein aktives Postfach (Modell für mehrere), Klärungsansicht mit Absenderhinweisen | teilweise | Nur Portal-Absender; ein Postfach als Mandantenspalten; keine Klärungsansicht für allgemeine Mails | `MailboxReader`, `Tenant`, `PortalEmail`, `FetchPortalMail` | Tabellen `mailboxes`, `inbound_messages`; Ansicht „Posteingang“ | U5 |
| **CH-07/13** deterministische Zuordnung: Antwortbezug, Portalreferenz, iCal-vor-Mail, Absender + Wohnung + Zeitraum (nur in Kombination; ein offener Vorgang desselben Absenders allein genügt nicht) | teilweise | Portal-Teil umgesetzt (`PortalIntake`); Antwortbezug und Gast-Mails fehlen | `LogBookingMail` (Message-ID), neue Zuordnung | Message-ID speichern; Zuordnungsregeln | U5 |
| **CH-08/09/12** Parser bleiben; Portal-Mail liefert Ereignis **und** Gastangaben | teilweise | Ereignis ja, Gastangaben nein | `ProcessPortalMail`, Fakteneingang, Extraktion | Gastangaben über Extraktion an den Fakteneingang | U5/U6 |
| **CH-11** Verifikation zweifelhafter Portal-Mailereignisse | teilweise | Unbekannte Mails → „Prüfen“; keine Absenderverifikation | `ProcessPortalMail` | Kriterien festlegen (Go-live), Prüfstatus | U5 |
| **CH-14 / E-035** KI-Kaskade, Prompts versioniert, Schema, Kritikalität im Programm; Eskalation auch bei Widerspruch oder fehlgeschlagener Plausibilität, unabhängig von der Modellkonfidenz | fehlt | — | neu: `app/Communication/Extraction` | Kleines Modell → Regeln → optional großes Modell → Kandidaten | U6 |
| **E-037 / CH §2a Nr. 4** zentraler Kanalmanager inkl. eigener Webseite, keine zweite Konfigurationsquelle | teilweise | Drei Orte; Webseite fehlt; neue Parameter fehlen | `ProcessSetting`, `ProcessSettings`, `Channel`, Filament-Seiten | Webseite als Konfigurationskanal; neue Parameter im bestehenden Enum | U1 |
| §3a neue Werte sichtbar unter „Wirksame Einstellungen“ | teilweise | Seite vorhanden, neue Werte fehlen | `EffectiveSettings` | Neue Zeilen und Spalte „Eigene Webseite“ | U1 |
| **M10** Testbetrieb: Versand nur an Testziel, Bestandsregression | umgesetzt (Versand) | Eingang im Testbetrieb nicht gekennzeichnet | `EnforceMailTestMode`, neue Eingangstabelle | Kennzeichen „im Testbetrieb eingegangen“ | U5 |
| Mandantentrennung | umgesetzt | — | `BelongsToTenant`, `TenantRunner` | Alle neuen Tabellen mit `tenant_id` und Scope | alle |
| P02-Änderung vor Annahme, Parallelangebote, Fristverlängerung | — | — | — | **nicht MVP** | — |
| Vertragsänderung, Teilstorno nach Vertragsschluss automatisch | teilweise manuell (Paket 5) | — | `ChangeBooking` | **nicht MVP**; bleibt manuell | — |
| Mehrere aktive Postfächer, Messenger, Gastkonto, V2/V3, generative Antworten | — | — | — | **nicht MVP** (nur Datenmodell für Postfächer) | — |
| Altersaufteilung Erwachsene/Jugendliche/Kinder | — | offen in v0.11 | — | **zu klären**; nicht Teil des Gates | — |
## 5. Wiederverwendbare Bausteine
| Baustein | Verwendung in v0.11 |
|---|---|
| `ProcessSetting` und `ProcessSettings` (Vererbung, `null` erbt, `0` ist ein Wert) | Alle neuen Parameter; kein zweites Konfigurationsmodell |
| `ProcessProfile` (eingefroren beim Eingang) | Der Vorgang behält Klärungs- und Rückfrageparameter seines Eingangs |
| `EffectiveSettings`, `process:settings-report` | Herkunftsnachweis (§3a) |
| `CaseActivities`, `CaseAutomation::advance` | Informationsbedarf, S6 |
| `DocumentComposer`/`DocumentFinding::blocker` | G2a als harter Blocker |
| `Booking::occupying`, `hold_expires_at`, `AvailabilityChecker`, iCal-Export | Klärungsreservierung ohne neue Belegungsmechanik |
| P7-Linkmuster (`InformationController`, `SubmitBookingWish`: Version, `ensureCurrent`, Sperre in der Transaktion, „bereits erledigt“) | Ergänzungslink |
| `EnforceMailTestMode`, `LogBookingMail`, `BookingMessage` | Ausgehende Rückfragen, Antwortbezug |
| `MailboxReader` (webklex), `ProcessPortalMail`, `PortalIntake` | Eingang; Portalpfad unverändert dahinter |
| `BookingTask::openOnce`, `Inbox`, `AppSupportInbox`, `CaseLog` | Freigaben, Konflikte, Änderungswünsche, Verlauf |
| `TenantService` (`ai_guest_mail`, `api_key`), `ServiceUsage`, `TenantFeatures` | Schalter, Schlüssel und Verbrauch für KI |
| `TenantRunner` und Scheduler | Erinnerungen, Abruf, Extraktion je Mandant |
## 6. Prüfgrenzen dieser Analyse
- Geprüft wurden Code und Tests im Repository. Der Server (Strato), echte Postfächer, die Unterstützung von Plus-Adressen beim Mailanbieter und LLM-Anbieter wurden nicht geprüft.
- Die in [Offene Prüfungen](../Offene_Fragen.md) zitierten früheren Agentenbefunde wurden nur geprüft, soweit sie v0.11 berühren. Nachgeprüft:
- Hold und Angebot sind gekoppelt: zutreffend, das ist K1.
- Hold nur je Wohnung gesteuert: nicht mehr zutreffend; seit Paket 1 je Mandant, Wohnung und Kanal.
- Gast-Pflichtfelder lösen Platzhalter aus: zutreffend, das ist der G2a-Befund.
@@ -0,0 +1,297 @@
# v0.11 – Technische Zielarchitektur
**Stand:** 03.11.2026 · **Status:** Planungsvorschlag zur Freigabe, keine Implementierung · Bezug: [Soll-Ist-Analyse](V011_SOLL_IST_ANALYSE.md), [Umsetzungsplan](V011_UMSETZUNGSPLAN.md), normativ [Communication Handler](../Querschnitt/Datenbeschaffung_und_Communication_Handler.md).
Die Namen von Klassen und Tabellen sind Vorschläge. Sie folgen den vorhandenen Konventionen: Geschäftsoperationen in `app/Actions`, Prozesslogik in `app/Process`, Kanäle in `app/Channels`.
---
## 1. Leitentscheidungen
1. **Kein neuer Kern.** `CaseActivities` und `CaseAutomation` bleiben führend. Der Communication Handler liefert nur Anlässe (S1 → Kommunikationsauftrag) und geprüfte Angaben (S5 → S6). Er ändert keinen Status, keine Frist und keinen Preis.
2. **Eine Konfigurationsquelle.** Alle neuen Parameter werden Fälle des bestehenden `ProcessSetting` und laufen durch `ProcessSettings::resolve`. Der Kanalmanager ist eine **Oberfläche** über den vorhandenen Speicherorten `tenants.process_defaults`, `properties.process_overrides` und `channels.process_overrides`.
3. **Die eigene Webseite ist ein Kanal-Datensatz eigener Art, nur für Konfiguration.** Vorgänge von der Webseite behalten `source = website` ohne `origin_channel_id`. So bleiben A1, `isDirect()`, Bezeichnungen und Auswertungen unverändert (Konflikt K3).
4. **Daten bleiben, wo sie sind.** Gastangaben stehen weiter in `guests`, Vorgangsangaben in `bookings`. Neu ist nur ein **Nachweisprotokoll** je Angabe (`case_facts`), keine zweite Datenhaltung.
5. **Reservierungen nutzen die vorhandene Belegungsmechanik.** Die Klärungsreservierung ist ein Hold mit eigenem Zweck (`hold_purpose`) und wird nicht als neuer Status abgebildet.
6. **Synchron und begrenzt.** Es gibt keine Queue-Worker (Strato). Abruf, Zuordnung, Extraktion und Erinnerungen laufen als begrenzte Scheduler-Schritte. Jeder Schritt ist idempotent und setzt bei einem Abbruch wieder auf.
7. **Keine neue Abhängigkeit ohne Freigabe.** Die LLM-Anbindung läuft über den Laravel-HTTP-Client hinter einer kleinen Schnittstelle.
8. **Bring your own key:**
- Jeder Mandant verbindet seinen eigenen KI-Zugang: Anbieter, Schlüssel, kleines und großes Modell.
- Es gibt keinen zentralen Betreiberschlüssel und keine im Code verdrahteten Modellkennungen.
- Die Endpunkte sind je Anbieter fest hinterlegt.
## 2. Komponenten und Datenfluss
```
┌────────────── Kanalmanager (Oberfläche) ──────────────┐
│ Mandantenstandard · Wohnung · Kanal × Eingangsart │
│ (inkl. „Eigene Webseite“) → ProcessSettings::resolve │
└───────────────────────────┬───────────────────────────┘
│ wirksame Werte (eingefroren im Profil)
Eingänge ▼
Webformular ─► CreateReservation ─► Vorgang ◄──── CaseActivities / CaseAutomation (führend)
Portal/iCal ─► PortalIntake (unverändert) │ S1: CaseRequirements → fehlende Angaben
Vermieterin ─► ViewBooking ▼
RequestCaseData (Beschaffungsvorgang, Modus, Zähler)
│ S4: Rückfrage-Mail (tatsächlicher Sperrstatus) + Ergänzungslink
▼
Gast ─► Ergänzungslink (Formular) ──────────────┐
Gast ─► E-Mail ─► IMAP ─► inbound_messages ─► Zuordnung (S3) ─► Extraktion (KI, optional)
Portal-Mail ─► inbound_messages ─► ProcessPortalMail (unverändert) ─┘ │
▼
S5: ContributeCaseFacts (Validierung, Phase, Feldklasse, Konflikt)
│ übernommen → guests/bookings + case_facts + CaseLog
▼
S6: CaseAutomation::advance (idempotent, nur im Automatikmodus)
```
## 3. Bausteine im Einzelnen
### 3.1 Konfiguration und Kanalmanager (F)
**Neue Fälle in `ProcessSetting`:**
| Schlüssel | Typ | Standard | Kanal-Eingangsarten | Quelle |
|---|---|---|---|---|
| `clarification_hold_auto_minutes` | int, `0` erlaubt | 15 | Anfrage | E-033 |
| `clarification_hold_manual_minutes` | int, `0` erlaubt | 180 | Anfrage | E-033 |
| `data_request_mode` | `automatic` / `approval` / `manual` | `approval`, technischer Vorschlag (§7 T3) | Anfrage, Buchung | CH §1.6 |
| `data_request_reminders_max` | int | 2 | Anfrage, Buchung | CH §4 Nr. 5 |
| `data_request_followups_max` | int | 2, technischer Vorschlag (offen) | Anfrage, Buchung | CH-15 |
| `data_request_reminder_hours` | int | 24, technischer Vorschlag (offen) | Anfrage, Buchung | CH-17 |
| `guest_link_valid_days` | int | 14, technischer Vorschlag (Go-live) | — (Mandant, Wohnung) | CH-18 |
- `ProcessProfile` friert sie beim Eingang wie bisher ein. `EffectiveSettings` und `process:settings-report` zeigen sie automatisch, sobald sie im Enum stehen.
- Den Wert „Klärungsreservierung bei manueller oder freigegebener Datenbeschaffung“ bestimmt der wirksame `data_request_mode`: bei `automatic` gilt der Wert für automatische Beschaffung, sonst der für Freigabe/manuell.
**Eigene Webseite als Kanal:**
- Spalte `channels.kind` mit den Werten `portal` (Bestand) und `website`. Je Wohnung gibt es einen Datensatz `website`, angelegt per Migration, ohne Connector, ohne Import, Export und Sperraufgaben.
- Neuer Scope `Channel::portals()`. Er ersetzt `active()` an den operativen Stellen: Sync, Postfach-Absender, Überwachung, `CreateChannelTasks`, `CalendarClearance`, Export-Feed, Digest, Statistik. Die Stellen sind in der Soll-Ist-Analyse §2.5 gezählt, alle durch Tests abgedeckt.
- `ProcessSettings::resolve` bekommt keinen neuen Parameter. Für eine Anfrage ohne Kanal mit `source = website` nimmt `forBooking`/`CreateReservation` den Webseiten-Kanal **nur als Einstellungsebene**. `caseTypeFor` prüft künftig `$channel?->kind === portal` statt `$channel !== null` (K3).
- Telefon und E-Mail von Hand bleiben ohne Kanal: Es gilt die Mandanten- und Wohnungsebene, wie R02 vorsieht.
**Oberfläche:**
- Der bisherige Bereich „Portale“ wird „Kanäle“ und ist in der einfachen Ansicht sichtbar.
- Oben steht der Eintrag „Alle Kanäle (Ihre Standards)“; er führt zu „So arbeite ich“, das bleibt der Ort der Mandantenstandards und Dokumentfreigaben.
- Darunter steht je Wohnung „Eigene Webseite“, dann die Portale.
- Jeder Kanal hat die Bereiche „Ablauf“ (bestehende Prozessabweichungen je Eingangsart), „Datenbeschaffung und Klärungsreservierung“ (neu) und „Anbindung“ (iCal, Regeln, Export, unverändert; bei der Webseite ausgeblendet).
### 3.2 Informationsbedarf (S1-Teil) und Gate G2a
- **`App\Process\CaseRequirements`** ist die einzige Stelle, die Pflichtangaben kennt. Sie liefert für einen Vorgang und eine Aktion eine Liste fehlender Angaben (Schlüssel, Bezeichnung, Feldklasse).
- `offer` (G2a) und `wish_confirmation` (verbindliche Bestätigung eines Buchungswunsches nach Auskunft, B3): Vorname, Nachname, E-Mail, Straße mit Hausnummer, PLZ, Ort, Land (B4), Personenzahl, An- und Abreise.
- `information` (Auskunft unter Vorbehalt): **kein** Angebots-Gate (B3). Es gelten nur die bestehenden Voraussetzungen (E-Mail, Preis, Freigaben); fehlende Angaben werden vor der Wunschbestätigung beschafft.
- Land (B4): Formulare dürfen „Deutschland“ als änderbaren Standard anbieten. Als vorhanden gilt das Land nur, wenn es aus einer Quelle stammt (Eingabe des Gastes, Bestätigung des vorbelegten Werts im Formular, Portal, Vermieterin). Ein leeres Kartenfeld wird nie still mit „DE“ gefüllt.
- `documents` für verbindliche Buchungen: wie heute nur Gast, E-Mail und Preis; keine rückwirkenden Pflichtangaben (P04).
- `arrival`: Anreisezeit, nur wenn eingestellt (Bestand).
- `DocumentComposer::commonFindings` erzeugt für `Offer` aus `CaseRequirements` **`DocumentFinding::blocker`**. Dieselbe Prüfung steht vor der verbindlichen Bestätigung eines Buchungswunsches (`SubmitBookingWish::findings`, `DecideBookingWish`) und verhindert dort die automatische wie die manuelle Bestätigung. Die Auskunft unter Vorbehalt bleibt ohne dieses Gate. Damit kann auch der manuelle Versand die fehlende Anschrift nicht übergehen (M01). Der bisherige Platzhalter-Hinweis bleibt für andere Platzhalter.
- `CaseActivities`: Die Aktivität „contact“ wird zu „Angaben vervollständigen“, mit der Liste aus `CaseRequirements` und dem Zustand „wartet auf Gast“, solange eine Rückfrage offen ist.
### 3.3 Gemeinsamer Fakteneingang (S5) und Neubewertung (S6)
**Tabelle `case_facts`** (Nachweisprotokoll, nur anfügen):
| Spalte | Inhalt |
|---|---|
| `tenant_id`, `booking_id` | Mandant, Vorgang |
| `field` | Schlüssel aus `CaseRequirements` (z. B. `guest.street`, `booking.guests`) |
| `value`, `previous_value` | neuer und bisheriger Wert (verschlüsselt, wie andere personenbezogene Felder) |
| `source` | `website_form`, `guest_link`, `email`, `portal_mail`, `llm`, `landlord` |
| `inbound_message_id`, `evidence` | Beleg: Nachricht und Textstelle |
| `confidence` | nur bei KI |
| `outcome` | `applied`, `confirmed` (gleicher Wert), `conflict`, `change_request`, `rejected` (Validierung) |
| `created_at`, `actor` | Zeitpunkt, Akteur |
**Aktion `App\Actions\ContributeCaseFacts`:** `handle(Booking, array $facts, FactSource, ?InboundMessage)`
1. Sperrt den Vorgang (`lockForTransition`) und arbeitet idempotent: Gleiche Quelle, Nachricht und Werte erzeugen nichts Neues (M03).
2. Validiert je Feld (E-Mail-Format, PLZ, Personenzahl im Rahmen der Wohnung, Datumslogik).
3. Bestimmt die Phase: P1 `Reserved`, P2 `OfferSent`, P3 `occupying()`.
4. Wendet die **Feldklassen** an:
- **administrativ:** Telefon, Anreisezeit, fehlende Anschrift oder fehlender Name bei P3;
- **angebotsrelevant:** Name, Anschrift, Personenzahl, Zeitraum, Leistungen;
- **vertragsrelevant ab P2:** Zeitraum, Personenzahl, Preis, Leistungen.
5. Regel je Feld:
| Lage | P1 | P2/P3 |
|---|---|---|
| leer → Wert | übernehmen | administrativ: übernehmen; vertragsrelevant: `change_request` |
| gleicher Wert | `confirmed` | `confirmed` |
| anderer Wert | Quelle `landlord`: übernehmen; sonst `conflict` | administrativ: `conflict`; vertragsrelevant: `change_request` |
Die Vermieterin bleibt maßgeblich; ihre Eingabe überschreibt mit Verlauf (K2 gelöst).
6. Schreibt übernommene Werte in `guests` bzw. `bookings`. Bei mehreren Vorgängen derselben Kartei gilt für eine **abweichende** Angabe aus Gastquellen immer `conflict` (Schutz fremder Vorgänge).
7. Öffnet Aufgaben: `BookingTaskKind::FactConflict` (neu) und `BookingTaskKind::ChangeRequest` (neu, E-038). Schreibt `CaseLog`.
8. Ruft **einmal** `CaseAutomation::advance` (S6) und benachrichtigt den Beschaffungsvorgang (U4), der Erinnerungen stoppt bzw. eine Folgefrage plant.
`ProvideGuestContact` und die Webformular-Übernahme (`guestFor`) rufen künftig `ContributeCaseFacts`. Die doppelte Fortsetzungslogik in `ProvideGuestContact` entfällt: Der Moduswechsel bleibt, die Fortsetzung übernimmt `advance`.
### 3.4 Klärungsreservierung (E)
- **Spalte `bookings.hold_purpose`:** `offer` (Bestand, Standard für alle Altdaten) oder `clarification`.
- **Eingang einer Anfrage** (`CreateReservation`, `TakeOverPortalInquiry`):
- **vollständig** nach `CaseRequirements::for('offer')`: unverändert (Hold = Angebots-Haltefrist, falls „Angebotsreservierung ja“);
- **unvollständig, aber V1-qualifiziert** (Wohnung, Zeitraum, verwendbare E-Mail, Verfügbarkeit positiv): `hold_purpose = clarification`, `hold_expires_at = Eingang + Minuten` (nach Modus) bzw. **kein Hold bei `0`**;
- **unvollständig, nicht qualifiziert** (keine E-Mail): kein Hold, Aufgabe.
- **Ablauf:** `ExpireReservations` beendet nur `hold_purpose = offer`. Ein abgelaufener Klärungsblock lässt den Vorgang offen (`Reserved`, Kalender frei).
- **Übergang zum Angebot:** ausschließlich über `SendOffer` bzw. `AutoOffer`. `SendOffer` prüft die Verfügbarkeit ohnehin und setzt `hold_purpose = offer` mit der unveränderten Frist. Der `AutoOffer`-Blocker „nicht mehr vorgemerkt“ gilt künftig nur für `offer`-Holds; für eine Anfrage nach abgelaufenem Klärungsblock entscheidet die erneute Verfügbarkeitsprüfung.
- **Nie** verlängert: Kein Baustein des Handlers schreibt `hold_expires_at`. Das sichert ein Architekturtest ab.
- **Nie** für `IntakeKind::Booking` (E-036).
- **Sperrstatus für Texte:** `Booking::clarificationState()` gibt `none`, `active(until)`, `expired` oder `failed` zurück, berechnet aus `hold_purpose` und `hold_expires_at`. Nur daraus werden Textbausteine gewählt (S4, M11).
### 3.5 Datenbeschaffung, Rückfrage und Ergänzungslink (B ausgehend, D)
**Tabelle `data_requests`** (Beschaffungsvorgang; je Vorgang höchstens einer offen):
| Spalte | Inhalt |
|---|---|
| `booking_id`, `tenant_id`, `status` | `draft` (wartet auf Freigabe), `open`, `answered`, `completed`, `stopped`, `manual` |
| `mode` | eingefroren aus dem Profil |
| `fields` | angefragte Angaben aus `CaseRequirements` |
| `followups_sent`, `reminders_sent` | Zähler, nie zurückgesetzt (CH-16) |
| `current_message_sent_at`, `response_due_at`, `next_reminder_at` | Antwortfrist ≠ Reservierungsfrist |
| `link_version` | Ungültigmachen älterer Links |
**Aktion `RequestCaseData` (S1):**
- Sie wird von `CaseAutomation` bzw. `CaseActivities` aufgerufen, wenn `CaseRequirements` für die nächste Aktion etwas fehlen sieht.
- Je Modus:
- `automatic`: Mail sofort;
- `approval`: Entwurf und Aufgabe „Rückfrage freigeben“ mit Vorschau;
- `manual`: Aufgabe mit Kopiertext, also das heutige Verhalten.
- Ohne verwendbare E-Mail entsteht eine Aufgabe, kein fingierter Versand.
**Mails (neue Mailables über den bestehenden Mailer, damit Testbetrieb und Protokoll greifen):**
- `DataRequested`: Erstrückfrage und gezielte Folgefrage;
- `DataReminder`: Erinnerung.
Die Textbausteine hängen ab von `clarificationState()`, Phase und Eingangsart:
- Klärungsblock `0`;
- aktiv, mit realem Datum und Uhrzeit;
- abgelaufen;
- extern verbindliche Buchung;
- P2/P3.
Antwortbezug: siehe 3.6.
**Ergänzungslink (CH-18):**
- Route `GET /angaben/{booking}` und `POST /angaben/{booking}`, `signed`, Gültigkeit aus `guest_link_valid_days`, Parameter `v = link_version`.
- **GET schreibt nichts.**
- Das Formular zeigt nur die angefragten Felder und die vom Gast für diesen Vorgang selbst angegebenen Werte (minimale Einsicht, K4). Vorbefüllt wird nur, was der Gast selbst geliefert hat.
- POST prüft Version und Status, ruft `ContributeCaseFacts(source: guest_link)` und ist idempotent.
- Bei abgelaufenem Link, abgeschlossenem Vorgang oder veralteter Version folgt eine verständliche Seite ohne Wirkung und das Angebot „neuen Link anfordern“ (Mail an die hinterlegte Adresse).
**Taktung:**
- Der Scheduler-Befehl `cases:data-requests` (alle fünf Minuten, `TenantRunner`) sendet fällige Erinnerungen (höchstens `reminders_max`).
- Danach entsteht die Aufgabe „Gast antwortet nicht“ (CH-16).
- Eine Antwort (S5) stoppt die laufende Erinnerung. Bleibt etwas offen, folgt eine gezielte Folgefrage bis `followups_max`, danach eine Aufgabe.
- Vollständigkeit, Absage oder das Ende des Vorgangs stoppen alles (CH-17).
### 3.6 Posteingang, Zuordnung und Klärung (B eingehend)
- **Tabelle `mailboxes`** (CH-05): `tenant_id`, Zugangsdaten verschlüsselt, Ordner, Aliasadressen, `is_active`, `mode` (`portal_only` = heutiges Verhalten, `full` = alle Mails).
- Migration übernimmt die heutigen `tenants.mailbox_*`.
- Je Mandant ist höchstens ein Postfach aktiv (Validierung).
- **Tabelle `inbound_messages`:**
- `tenant_id`, `mailbox_id`, `message_id` (eindeutig je Mandant), `in_reply_to`/`references`, Absender, Empfänger, Betreff, Text (verschlüsselt), Eingang;
- `test_mode` (im Testbetrieb eingegangen, M10), `status` (`new`, `assigned`, `needs_review`, `ignored`, `processed`), `booking_id`, `match_reason`, `portal_email_id`.
- **Abruf** (`channels:fetch-mail`, erweitert):
- `portal_only` wie heute;
- `full`: alle neuen Mails seit dem letzten Lauf, ungelesen lassen, Rückblick wie bisher.
- Speichern geht vor Verarbeiten. Portal-Absender laufen danach **unverändert** durch `ProcessPortalMail` (CH-08).
- **Zuordnung** (`App\Communication\MessageMatcher`, deterministisch, CH-13). Die Reihenfolge:
1. `In-Reply-To`/`References` gegen gespeicherte Message-IDs ausgehender Mails (neue Spalte `booking_messages.message_id`, gefüllt in `LogBookingMail`);
2. Vorgangskennung in Betreff bzw. Antwortadresse (Plus-Adresse, falls der Anbieter sie unterstützt; Technik **T6**);
3. Portalreferenz über `PortalIntake::caseByReference`;
4. Direkte Gast-Mail ohne Antwort- oder Vorgangsbezug: nur bei eindeutiger **Kombination** aus Absender (= hinterlegte Gast-E-Mail), Wohnung **und** Zeitraum. Wohnung und Zeitraum müssen in der Nachricht erkennbar sein und zu genau einem offenen Vorgang ohne Widerspruch passen (CH-13). Ein einziger offener Vorgang desselben Absenders allein genügt **nicht**; er erscheint nur als Hinweis in der Klärungsansicht.
Mehrere Kandidaten oder Widersprüche ergeben `needs_review` mit Hinweisen (M04). Eine Zuordnung berechtigt noch nicht zur Übernahme.
- **Klärungsansicht** (Filament-Ressource „Posteingang“):
- Liste `needs_review` mit Absenderhinweisen (bekannte Gäste und Vorgänge);
- Aktionen „Vorgang zuordnen“, „Als neue Anfrage anlegen“ (vorbefüllt, ruft die bestehende Erfassung) und „Ignorieren“.
- Eine allgemeine Mail legt nie selbst einen Vorgang an (CH-06).
### 3.7 KI-Extraktion (C)
- **Schnittstelle `App\Communication\Extraction\Extractor`:** `extract(InboundMessage, ExtractionContext): ExtractionResult`.
- Implementierungen:
- `RuleExtractor`: bestehender Portalparser und einfache Muster;
- `LlmExtractor`: kleines Modell;
- `ReviewLlmExtractor`: großes Modell, sieht Original und Erstextraktion.
- Die Modellanbindung `LlmClient` läuft über den HTTP-Client mit dem **Zugang des Mandanten** (`AiAccess`, siehe 3.8). Unterstützte Anbieter sind Anthropic (Messages API) und **OpenRouter** (Chat Completions mit `response_format: json_schema`, `strict`, `provider.require_parameters`). Die Endpunkte stehen fest im Enum `AiProvider` und lassen sich nicht über Konfiguration umlenken.
- **Prompts** liegen versioniert als Dateien unter `resources/prompts/extraction/<version>.md`, mit Platzhaltern wie `{{phase}}`, `{{requested_fields}}`, `{{known_values_masked}}`, `{{message}}`. Das JSON-Schema liegt daneben (`schema.json`). Die genutzte Version wird an jedem Ergebnis gespeichert.
- **Ausgabe:** schema-validiert. Fakten mit `field`, `value`, `evidence` (Zitat) und `confidence`; Änderungsabsichten; Unsicherheiten. Bei ungültigem Schema wird einmal wiederholt, danach geht die Nachricht in die Klärung.
- **Programmatische Risikoprüfung** (`App\Communication\Extraction\RiskAssessment`):
- Die Kritikalität ergibt sich aus Feldklasse, Phase und Art der Abweichung (vgl. 3.3).
- Eskaliert wird zum großen Modell, wenn **eine** der Bedingungen zutrifft:
- `Kritikalität × (1 − Konfidenz)` liegt über dem Schwellwert (konfigurierbar, Kalibrierung offen);
- **unabhängig von der Konfidenz:** Widerspruch zu einem vorhandenen Wert oder zu einer anderen Angabe derselben Nachricht, erkannte Änderungsabsicht in P2/P3, fehlgeschlagene Plausibilitätsprüfung (z. B. Abreise vor Anreise, Personenzahl über der Kapazität, Termine passen nicht zum zugeordneten Vorgang, Belegstelle nicht im Original).
- Die Konfidenz des Modells ist keine kalibrierte Wahrscheinlichkeit (CH-14). Sie kann eine Prüfung auslösen, aber nie eine entfallen lassen. Fakten mit Widerspruch oder fehlgeschlagener Plausibilität werden auch nach der Prüfung durch das große Modell nie automatisch übernommen, sondern der Vermieterin vorgelegt.
- **Automatische Übernahme** nur, wenn alle Bedingungen erfüllt sind: Feld bisher leer, Feldklasse administrativ oder angebotsrelevant in P1, Validierung bestanden, Belegstelle im Original gefunden (wörtlicher Abgleich), Mindestkonfidenz. Alles andere geht an die Vermieterin (`conflict` bzw. Prüfung).
- **Ergebnis:** `ContributeCaseFacts(source: llm)`. Die KI schreibt nie selbst.
- **Betrieb:**
- Schalter `ai_guest_mail` wird `isWired`;
- Schlüssel, Anbieter und Modelle je Mandant (`TenantService` des Dienstes `ai_guest_mail`), Verbrauch in `ServiceUsage`;
- je Lauf höchstens N Nachrichten, Zeitlimit je Aufruf;
- bei Ausfall bleibt die Nachricht `needs_review` (sicherer Rückfall).
- **Messung (M05):** Der Befehl `ai:evaluate` führt einen Satz anonymisierter Testnachrichten mit Sollwerten aus und meldet getrennt Fehlwerte und übersehene Angaben. Er läuft ohne Netz in den Tests mit aufgezeichneten Antworten, mit Netz nur bewusst.
### 3.8 KI-Zugang je Mandant (Bring your own key)
- **Ort:** Seite „System › KI-Anbindung“. Sie ist nur sichtbar, wenn der Betreiber den Dienst „KI: Gästekommunikation“ für den Mandanten eingeschaltet hat.
- **Felder:** Anbieter (Anthropic oder OpenRouter), API-Schlüssel, Modell für die erste Auswertung, Modell für die Prüfung. Die Modelle sind Pflicht; der Code gibt keine vor.
- **Speicherung:** im bestehenden `TenantService` des Dienstes `ai_guest_mail`.
- Schlüssel in `api_key`, verschlüsselt und `hidden`.
- Anbieter und Modelle in `settings`.
- Prüfergebnis in `check_status`, `check_message` und `checked_at`.
- **Anzeige:** Der Schlüssel wird nie wieder angezeigt. Ein leeres Feld behält ihn, „Schlüssel entfernen“ löscht ihn.
- **Keine Schlüssel in Meldungen:** Fehlermeldungen enthalten den Schlüssel nie, auch wenn der Anbieter ihn zurückspiegelt.
- **Verbindung prüfen:** Je eine minimale Anfrage mit strukturierter Ausgabe an beide Modelle; das Ergebnis wird gespeichert.
- **Abgelehnter Zugang** (HTTP 401/402/403):
- Der Zugang gilt als ungültig, und die Auswertung ist für diesen Mandanten aus, bis er gespeichert oder erneut geprüft wird. Es gibt keine Wiederholungsschleife.
- Die Vermieterin bekommt einen Hinweis im Postfach der Verwaltung.
- Die Nachrichten bleiben im Posteingang zur Prüfung.
- **Unvollständiger Zugang:** Fehlt der Zugang oder ist er unvollständig, wird nichts gesendet (`extraction_status = disabled`).
- **Wiederholung:** Nur vorübergehende Fehler werden wiederholt (Verbindung, 429, 5xx).
## 4. Datenmodelländerungen (Übersicht)
| Änderung | Rückwärtskompatibilität |
|---|---|
| `channels.kind` (Standard `portal`) und je Wohnung ein `website`-Datensatz | Bestehende Kanäle unverändert; Migration idempotent |
| `bookings.hold_purpose` (Standard `offer`) | Altdaten verhalten sich wie bisher |
| `case_facts` (neu) | Nur anfügen; kein Rückbau nötig |
| `data_requests` (neu) | — |
| `booking_messages.message_id` (nullable) | Alte Einträge ohne ID |
| `mailboxes` (neu) mit Übernahme von `tenants.mailbox_*` | Alte Spalten bleiben bis nach der Produktivmigration lesbar (wie bei `properties.hold_hours`) |
| `inbound_messages` (neu), `portal_emails.inbound_message_id` (nullable) | Portalpfad unverändert |
| `BookingTaskKind`: `FactConflict`, `ChangeRequest`, `DataRequestApproval`, `GuestUnresponsive` | Enum-Erweiterung |
| `tenant_services.settings`, `check_status`, `check_message`, `checked_at` (BYOK) | nullable; Schlüssel bleibt in `api_key` |
## 5. Sicherheit und Datenschutz (technisch)
- Signierte Links mit Mandanten- und Vorgangsbindung (Route-Model-Binding mit Mandanten-Scope wie bei P7), Version, Ablauf, Begrenzung der Aufrufe (`throttle`). Die Sicherheitsgrenzen sind nicht abschaltbar.
- Nachrichtentexte, Faktwerte und Postfach-Zugangsdaten werden verschlüsselt gespeichert. Die Löschung folgt dem bestehenden `AnonymizeGuests`-Lauf; die Frist ist offen (Go-live).
- An das LLM gehen nur die Nachricht und die angefragten Feldnamen, bekannte Werte nur maskiert. Kein Training, kein Speichern beim Anbieter, soweit vertraglich zusicherbar (Go-live).
- Die Testbetriebs-Schranke bleibt die einzige Versandschranke. Eingehende Nachrichten im Testbetrieb werden gekennzeichnet.
## 6. Beziehung zu bestehenden Abläufen
| Bestand | Wirkung der Erweiterung |
|---|---|
| iCal-Sync, Regeln, Export | keine; nur der Scope `portals()` statt `active()` |
| Portal-Schnellweg (Mail → Sperre) | unverändert; Mails werden vorher gespeichert |
| Angebot, Auskunft, Buchungswunsch, Annahme | unverändert; neu nur das Gate G2a vor dem Angebot und vor der verbindlichen Wunschbestätigung; die Auskunft bleibt ohne Gate |
| Ändern und Stornieren (Paket 5) | unverändert; Änderungswünsche erzeugen nur eine Aufgabe |
| Aufenthalt und Abschluss (Paket 9) | unverändert; Anreisezeit kann über Link oder Mail kommen |
## 7. Technische Entscheidungen im Rahmen der Umsetzung
| # | Entscheidung | Vorschlag |
|---|---|---|
| T1 | Webseite als Kanal | `channels.kind = website`, nur Konfiguration (§3.1) |
| T2 | Nachweis je Angabe | `case_facts` als Protokoll, Daten bleiben in `guests`/`bookings` |
| T3 | Technische Standards für offene Parameter | Rückfragemodus `approval`, Folgefragen 2, Erinnerungsabstand 24 h, Link 14 Tage; überschreibbar, Go-live-Freigabe |
| T4 | LLM-Anbindung | HTTP-Client; BYOK je Mandant: Anthropic oder OpenRouter, kleines und großes Modell frei wählbar (keine Vorgabe im Code), feste Endpunkte |
| T5 | Abruf im Modus `full` | Ungelesen lassen, UID-Merkpunkt je Postfach, Deduplizierung per Message-ID |
| T6 | Antwortadresse | Message-ID-Bezug und Vorgangskennung im Betreff sicher; Plus-Adresse zusätzlich, wenn der Anbieter sie zustellt |
| T7 | Eingang im Testbetrieb | normal verarbeiten, sichtbar gekennzeichnet; Versand bleibt über die Schranke umgeleitet |
@@ -0,0 +1,346 @@
# v0.11 – Umsetzungsplan
**Stand:** 03.11.2026 · **Status:** zur Prüfung und Freigabe. Die Umsetzung wird gesondert beauftragt. · Bezug: [Soll-Ist-Analyse](V011_SOLL_IST_ANALYSE.md) · [Technische Zielarchitektur](V011_TECHNISCHE_ZIELARCHITEKTUR.md) · normativ [Communication Handler](../Querschnitt/Datenbeschaffung_und_Communication_Handler.md) (CH-01–CH-18, S1–S6, M01–M12)
---
## 1. Management-Zusammenfassung
**Umfang:** sechs Pakete. Zwei davon sind kleine Grundlagenpakete (Konfiguration, Gate und Fakteneingang), eines betrifft die Reservierung, drei den Communication Handler (Rückfrage und Link, Posteingang, KI). Grob geschätzt hat das etwa den Umfang der Pakete 1–9 der v0.10 zusammen. Der größte Einzelblock ist der Communication Handler (U4–U6).
**Wesentliche Architekturentscheidungen:**
- Keine neue Engine; `CaseAutomation` und `CaseActivities` bleiben führend.
- Alle neuen Parameter laufen im bestehenden `ProcessSetting`. Der Kanalmanager ist eine Oberfläche über den vorhandenen Speicherorten.
- Die eigene Webseite wird ein Kanal-Datensatz eigener Art nur für die Konfiguration; Vorgänge bleiben A1.
- Gastdaten bleiben in `guests` und `bookings`; neu ist ein Nachweisprotokoll je Angabe.
- Die Klärungsreservierung ist ein Hold mit Zweck `clarification` in der vorhandenen Belegungsmechanik.
- Die KI liefert nur Kandidaten an den Fakteneingang.
**Wesentliche Risiken:**
1. Das Gate G2a und die Klärungsreservierung verändern das Verhalten für Webseiten-Anfragen ohne Anschrift sichtbar (K1; vom Betreiber mit B1 bestätigt).
2. Den Postfachabruf auf „alle Mails“ umzustellen berührt den Portal-Schnellweg; das wird mit einem Modus je Postfach abgesichert.
3. LLM-Qualität, Kosten und Datenschutz sind erst mit echten Testnachrichten belastbar (M05, Go-live).
4. Ohne Queue-Worker müssen Abruf und Extraktion begrenzt im Scheduler laufen.
**Tatsächliche Implementierungsblocker:** keine mehr. Der Betreiber hat B1–B4 am 03.11.2026 entschieden (§3.1). Offen sind nur technische Entscheidungen (§3.2) und Go-live-Bedingungen (§3.3).
## 2. Pakete im Überblick
| Paket | Inhalt | Abhängig von | Größe | Abnahmefälle |
|---|---|---|---|---|
| **U1** | Neue Parameter, Webseite als Kanal, Kanalmanager, „Wirksame Einstellungen“ | – | M | M12 (Konfigurationsteil) |
| **U2** | Informationsbedarf, Gate G2a, gemeinsamer Fakteneingang, Neubewertung | – | M | M01, M06 (Teil), M03 (Teil) |
| **U3** | Klärungsreservierung V0/V1 | U1, U2 | S–M | M11 (Reservierungsteil), M12 (Bestandsschutz) |
| **U4** | Beschaffungsvorgang, Rückfrage, Folgefrage, Erinnerung, Ergänzungslink, Zustandstexte | U1–U3 | L | M02 (Formular), M03, M08, M09, M11 |
| **U5** | Postfächer, Nachrichteneingang, Zuordnung, Klärungsansicht, Antwortbezug | U2, U4 (Message-ID) | L | M02 (E-Mail), M04, M07, M10 |
| **U6** | KI-Extraktion (klein → Regeln → groß), Prompts, Schema, Messung | U5 | M–L | M05, M06 |
Reihenfolge: **U1 ∥ U2 → U3 → U4 → U5 → U6**. Nach U4 ist der Nutzen schon im Betrieb verfügbar: Die fehlende Anschrift wird automatisch per Link beschafft, Antworten per E-Mail trägt die Vermieterin bis U5 von Hand ein.
---
## 3. Offene Punkte, geordnet
### 3.1 Implementierungsblocker – am 03.11.2026 entschieden
Die Tabelle zeigt die ursprüngliche Frage und die Entscheidung des Betreibers. Es bestehen keine offenen Blocker mehr.
| # | Paket | Frage | Warum blockierend | Entscheidung des Betreibers |
|---|---|---|---|---|
| **B1** | U3 | **Eingangsverhalten unvollständiger Anfragen (K1):** Bekommt eine unvollständige Anfrage künftig statt der Angebots-Haltefrist (heute 48 h ab Eingang) nur die Klärungsreservierung (15/180 min oder `0`)? Und entsteht bei Vervollständigung **kein** neuer Hold, bis das Angebot gesendet wird? | Der Code reserviert heute jede Anfrage beim Eingang. v0.11 P01 Nr. 4 und CH §2a Nr. 1 legen das nahe, ändern aber sichtbares Bestandsverhalten. | **Bestätigt.** Unvollständige unverbindliche Anfragen erhalten nur die konfigurierte Klärungsreservierung. Eine Angebots-Vorreservierung entsteht erst über den bestehenden Angebotsprozess, nicht allein durch das Ergänzen fehlender Daten. Vollständige Anfragen bleiben unverändert. |
| **B2** | U3 | **Anschrift im Webformular:** Bleibt sie optional (dann laufen die meisten Webseiten-Anfragen über Rückfrage und Kurzblock) oder wird sie über den Kanal „Eigene Webseite“ zur Pflicht (dann bleibt das 48-h-Verhalten für die Webseite)? | Bestimmt Formular, Kanalparameter und Regressionsumfang. | **Bestätigt.** Vollständige Anschrift im Webformular als Kanaleinstellung konfigurierbar; Standard zunächst **optional**. |
| **B3** | U2 | **Gate auch vor der Auskunft unter Vorbehalt (Angebots-Hold 0)?** Die v0.11 nennt das Gate „vor eigenem verbindlichem Angebot“. Bei Hold 0 entsteht die Bindung erst mit der Bestätigung des Buchungswunsches. | Sonst kommt ein Vertrag ohne Anschrift zustande. | **Entschieden:** Das vollständige Angebots-Gate gilt vor einem eigenen verbindlichen Angebot **und** vor einer verbindlichen Buchungswunschbestätigung, automatisch wie manuell. Die ausdrücklich unverbindliche Auskunft unter Vorbehalt bleibt mit unvollständigen Gastdaten möglich. |
| **B4** | U2 | **„Vollständige Postanschrift“:** Straße mit Hausnummer, PLZ, Ort **und Land**? | Feldliste des Gates. | **Bestätigt.** Die vollständige Anschrift umfasst das Land. „Deutschland“ darf als änderbarer Formularstandard angeboten werden, ist aber keine ungeprüfte Tatsachenannahme: Ein leeres Feld gilt als fehlend und wird nie still gefüllt. Der Name ist Vor- **und** Nachname. |
Die Altersaufteilung ist ausdrücklich offen und **nicht** Teil des Gates; sie blockiert nichts.
### 3.2 Technische Entscheidungen (in der Umsetzung, siehe Zielarchitektur §7)
T1 Webseite als Kanal · T2 Nachweisprotokoll `case_facts` · T3 technische Standardwerte (Rückfragemodus „Freigabe“, Folgefragen 2, Erinnerung alle 24 h, Link 14 Tage) · T4 LLM über HTTP-Client, Anbieter konfigurierbar · T5 Abrufmodus je Postfach · T6 Antwortbezug über Message-ID und Betreffkennung, Plus-Adresse optional · T7 Eingang im Testbetrieb gekennzeichnet.
Zusätzlich vor U6: Die Aufnahme eines Anbieter-SDK ist **nicht** vorgesehen. Falls doch gewünscht, braucht das eine Freigabe, weil sich die Abhängigkeiten ändern.
### 3.3 Go-live-Freigabebedingungen (blockieren die Umsetzung nicht)
| # | Bedingung | Betrifft |
|---|---|---|
| G1 | Rechtlich geprüfte Texte: Rückfrage, Folgefrage, Erinnerung, Zustandstexte (Klärungsblock 0/aktiv/abgelaufen, Portalbuchung), Linkseite | U4 |
| G2 | Endgültige Werte: Rückfragemodus je Kanal, Erinnerungsabstand, Folgefragen-Obergrenze, Linklaufzeit, Klärungsminuten je Kanal (z. B. `0` für träge iCal-Portale) | U1, U4 |
| G3 | Eigenes Postfach je Mandant eingerichtet; Zustellung von Antworten (Plus-Adresse ja/nein) geprüft | U5 |
| G4 | Datenschutz: Lesen aller Mails des Postfachs, Speicher- und Löschfristen (kein 30-Tage-Wert beschlossen), Datenschutzhinweise | U5, U6 |
| G5 | LLM-Anbieter: Auftragsverarbeitung, Speicherort, kein Training; Kosten je Nachricht | U6 |
| G6 | Kalibrierung von Konfidenz und Eskalationsschwelle an repräsentativen, anonymisierten Nachrichten; gemessene Rate übersehener Angaben akzeptiert (M05) | U6 |
| G7 | Kriterien für verlässliche Portal-Mailereignisse (CH-11) bestätigt | U5 |
| G8 | Sicherheitsprüfung der Gastlinks und des Posteingangs; Abnahme M01–M12 auf dem Testsystem; Regression v0.10 (T01–T25) | alle |
### 3.4 Spätere Erweiterungen (nicht beauftragt)
Parallele Angebotsvarianten, Angebotsänderung vor Annahme mit neuem Angebot, Fristverlängerung, automatische Vertragsänderung und Teilstorno nach Vertragsschluss, mehrere aktive Postfächer, Messenger und Social Media, generative Antworten, Gastkonto, V2/V3 des Klärungsblocks, Altersaufteilung, Leads (V02).
---
## 4. Pakete im Detail
### U1 – Parameter, Webseite als Kanal, Kanalmanager
**Ziel:** Alle Kanäle einschließlich der eigenen Webseite werden an einer Stelle verwaltet (E-037, M12). Die v0.11-Parameter sind einstellbar und wirksam sichtbar.
**Wiederverwendung:**
- `ProcessSetting`, `ProcessSettings`, `ProcessProfile`;
- `ProcessSettingFields` (Formularfelder je Einstellung);
- `ChannelForm`, `HandlingSettings`, `EffectiveSettings`, `process:settings-report`.
**Änderungen:**
1. `ProcessSetting` um die sieben Fälle der Zielarchitektur §3.1 erweitern (Standard, Frage, Eingangsarten, `normalize`, `describe`).
2. Migration `channels.kind` (`portal`/`website`) und je Wohnung ein Webseiten-Kanal. `Channel::portals()`-Scope einführen; `active()` an den operativen Stellen durch `portals()` ersetzen (Sync, `FetchPortalMail`, `ProcessPortalMail::channelFor`, `MonitorChannels`, `CreateChannelTasks`, `ChangeBooking` Z. 424, `CalendarClearance`, `ChannelController`, `DigestReport`, `BookingStats`, `ICalRuleEngine`).
3. `ProcessProfile::caseTypeFor`: A2 nur bei `kind = portal`. `CreateReservation` und `ProcessSettings::forBooking` lesen bei `source = website` den Webseiten-Kanal als Einstellungsebene. `origin_channel_id` bleibt leer.
4. Oberfläche:
- Ressource „Kanäle“, in der einfachen Ansicht sichtbar (`FollowsAdminMode`);
- Eintrag „Alle Kanäle (Ihre Standards)“ verweist auf „So arbeite ich“;
- Bereiche „Ablauf“, „Datenbeschaffung und Klärungsreservierung“, „Anbindung“; bei der Webseite ohne Anbindung;
- Schalter „Anschrift im Formular verlangen“ nach B2.
5. „Wirksame Einstellungen“: Spalte „Eigene Webseite“ und neue Zeilen.
**Migrationen:** zwei, idempotent, rückwärtskompatibel (Standard `portal`).
**Risiken:**
- Eine vergessene `active()`-Stelle würde den Webseiten-Kanal synchronisieren oder als Portal anzeigen.
- Die Ressourcenumbenennung ändert die Navigation.
**Tests:**
- Neu: Webseiten-Kanal überschreibt den Mandantenstandard für Webseiten-Anfragen; Vorgang bleibt A1 und direkt; Webseiten-Kanal erscheint in keinem Sync, keiner Sperraufgabe, keinem Export und keiner Überwachung (je ein Test über die Scope-Stellen); neue Parameter erben bzw. `0` bleibt `0`; Profil eingefroren.
- Regression: `CaseCoreTest` (Vererbung, wirksame Einstellungen), T12/T24 in `EndToEndAcceptanceTest`, Kanal-, Sync-, Export- und Postfach-Tests vollständig.
**Voraussetzungen:** keine.
### U2 – Informationsbedarf, Gate G2a, Fakteneingang, Neubewertung
**Ziel:**
- Vor einem eigenen Angebot und vor einer verbindlichen Buchungswunschbestätigung (B3) müssen alle Pflichtangaben vorliegen; das gilt nicht übergehbar (E-032, M01). Die Auskunft unter Vorbehalt bleibt mit unvollständigen Angaben möglich.
- Alle Quellen übernehmen Angaben über einen Eingang mit Herkunft, Konflikt und Änderungswunsch (S5, CH-03, E-038).
- Danach folgt genau eine Neubewertung (S6).
**Wiederverwendung:**
- `DocumentComposer`, `DocumentFinding::blocker`, `CaseAutomation::advance`;
- `CreateReservation::guestFor` (Regeln für abweichende Angaben);
- `BookingTask::openOnce`, `CaseLog`.
**Änderungen:**
1. `App\Process\CaseRequirements` (Zielarchitektur §3.2) mit der Feldliste nach B4. Formulare können „Deutschland“ als änderbaren Standard anbieten; ein leeres Land gilt als fehlend.
2. `DocumentComposer::commonFindings`: Blocker aus `CaseRequirements` für das Angebot. `SubmitBookingWish::findings` bzw. `DecideBookingWish`: dieselbe Prüfung vor der verbindlichen Bestätigung (B3); die automatische Bestätigung unterbleibt, die manuelle ist gesperrt. Die Auskunft (`SendInformation`) bleibt ohne Angebots-Gate.
3. `CaseActivities`: „Angaben vervollständigen“ mit Liste; `CaseAutomation::documentBlockers` liest `CaseRequirements`.
4. Tabelle `case_facts`; Aktion `ContributeCaseFacts` mit Feldklassen und Phasenregeln (Zielarchitektur §3.3); neue Aufgabenarten `FactConflict` und `ChangeRequest`.
5. `ProvideGuestContact` auf `ContributeCaseFacts(source: landlord)` umstellen; die doppelte Fortsetzungslogik wird durch `advance` ersetzt, der Moduswechsel bleibt. `CreateReservation::guestFor` schreibt `case_facts(source: website_form)`.
6. Die Dialoge „Kontaktdaten eintragen“ und „Angaben ergänzen“ zeigen die Herkunft der vorhandenen Werte.
**Migrationen:** `case_facts`.
**Risiken und Regressionen:**
- Tests, die Angebote für Gäste ohne Anschrift senden (Webformular-Fälle in `GuidedCaseHandlingTest`, `EndToEndAcceptanceTest`, `BookingRequestPageTest`, `DocumentCompositionTest`), müssen Anschriften liefern. Das ist eine erwartete, fachlich gewollte Änderung.
- Die `ProvideGuestContact`-Umstellung berührt Portalbuchungen (A3/A4: Unterlagen nach Kontaktdaten). Abgesichert durch T04/T05 und `PortalBookingTest`.
**Tests:**
- M01: Webseiten-Anfrage ohne Anschrift. Kein Angebot automatisch, keines von Hand, auch nicht mit Bestätigung; mit Anschrift geht es durch.
- B3:
- Auskunft unter Vorbehalt mit unvollständigen Angaben möglich;
- Buchungswunsch ohne Anschrift → keine automatische Bestätigung, manuelle Bestätigung gesperrt, Aufgabe „Angaben vervollständigen“;
- mit Anschrift → Bestätigung wie bisher.
- B4:
- leeres Land → fehlend;
- vom Gast bestätigter vorbelegter Standard → vorhanden;
- nie stilles Auffüllen der Kartei.
- Fakten:
- leer → übernommen;
- gleich → bestätigt;
- abweichend vom Gast → Konflikt, Kartei unverändert;
- abweichend von der Vermieterin → übernommen mit `previous_value`;
- in P3 Telefon → übernommen, Zeitraum → Änderungswunsch, Buchung unverändert (M06-Kern);
- gemeinsame Kartei mehrerer Vorgänge → Konflikt.
- Idempotenz: zweimal dieselbe Übermittlung → ein Eintrag, eine Neubewertung (M03-Teil).
- Externe Buchung ohne Gastdaten bleibt verbindlich (E-036).
**Voraussetzungen:** keine (B3, B4 entschieden).
### U3 – Klärungsreservierung
**Ziel:** Optionaler Kurzblock für unvollständige unverbindliche Anfragen (E-033, G1a). Die Angebots-Vorreservierung bleibt unverändert.
**Wiederverwendung:** `hold_expires_at`, `Booking::occupying`, `AvailabilityChecker`, iCal-Export, `ExpireReservations`, `AutoOffer`, `SendOffer`.
**Änderungen:**
1. Migration `bookings.hold_purpose` (Standard `offer`).
2. `CreateReservation` und `TakeOverPortalInquiry`: Fallunterscheidung vollständig / V1-qualifiziert / nicht qualifiziert (Zielarchitektur §3.4). Minuten nach `data_request_mode` des Profils; `0` = kein Hold.
3. `ExpireReservations`: nur `offer`-Holds beenden; abgelaufene Klärungsreservierung im Verlauf vermerken, den Vorgang offen lassen.
4. `AutoOffer`: Der Blocker „nicht mehr vorgemerkt“ gilt nur für `offer`-Holds.
5. `Booking::clarificationState()`; Anzeige im Vorgang („Zeitraum zur Klärung vorläufig reserviert bis …“ bzw. „nicht reserviert“).
6. Architekturtest: Außer `CreateReservation`, `TakeOverPortalInquiry`, `SendOffer`, Paket-5-Aktionen und `ReleaseReservation` schreibt niemand `hold_expires_at`.
**Migrationen:** eine Spalte.
**Risiken:**
- Sichtbare Verhaltensänderung für Anfragen ohne Anschrift (B1/B2).
- Kurzblöcke erscheinen im iCal-Export und können in trägen Portalen länger sichtbar sein (in der v0.11 bekannt; Kanalwert `0` möglich).
**Tests:**
- vollständige Anfrage → Hold wie bisher (Regression);
- unvollständige mit Automatik → 15 min, mit Freigabe → 180 min, Kanalwert `0` → kein Hold;
- ohne E-Mail → kein Hold;
- belegter Zeitraum → keine Reservierung (bestehende Ausnahme);
- Ablauf → Vorgang offen, Kalender frei;
- Vervollständigung nach Ablauf → Angebot nur bei freiem Zeitraum;
- Portalbuchung → nie Klärungsreservierung (M12-Teil);
- `SendOffer` setzt `offer` mit unveränderter Frist.
**Voraussetzungen:** U1 (Parameter), U2 (`CaseRequirements`); B1, B2 entschieden.
### U4 – Datenbeschaffung: Rückfrage, Erinnerung, Ergänzungslink
**Ziel:**
- Fehlende Angaben werden nach wirksamem Modus automatisch, nach Freigabe oder manuell beim Gast angefragt (S1, S4, CH-04, CH-15–CH-18).
- Antworten über den Link gehen an den Fakteneingang.
**Wiederverwendung:**
- P7-Linkmuster (`InformationController`, Version, `ensureCurrent`, Transaktion, „bereits erledigt“);
- Mailer mit Testbetriebs-Schranke und `LogBookingMail`;
- `BookingTask`, `TenantRunner`, Scheduler.
**Änderungen:**
1. Tabelle `data_requests`; Aktion `RequestCaseData` (Erstrückfrage, Folgefrage); Befehl `cases:data-requests` (Erinnerungen, Grenzen, Aufgabe „Gast antwortet nicht“).
2. Auslösung: `CaseAutomation`/`CaseActivities` erkennen „Angaben fehlen für die nächste Aktion“ und rufen `RequestCaseData` auf.
- Im Modus `approval` entsteht die Aufgabe „Rückfrage freigeben“ mit Vorschau, Freigabe per Klick.
- Im Modus `manual` gibt es die Aufgabe mit Kopiertext; das bisherige „Gast um Kontaktdaten bitten“ geht darin auf.
3. Mailables `DataRequested`, `DataReminder` mit Textbausteinen je `clarificationState()`, Phase und Eingangsart (M11). Die Betreffkennung des Vorgangs wird für U5 vorbereitet.
4. Ergänzungslink: Routen, Controller, Livewire- oder Blade-Formular im Theme-System (Basistheme), minimale Einsicht (K4), `ContributeCaseFacts(source: guest_link)`, „neuen Link anfordern“.
5. Antwort stoppt die laufende Erinnerung; bleibt etwas offen, folgt eine gezielte Folgefrage; Zähler werden nie zurückgesetzt.
6. Hinweis- und Aktionsfläche im Vorgang: Stand der Rückfrage, Zähler, nächste Erinnerung, „jetzt erinnern“, „Rückfrage beenden“.
**Migrationen:** `data_requests`.
**Risiken:**
- Mailtexte sind rechtlich nicht freigegeben (G1). Bis dahin laufen sie als Arbeitsfassung über die bestehende Dokumentfreigabe-Logik und werden nie automatisch versendet, solange sie nicht freigegeben sind.
- Doppelte Rückfragen bei parallelen Auslösern werden durch eine Sperre und „höchstens eine offene Rückfrage“ verhindert.
**Tests:**
- M02 (Formular, auch teilweise);
- M03 (doppeltes Absenden, Mehrfachaufruf, GET schreibt nicht);
- M08 (Teilantwort → Folgefrage, Zähler ohne Reset, Grenzen → Aufgabe, keine Fristverlängerung);
- M09 (abgelaufener, fremder und veralteter Link, Konflikt mit geändertem Wert);
- M11 (Texte bei `0`, aktiv mit echter Uhrzeit, abgelaufen, fehlgeschlagen; nie eine unbegründete Reservierungsbehauptung);
- Modi `automatic`/`approval`/`manual`;
- ohne E-Mail → Aufgabe;
- Testbetrieb → Versand nur an die Testadresse (M10-Teil);
- Portalbuchung: Rückfrage ohne Klärungs- oder Angebotstexte.
**Voraussetzungen:** U1–U3; Arbeitsfassungen der Texte (G1 erst zum Go-live).
### U5 – Posteingang, Zuordnung, Klärungsansicht
**Ziel:** Ein aktives Postfach je Mandant (Modell für mehrere), alle Mails erfasst, dedupliziert, deterministisch zugeordnet oder zur Klärung gestellt (CH-01, CH-05–CH-08, CH-11–CH-13, M04, M07, M10).
**Wiederverwendung:** `MailboxReader` (webklex), `ProcessPortalMail`, `PortalIntake::caseByReference`, `PortalEmail`-Ansicht, `Inbox`, `Settings`, Testbetriebs-Logik.
**Änderungen:**
1. Tabelle `mailboxes` mit Übernahme von `tenants.mailbox_*`; die Einstellungsseite „System › Betrieb“ bearbeitet künftig das Postfach. Modus `portal_only` als Standard, bis `full` je Mandant bewusst eingeschaltet wird.
2. Tabelle `inbound_messages`; `FetchPortalMail` speichert zuerst und verarbeitet dann. Portal-Absender gehen weiter durch `ProcessPortalMail` (verknüpft über `inbound_message_id`).
3. `booking_messages.message_id` in `LogBookingMail` füllen; Vorgangskennung im Betreff der Rückfragen.
4. `MessageMatcher` (Reihenfolge Zielarchitektur §3.6); eine Antwort an einen Beschaffungsvorgang führt zum Stand „Antwort eingegangen“, Erinnerungen ruhen. Ohne KI (vor U6) entsteht die Aufgabe „Antwort prüfen und Angaben übernehmen“ mit vorbereitetem Dialog.
5. Filament-Ressource „Posteingang“ (Klärungsansicht) mit Absenderhinweisen und den Aktionen Zuordnen, Als Anfrage anlegen, Ignorieren.
6. Kennzeichnung `test_mode`; Anzeige „im Testbetrieb eingegangen“.
**Migrationen:** `mailboxes` (mit Datenübernahme), `inbound_messages`, Spalten an `booking_messages` und `portal_emails`.
**Risiken:**
- Regression des Portal-Schnellwegs. Abgesichert durch den Modus `portal_only` als Standard, die unveränderte Verarbeitung danach und den vollständigen Lauf von `PortalMailTest` und `CaseIntakeTest`.
- IMAP-Laufzeit im Minutentakt: Begrenzung je Lauf, UID-Merkpunkt.
- Datenschutz (G4).
**Tests:**
- M04 (mehrdeutige oder allgemeine Mail → Klärung, kein Vorgang);
- M07 (iCal vor Mail und umgekehrt; späte Mail ergänzt, keine zweite Anlage);
- Antwortbezug über `In-Reply-To`;
- Absender + Wohnung + Zeitraum eindeutig → zugeordnet;
- nur Absender mit genau einem offenen Vorgang, ohne Antwort- oder Vorgangsbezug und ohne passende Wohnungs- und Zeitraummerkmale → **keine** automatische Zuordnung, sondern Klärung mit Hinweis (CH-13);
- zwei offene Vorgänge desselben Gastes → Klärung;
- gleiche Mail zweimal → einmal;
- Testbetrieb gekennzeichnet (M10);
- `portal_only` verhält sich exakt wie heute.
**Voraussetzungen:** U2 (Fakteneingang), U4 (Message-ID, Betreffkennung); G3 für die Probe auf dem Testsystem.
### U6 – KI-Extraktion
**Ziel:** Unstrukturierte Gast- und Portalnachrichten werden zu Kandidaten mit Beleg und Konfidenz. Programmatische Regeln entscheiden über Übernahme, Eskalation oder Klärung (CH-14, E-035, M05, M06).
**Wiederverwendung:** `TenantService` (`ai_guest_mail`, `api_key`), `ServiceUsage`, `TenantFeatures`, `PortalMailParser` als `RuleExtractor`, Fakteneingang.
**Änderungen:**
1. `Extractor`-Schnittstelle, `RuleExtractor`, `LlmExtractor`, `ReviewLlmExtractor`, `LlmClient` (HTTP).
- **Bring your own key:** Anbieter Anthropic oder OpenRouter, Schlüssel sowie kleines und großes Modell je Mandant über „System › KI-Anbindung“, gespeichert im `TenantService` (Schlüssel verschlüsselt, nie wieder angezeigt).
- Feste Endpunkte; Verbindungsprüfung beider Modelle.
- Ein abgelehnter Zugang schaltet die Auswertung sicher ab.
- Kein zentraler Schlüssel, keine Modellkennungen im Code.
2. Prompt-Dateien mit Version und Platzhaltern, JSON-Schema, Validierung, einmalige Wiederholung.
3. `RiskAssessment` (Kritikalität aus Feldklasse, Phase und Abweichung; Eskalationsschwelle konfigurierbar; Mindestbedingungen für die Übernahme inkl. wörtlichem Belegabgleich). Widersprüche, Änderungsabsichten in P2/P3 und fehlgeschlagene Plausibilitätsprüfungen lösen **unabhängig von der Modellkonfidenz** die weitere Prüfung aus und werden nie automatisch übernommen. Die endgültigen Schwellen folgen aus der Kalibrierung (G6).
4. Scheduler-Schritt `messages:extract` (begrenzt je Lauf, Zeitlimit); bei Ausfall bleibt `needs_review`.
5. Klärungsansicht zeigt Kandidaten mit Beleg und „übernehmen“/„verwerfen“.
6. `ai:evaluate` mit anonymisiertem Nachrichtensatz; Bericht über Fehlwerte und übersehene Angaben.
**Migrationen:** Spalten bzw. Tabelle für Extraktionsergebnisse an `inbound_messages` (Prompt-Version, Modell, Rohergebnis, Kandidaten).
**Risiken:** Qualität und Kosten (G5, G6); Modelländerungen beim Anbieter, abgefedert durch Prompt-Version und Evaluationslauf; personenbezogene Daten beim Anbieter (G5).
**Tests (ohne Netz, aufgezeichnete Antworten):**
- Schema-Verstoß → Wiederholung, dann Klärung;
- hohe Kritikalität oder niedrige Konfidenz → großes Modell;
- Widerspruch oder fehlgeschlagene Plausibilität bei **hoher** Modellkonfidenz → trotzdem großes Modell und keine automatische Übernahme;
- großes Modell widerspricht → Klärung;
- Beleg nicht im Original → keine Übernahme;
- M06 (Telefon übernommen, Änderungswunsch nur als Aufgabe);
- Ausfall → sicherer Rückfall;
- Schalter aus → keine Aufrufe;
- Verbrauch gezählt.
**Voraussetzungen:** U5; Anbieter-Zugang für das Testsystem; G5/G6 erst zum Go-live.
---
## 5. Testplanung und Regression
**Abnahmefälle M01–M12 → Pakete:**
| M | Paket | Art |
|---|---|---|
| M01 | U2 | Feature-Test und Browserprobe |
| M02 | U4 (Link), U5/U6 (E-Mail) | Feature |
| M03 | U2, U4, U5 | Feature (Idempotenz) |
| M04 | U5 | Feature |
| M05 | U6 | Evaluationslauf mit Fehlerraten |
| M06 | U2, U6 | Feature |
| M07 | U5 | Feature (auf `CaseIntakeTest` aufbauend) |
| M08 | U4 | Feature mit Zeitreise |
| M09 | U4 | Feature (signierte URLs) |
| M10 | U4, U5 | Feature und Probe auf dem Testsystem (echtes SMTP/IMAP) |
| M11 | U3, U4 | Feature (Texte je Zustand) |
| M12 | U1, U3 | Feature |
**Regression nach jedem Paket:**
- volle Testsuite (heute 702 Tests);
- End-to-End-Abnahme T01–T25 der v0.10, insbesondere T03/T04/T05 (Kontaktdaten und Portalbuchungen), T12/T24 (Wirksamkeit), T17 (Buchungswunsch) und T23 (Testbetrieb über SMTP).
**Besonders gefährdete Bestandsfunktionen:**
1. automatisches Angebot für Webseiten-Anfragen (U2/U3);
2. Portal-Schnellweg per Mail (U5);
3. iCal-Sync und Sperraufgaben (U1, Scope-Umstellung);
4. Kontaktübernahme bei Portalbuchungen (U2).
**Abnahme je Paket:**
- Testsuite grün;
- neue Fälle grün;
- Kurzbericht im Stil der bisherigen `UMSETZUNGSERGEBNIS_*.md`;
- Probe auf dem Testsystem im Testbetrieb.
Merge und Auslieferung erfolgen nur nach Freigabe.
## 6. Nicht Teil dieses Plans
Siehe §3.4 sowie die Architekturgrenzen des Auftrags: keine zweite Engine, keine Warteschlange oder Nachrückautomatik, keine Änderung von Angebots-Vorreservierung und Annahmefristen, kein Eingriff in die regelbasierte iCal-Ereignisverarbeitung, keine automatische Änderung geschützter Vertragsdaten.
+33 -2
View File
@@ -1,6 +1,38 @@
# Projektstand
## Aktueller Stand (02.11.2026)
## Aktueller Stand (03.11.2026)
**Prozessarchitektur v0.11: integrierter MVP umgesetzt (Pakete U1–U6), automatisiert getestet, noch nicht auf dem Testsystem.**
| Branch | Inhalt | Stand |
|---|---|---|
| `main` | Produktion | unverändert |
| `develop` (Testsystem stommer.info) | v0.10 Pakete 1–9, Korrekturen vom 02.11. | ausgeliefert |
| `feature/aufenthalt` | zusätzlich v0.11-Spezifikation, Planung und MVP U1–U6 | **nicht** gemergt oder ausgeliefert; Auslieferung, Postfach und KI-Schlüssel stimmt der Betreiber vorher ab |
- **Kanalmanager:** „Kanäle“ mit eigener Webseite und Portalen; neue Einstellungen für Klärungsreservierung (15/180 min, 0 = keine), Rückfragemodus, Erinnerungen, Folgefragen, Linkgültigkeit, Anschrift im Formular.
- **Angebots-Gate:** Vor Angebot und Wunschbestätigung braucht es Name, E-Mail, vollständige Anschrift mit Land, Personenzahl und Zeitraum; das lässt sich nicht übergehen. Die Auskunft bleibt ohne Gate.
- **Fakteneingang:** jede Angabe mit Herkunft (`case_facts`); Abweichungen des Gastes werden Prüfaufgaben, Zeitraum und Personenzahl nur Änderungswünsche.
- **Klärungsreservierung** für unvollständige Anfragen; der Angebots-Hold ist unverändert.
- **Datenbeschaffung:** Rückfrage, Folgefrage, Erinnerung, signierter Ergänzungslink; Texte nach tatsächlichem Sperrstatus.
- **Posteingang:** eigenes Postfach im Modus „alle Nachrichten“, Zuordnung nach CH-13, Klärungsansicht.
- **KI-Auswertung:** kleines Modell → Regeln → Prüfmodell; nur geprüfte Angaben gehen über den Fakteneingang. Der Dienst ist je Mandant standardmäßig aus.
- **KI-Zugang:** Bring your own key je Mandant (Anthropic oder OpenRouter, Seite „System › KI-Anbindung“, Verbindungsprüfung), kein zentraler Schlüssel.
- **Tests:** 766 grün.
Dokumente:
- [Umsetzungsergebnis v0.11](Prozessarchitektur/Implementierungsstände/UMSETZUNGSERGEBNIS_V011.md) (Rückverfolgung, Entscheidungen, Einschränkungen, Go-live-Bedingungen);
- [Abnahme auf dem Testsystem](Prozessarchitektur/Abnahme/V011_ABNAHME_TESTSYSTEM.md) (Dienste, Konfiguration, Drehbuch);
- Planung: [Soll-Ist](Prozessarchitektur/Implementierungsstände/V011_SOLL_IST_ANALYSE.md), [Zielarchitektur](Prozessarchitektur/Implementierungsstände/V011_TECHNISCHE_ZIELARCHITEKTUR.md), [Umsetzungsplan](Prozessarchitektur/Implementierungsstände/V011_UMSETZUNGSPLAN.md).
**Nächste Schritte:**
1. Abstimmung mit dem Betreiber: Auslieferung von `feature/aufenthalt` über `develop` auf das Testsystem (vier neue Migrationen), eigenes IMAP-Postfach, KI-Zugang des Mandanten unter „System › KI-Anbindung“ (Dienst vorher im Betreiberbereich einschalten).
2. Fachliche Abnahme nach dem Drehbuch, danach die Go-live-Bedingungen G1–G8.
3. Weiterhin aus v0.10: echte Mietbedingungen und Bank, Rechtsprüfung, Bedienprobe.
## Verlauf (historisch, neueste zuerst)
**Stand 02.11.2026:**
**Prozessarchitektur v0.10: Pakete 1–9 umgesetzt.**
@@ -26,7 +58,6 @@ ## Aktueller Stand (02.11.2026)
2. Echte Mietbedingungen und Bank eintragen, Texte freigeben, Rechtsprüfung der Gastschritte.
3. Bedienprobe mit der Vermieterin.
## Verlauf (historisch, neueste zuerst)
**Pakete 8, 5 und 6 der Prozessarchitektur v0.10 (01.11.2026, Branch `feature/abwicklung`, nicht ausgeliefert):** **Beträge und Zahlungen** – Zahlungen mit Art (Gast an uns / laut Portal ans Portal / Auszahlung Portal / Erstattung), Portalbeträge als Angaben mit Quelle (`case_amounts`), Übersicht `App\Pricing\CaseMoney` trennt Gastforderung, Portalzahlung, Auszahlung und Kontoeingang; R09 exakt erfassbar. **Ändern und Beenden** – `ChangeBooking` mit Folgenvorschau, „mit dem Gast vereinbart“ (Grundlage, Zeitpunkt) oder „dem Gast vorschlagen“ (signierter Link, Annahme mit Nachweis); ein Stornoweg mit Initiator, Grund, Kosten- und Erstattungsaufgabe; Portalbuchungen erst storniert, wenn im Portal bestätigt. **A6** – Eigene Nutzung, Besuch und Sperre als Vorgang („Neu“, Belegungsplan „+ eintragen“), Kurabgabe als Position (Satz an der Wohnung), Aufenthaltsbestätigung ohne Mietvertrag, keine Mahnung/Bewertung/Marketing; Altsperren per `cases:adopt-blocks` (Vorschau, `--apply`, `--revert`, Export identisch). **System › Wirksame Einstellungen** zeigt je Eingangsweg und Vorgang die angewandten Werte. **685 Tests grün** (inkl. Abnahmekatalog T01–T14). Dokumente: [UMSETZUNGSERGEBNIS_P5_P6_P8](Prozessarchitektur/UMSETZUNGSERGEBNIS_P5_P6_P8.md), [END_TO_END_ABNAHME](Prozessarchitektur/END_TO_END_ABNAHME.md), [KONFIGURATION_UND_WIRKSAMKEIT](Prozessarchitektur/KONFIGURATION_UND_WIRKSAMKEIT.md).
@@ -0,0 +1,30 @@
[
{
"id": "antwort-anschrift",
"subject": "Re: Ihre Anfrage 2026-0001: Bitte ergänzen Sie Ihre Angaben",
"body": "Hallo,\n\nhier unsere Anschrift: Lindenallee 12, 10115 Berlin, Deutschland. Telefon 030 1234567.\n\nViele Grüße\nGesa Gast",
"expected": {"guest.street": "Lindenallee 12", "guest.postal_code": "10115", "guest.city": "Berlin", "guest.country": "DE", "guest.phone": "030 1234567"},
"expected_changes": []
},
{
"id": "teilantwort-mit-wunsch",
"subject": "Re: Rückfrage",
"body": "Guten Tag, wir wohnen in 18225 Kühlungsborn, Strandweg 3. Können wir eventuell einen Tag länger bleiben, bis zum 11.11.2026?",
"expected": {"guest.street": "Strandweg 3", "guest.postal_code": "18225", "guest.city": "Kühlungsborn"},
"expected_changes": ["booking.departure"]
},
{
"id": "zitat-nicht-uebernehmen",
"subject": "Re: Ihre Buchung",
"body": "Danke, alles klar!\n\n> Bitte nennen Sie uns Ihre Anschrift, z. B. Musterstraße 1, 12345 Musterstadt.",
"expected": {},
"expected_changes": []
},
{
"id": "anreisezeit",
"subject": "Anreise",
"body": "Wir kommen voraussichtlich gegen 17 Uhr an. Herzliche Grüße, Familie Muster",
"expected": {"booking.arrival_time": "17:00"},
"expected_changes": []
}
]
+36
View File
@@ -0,0 +1,36 @@
{
"type": "object",
"additionalProperties": false,
"required": ["facts", "change_requests", "intent", "uncertainties"],
"properties": {
"facts": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["field", "value", "evidence", "confidence"],
"properties": {
"field": {"type": "string", "enum": ["guest.first_name", "guest.last_name", "guest.email", "guest.phone", "guest.street", "guest.postal_code", "guest.city", "guest.country", "booking.guests", "booking.arrival", "booking.departure", "booking.arrival_time"]},
"value": {"type": "string"},
"evidence": {"type": "string"},
"confidence": {"type": "number"}
}
}
},
"change_requests": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["field", "value", "evidence"],
"properties": {
"field": {"type": "string", "enum": ["booking.guests", "booking.arrival", "booking.departure", "booking.extras", "cancellation", "other"]},
"value": {"type": "string"},
"evidence": {"type": "string"}
}
}
},
"intent": {"type": "string", "enum": ["answer", "question", "change", "cancellation", "new_request", "other"]},
"uncertainties": {"type": "array", "items": {"type": "string"}}
}
}
+12
View File
@@ -0,0 +1,12 @@
You check another model's extraction from a guest's e-mail to a holiday apartment landlord. You see the original message and the first extraction. Correct it: remove values the message does not state, add details that were missed, move wishes to change something into `change_requests`, and lower the confidence of anything ambiguous. Keep `evidence` as an exact copy of the passage in the message. You only extract; you decide nothing about bookings, prices or contracts.
Context of the case (not from the guest):
- Stage of the case: {{phase}}
- Details the landlord is waiting for: {{requested_fields}}
- Details already on file (masked, for comparison only): {{known_fields}}
- Today's date: {{today}}
First extraction:
{{first_extraction}}
Return the corrected extraction in the same format. Note in `uncertainties` what you changed and why.
+16
View File
@@ -0,0 +1,16 @@
You read one e-mail that a guest of a holiday apartment sent to the landlord, and you extract structured details from it. You only extract; you never decide anything about bookings, prices or contracts.
Context of the case (not from the guest):
- Stage of the case: {{phase}}
- Details the landlord is waiting for: {{requested_fields}}
- Details already on file (masked, for comparison only): {{known_fields}}
- Today's date: {{today}}
Rules:
- Extract only what the guest states in this message about the guest or this stay. Ignore quoted earlier mails, signatures of other people and anything you would have to guess.
- `facts`: one entry per detail. `field` must be one of the allowed keys. `value` is written as the guest wrote it, normalised only as described below. `evidence` is the exact passage of the message that contains the value, copied character for character. `confidence` is your estimate between 0 and 1.
- Normalise: country as ISO 3166-1 alpha-2 code (e.g. DE), dates as YYYY-MM-DD, number of guests as a whole number, postal code without the country prefix.
- If the guest wants something to change (other dates, other number of guests, cancel, extras), put it into `change_requests` with the wished value – never into `facts`.
- `intent`: what the message mainly is.
- `uncertainties`: short notes about anything unclear, contradictory or possibly missed. Empty when there is nothing.
- If the message contains no details, return empty lists.
@@ -2,11 +2,11 @@
@php
$cell = 'padding:.4rem .5rem;border-bottom:1px solid rgba(128,128,128,.2);vertical-align:top';
$muted = 'color:#6b7280;font-size:.8rem';
$levels = [\App\Process\ProcessProfile::SYSTEM => 'Grundeinstellung', \App\Process\ProcessProfile::TENANT => 'Ihr Standard', \App\Process\ProcessProfile::PROPERTY => 'Wohnung', \App\Process\ProcessProfile::CHANNEL => 'Portal', \App\Process\ProcessProfile::CASE_TYPE => 'fest (A6)'];
$levels = [\App\Process\ProcessProfile::SYSTEM => 'Grundeinstellung', \App\Process\ProcessProfile::TENANT => 'Ihr Standard', \App\Process\ProcessProfile::PROPERTY => 'Wohnung', \App\Process\ProcessProfile::CHANNEL => 'Portal', \App\Process\ProcessProfile::WEBSITE => 'Webseite', \App\Process\ProcessProfile::CASE_TYPE => 'fest (A6)'];
@endphp
<x-filament::section heading="So lesen Sie diese Übersicht" collapsible collapsed>
<p style="font-size:.9rem">Jede Spalte ist ein Eingangsweg. Jede Zelle zeigt den Wert, der für einen <strong>neuen</strong> Vorgang auf diesem Weg gilt, und darunter, woher er kommt: Grundeinstellung → Ihr Standard (So arbeite ich) → Abweichung der Wohnung → Abweichung des Portals für Anfragen bzw. feste Buchungen. Laufende Vorgänge behalten ihr beim Eingang festgehaltenes Profil – das zeigt der Abschnitt „Einen Vorgang prüfen“. Ändern lassen sich die Werte nur an ihrer Stelle (rechte Spalte).</p>
<p style="font-size:.9rem">Jede Spalte ist ein Eingangsweg. Jede Zelle zeigt den Wert, der für einen <strong>neuen</strong> Vorgang auf diesem Weg gilt, und darunter, woher er kommt: Grundeinstellung → Ihr Standard (So arbeite ich) → Abweichung der Wohnung → Abweichung des Kanals (eigene Webseite bzw. Portal für Anfragen und feste Buchungen). Laufende Vorgänge behalten ihr beim Eingang festgehaltenes Profil – das zeigt der Abschnitt „Einen Vorgang prüfen“. Ändern lassen sich die Werte nur an ihrer Stelle (rechte Spalte).</p>
</x-filament::section>
@foreach ($this->matrix() as $block)
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff. Show more