Compare commits

...
11 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
Lars 9a9e5e157e Prozessarchitektur V0.11 2026-11-03 12:13:09 +01:00
164 changed files with 8893 additions and 255 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']);
});
}
};
File diff suppressed because it is too large. Load diff
@@ -3,7 +3,7 @@
typ: prozesslandkarte
titel: FewoPortal – Prozesslandkarte
status: fachlicher-arbeitsstand
version: "0.10"
version: "0.11"
---
# Prozesslandkarte FewoPortal
@@ -37,6 +37,8 @@ ## Einheitlicher Vorgang
Die bestehende **Owner-/Ursprungskanal-Zuordnung** ist eine vorhandene Funktion. Der technische Eingang (z. B. E-Mail/iCal), Ursprungskanal und ggf. provisionsrelevante Partnerherkunft sind begrifflich zu unterscheiden. Herkunftsketten sind **kein eigener Archetyp**.
Für die v0.11 werden **eingehende Nachrichten, Gastformular und manuelle Daten** über eine gemeinsame kontrollierte Informationsübernahme mit der vorhandenen Prozesssteuerung verbunden. Der [Communication Handler](Querschnitt/Datenbeschaffung_und_Communication_Handler.md) ist eine Querschnittsfähigkeit, kein neuer Buchungsarchetyp oder eigenständiger Workflow. Der zentrale Kanalmanager pflegt eigene Website und externe Kanäle gemeinsam; die iCal-Ereignisverarbeitung bleibt bestehen.
## Führungs- und Verantwortungsprinzip
FewoPortal ist das führende **interne** Verwaltungs- und Arbeitsinstrument. Ein externes Portal kann den Vertrag abschließen, Geld einziehen, Nachrichten oder Stornierungen bearbeiten. Im Vorgang werden deshalb **tatsächlicher Sachverhalt, Quelle, fachliche Zuständigkeit, Nachweis und erforderliche eigene Folgehandlung** festgehalten. Externe Verantwortung bedeutet nicht, dass eine Leistung nachweislich bereits erbracht wurde.
@@ -3,7 +3,7 @@
typ: archetypenkatalog
titel: Buchungsarchetypen A1–A6
status: fachlicher-arbeitsstand
version: "0.10"
version: "0.11"
---
# Buchungsarchetypen A1–A6
@@ -21,6 +21,8 @@ # Buchungsarchetypen A1–A6
**Partner-/Hub-Vertrieb ist kein A6.** Unterschiedliche Provisionen je Partner sind eine kaufmännische Eigenschaft des Ursprungskanals bzw. der Buchung; eine separate Partnerprozessklasse wird nicht benötigt. Telefon/manuell/iCal/E-Mail/API beschreiben Informations- oder Erfassungskanäle, keine eigenen Archetypen.
**v0.11-Präzisierung:** Der Communication Handler darf A1/A2-Anfragen mit fehlenden Daten nachfordern und beim eigenen Angebot erst nach vollständigen Pflichtangaben fortsetzen. Für A3–A5 gilt die externe Verbindlichkeit dagegen von Anfang an, auch wenn Gastdaten fehlen. Eine nachfolgende E-Mail oder ein Formular darf diese nicht in eine unverbindliche Anfrage verwandeln. Details stehen im [Communication-Handler-Querschnitt](Querschnitt/Datenbeschaffung_und_Communication_Handler.md).
## Verhalten im gemeinsamen Prozess
- **A1/A2:** Mit Hold > 0 kann nach geeigneter Belegungssicherung ein bindendes zeitlich befristetes Angebot verschickt werden. **Hold = 0:** reine Preis-/Verfügbarkeitsauskunft unter Vorbehalt; bei Buchungswunsch erneute Prüfung und Bestätigung entsprechend dem automatisch/manuell konfigurierten Modus. Die verbindliche Annahme eines gültigen eigenen Angebots erfordert **keine zweite Freigabe**.
@@ -3,28 +3,35 @@
typ: fachkonzept
titel: Abwicklungsprofile, Einstellungen und Dokumente
status: fachlicher-arbeitsstand
version: "0.10"
version: "0.11"
---
# Abwicklungsprofile, Einstellungen und Dokumente
## Konfiguration: Vermieterstandard und Kanalabweichung
**Mandantenregel:** Jeder Vermieter legt seine eigenen **globalen Standardeinstellungen** fest. Für einen Kanal kann er einzelne Werte ausdrücklich überschreiben. Ein **nicht gesetzter Kanalwert** erbt den globalen Vermieterwert. Das gilt auch für `0`, `nein` und `manuell`: Diese bewusst eingestellten Werte sind **keine leeren Werte**. Objekt- und Vorgangskontext beeinflussen weiterhin Preis, Belegung und Vorlagenauswahl, soweit fachlich erforderlich; eine weitergehende Hierarchie wird nicht ohne Entscheidung eingeführt.
**Mandantenregel:** Jeder Vermieter legt seine eigenen **globalen Standardeinstellungen** fest. Für einen Kanal kann er einzelne Werte ausdrücklich überschreiben. Ein **nicht gesetzter Kanalwert** erbt den globalen Vermieterwert. Das gilt auch für `0`, `nein` und `manuell`: Diese bewusst eingestellten Werte sind **keine leeren Werte**. Die in der implementierten v0.10-Betriebskonfiguration dokumentierte Hierarchie **Vermieterstandard → Wohnung → Kanal × tatsächliche Eingangsart → Vorgangsentscheidung** ist für passende Geschäftsparameter zu verwenden; die konkreten Wirkungen und Herkunftswerte müssen sichtbar bleiben. Die technische Einpassung neuer Parameter wird am Repository-Code geprüft.
Je nach Kanal **und tatsächlicher Eingangsart** werden relevante Regeln angewandt. Es gibt kein automatisches „alle FeWo-direkt-Buchungen sind gleich“. Die Konfiguration ist bewusst schlank: keine frei programmierbare Workflow-Engine erforderlich.
| Konfigurationsbereich | Zweck |
|---|---|
| Automatisch/manuell | Anfrage, Buchungswunsch und zulässige Folgeaktionen nach wirksamem Vermieterstandard oder Kanalabweichung bearbeiten; individuelle manuelle Übernahme möglich |
| Haltefrist | Für eigene/unverbindliche Anfragen: `0` = kein Hold; `>0` = befristete Reservierung mit passend befristetem bindendem Angebot (z. B. 24/48/72 Stunden) |
| **Bestehende Angebots-Haltefrist** | **Unverändert:** Für eigene Angebote: `0` = Auskunft unter Vorbehalt ohne Angebots-Hold; `>0` = befristete Reservierung mit passend befristetem bindendem Angebot (z. B. 24/48/72 Stunden). **Nicht** die Klärungsreservierung. |
| **Vorgelagerter Klärungsblock (neu)** | Für unvollständige unverbindliche A1/A2-Anfragen getrennt konfigurierbar; bei `0` keine Klärungssperre, bei `>0` kurze tatsächliche Verfügbarkeitsabsicherung nach Wohnung/Zeitraum/E-Mail-Qualifikation. Ausgangswerte 15 Minuten automatisch / 180 Minuten manuell oder Freigabe; keine Verlängerung durch Nachrichten. |
| Datenbeschaffung | Automatisch, manuell oder kombiniert; vorhandene, unvollständige und unbekannte Portalwerte unterscheiden |
| Verantwortung | Vertrags-/Dokumentenversand, Gastkommunikation, Zahlung, Mahnung, Storno/Erstattung, lokale Leistungen, Kalender-/Sperrpflege |
| Dokumentenprofil | Vorlagen und Anlagen abhängig von Vermieter, Objekt, Kanal, Eingangsart/Vorgangstyp und konkretem Vorgang |
| Konditionsquelle | Eigene Jahres-/Saisonpreise bei eigenem Angebot oder verbindlich akzeptierter Portalpreis bei extern abgeschlossenem Vertrag |
| Kanal-Fähigkeit | iCal/API/E-Mail/Portaloberfläche/manuell; Nachweis, Verzögerung, Vollständigkeit und erforderliche manuelle Schritte |
Bei **Hold = 0** ist die ursprüngliche Mitteilung **kein uneingeschränkt annehmbares Vertragsangebot**. Nach dem erneuten Verfügbarkeitscheck wird der Buchungswunsch gemäß wirksamem Modus automatisch bestätigt oder zur Vermieterentscheidung vorgelegt. Bei einem bereits verbindlich angenommenen Angebot oder extern geschlossenen Vertrag darf diese Wahl die entstandene Verbindlichkeit nicht nachträglich aufheben.
Bei **Angebots-Hold = 0** ist die ursprüngliche Mitteilung **kein uneingeschränkt annehmbares Vertragsangebot**. Nach dem erneuten Verfügbarkeitscheck wird der Buchungswunsch gemäß wirksamem Modus automatisch bestätigt oder zur Vermieterentscheidung vorgelegt. Bei einem bereits verbindlich angenommenen Angebot oder extern geschlossenen Vertrag darf diese Wahl die entstandene Verbindlichkeit nicht nachträglich aufheben.
## Zentraler Kanalmanager (v0.11)
**Alle** Kanäle einschließlich der eigenen Website werden an einem gemeinsamen fachlichen Verwaltungsort geführt. Dort werden vorhandene Kanaleigenschaften und Wohnungszuordnungen, iCal-Import/-Export mit Einstellungen und Status, tatsächliche Eingangsarten, Kommunikationswege und kanalabhängige Geschäftsparameter einschließlich des neuen Klärungsblocks zugänglich gemacht. Die bestehenden Vermieter- und Wohnungsstandards werden wiederverwendet, nicht als zweites Konfigurationsmodell kopiert. Die operative iCal-Synchronisation, Eingangserkennung und Buchungslogik bleiben außerhalb dieses Verwaltungsbausteins unverändert.
Bei Datenbeschaffung wird **Rückfragemodus** (automatisch/Freigabe/manuell) unabhängig von der vorhandenen **Angebotsfreigabe** konfiguriert. Gültige Einstellungen sind pro Vorgang nachvollziehbar; `null` bedeutet Vererbung, `0` bedeutet ausdrücklich keine Klärungssperre. Vorgänge behalten ihr beim Eingang geltendes Profil nach der bisherigen Wirksamkeitsregel. Kommunikationsnachrichten müssen den **tatsächlichen** Sperrstatus und nicht nur den konfigurierten Wunschwert verwenden. Siehe [Konfiguration und Wirksamkeit](KONFIGURATION_UND_WIRKSAMKEIT.md) und [CH-Querschnitt](Querschnitt/Datenbeschaffung_und_Communication_Handler.md).
## Dokumentarten und Auswahl
@@ -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).
+10 -2
View File
@@ -3,7 +3,7 @@
typ: entscheidungsregister
titel: Gültige fachliche Entscheidungen
status: fachlicher-arbeitsstand
version: "0.10"
version: "0.11"
---
# Gültige fachliche Entscheidungen
@@ -37,13 +37,21 @@ # Gültige fachliche Entscheidungen
| E-023 | Einheitlicher Vorgang | Jeder qualifizierte Geschäftsfall ein Vorgang, keine separat anzulegende Buchungsakte; Belegungswirkung davon unterscheidbar. |
| E-024 | A6 und Nebenleistungen | Je Anlass Gäste, Wäsche, Kurabgabe und Zahlungen möglich, auch bei Mietpreis 0; reine Sperre ohne Gast/Vertrag. |
| E-025 | Dokumente steuern den Ablauf | Zutreffendes Vorlagen-/Dokumentenprofil (inkl. Bestätigungen) nach tatsächlichem Vorgang und Kanal wählen; konkrete Nachweise versionieren. |
| E-026 | Schlanker Angebotsweg | **Haltefrist als einzige Standardfrist**: >0 bindendes Angebot passend zur Belegung, 0 Auskunft unter Vorbehalt mit erneuter Prüfung vor Bestätigung; keine separate Preisbindefrist. |
| E-026 | Schlanker Angebotsweg | **Angebots-Haltefrist als einzige Standardfrist des bestehenden Angebotswegs**: >0 bindendes Angebot passend zur Belegung, 0 Auskunft unter Vorbehalt mit erneuter Prüfung vor Bestätigung; keine separate Preisbindefrist. Der **neue optionale vorgelagerte Klärungs-Kurzblock** für unvollständige Anfragen ist davon unabhängig und keine weitere Angebotsfrist. |
| E-027 | Risikopragmatismus | Seltene Doppelbuchungen ernst nehmen, aber keine überdimensionierte Verfügbarkeits-/Risikoengine; reale Portalverzögerungen berücksichtigen. |
| E-028 | Vorhandene Owner-Zuordnung | Bereits implementierte Herkunfts-/Owner-Erkennung wiederverwenden; zunächst Ist-Abgleich statt neuer paralleler Vorgangsstruktur. |
| **E-029** | **Mandantenstandard/Vererbung** | **Globale Einstellungen gelten je Vermieter**; kanalindividuelle Werte überschreiben nur, wenn ausdrücklich gesetzt. Nicht gesetzt ≠ 0/aus/manuell. |
| **E-030** | **Automatisierung je Kanal** | Eigener Abschluss nach Hold = 0 erfolgt nach erneuter Verfügbarkeitsprüfung **automatisch oder manuell nach wirksamer Einstellung**. Bereits bestehende verbindliche Buchungen benötigen keine zweite Freigabe. |
| **E-031** | **Dokumentationsstruktur** | Fachliche Dokumente bilden eine hierarchische Prozesslandschaft und den **einen gültigen Stand** ab; wenige relevante relative Links, keine historischen Ergänzungsschichten; Änderungen in Git. |
| **E-032** | **Vorgelagerte Datenbeschaffung** | Unvollständige unverbindliche A1/A2-Anfragen sind zulässig; vor eigenem bindendem Angebot müssen Vorname, Nachname, vollständige Postanschrift, E-Mail, Zeitraum und Personenzahl plus die bestehenden Angebots-Gates erfüllt sein. Detailregel [Communication Handler](Querschnitt/Datenbeschaffung_und_Communication_Handler.md). |
| **E-033** | **Zwei getrennte Reservierungszwecke** | Optionaler Klärungsblock V0/V1 (für Wohnung, Zeitraum, E-Mail und bestandene Verfügbarkeitsprüfung; konfigurierbar 15 Minuten automatisch / 180 Minuten mit Freigabe oder manuell, je `0` möglich) geht der unveränderten Angebots-Vorreservierung voraus. |
| **E-034** | **Kanalspezifische Kommunikation** | Rückfrage, Teilantwort, Folgefrage und Erinnerung über Email oder signierten Ergänzungslink; mit Status-/Fristtexten, die nur tatsächlich wirksame Reservierungen behaupten. |
| **E-035** | **Quellen und KI** | Gemeinsamer Fakteneingang; bestehende Portalparser und iCal-Pfade bleiben; IMAP und risikobasierte kleine/große LLM-Extraktion liefern nur Kandidaten. Kontrollierte Übernahme abhängig von Phase und Feldkritikalität. |
| **E-036** | **Externe Bindung geschützt** | Bereits extern verbindliche Buchung bleibt auch bei fehlenden Gastdaten gültig; keine neue Angebotsannahme und keine Klärungsreservierung wegen fehlender Angaben. |
| **E-037** | **Zentraler Kanalmanager** | Führende fachliche Kanalverwaltung für eigenes Portal und externe Kanäle, iCal-Verbindungen, Kommunikations-/Geschäftseinstellungen und Vermieter-/Wohnungsstandards; operative iCal- und Buchungslogik bleibt bestehen. |
| **E-038** | **Änderungsgrenze MVP** | Vor Annahme: Änderungswunsch erkennen/zu manueller Bearbeitung geben. Nach Vertragsschluss: vertragsrelevante Änderungen manuell; administrative fehlende Fakten können kontrolliert ergänzt werden. Parallele bindende Angebotsvarianten und Fristverlängerung bleiben spätere P02-Spezifikation. |
## Grenze fachlicher Freigabe
Noch nicht entschieden sind insbesondere die vollständigen Abschluss-/Statuskriterien, rechtliche Einbeziehung konkreter Drittportalbedingungen, exakte örtliche Meldedaten und die tatsächliche Funktion einzelner Portalschnittstellen. Ein Coding-Agent darf technische Lösungen selbständig vorschlagen, **fachlich offene Regeln aber nicht als beschlossen ausgeben**.
@@ -0,0 +1,160 @@
# FewoPortal – Communication Handler: konsolidierter fachlicher MVP-Stand
**Stand:** 03.11.2026 · **Fassung 4** (CH-01 bis CH-18 unverändert im Beschlusskern; nachträgliche fachliche Präzisierungen und Kanalmanager ergänzt)
**Status:** Fachlich bestätigter Arbeitsstand mit ausdrücklich offenen Punkten; **keine normative Änderung** der Prozessarchitektur v0.10, **keine Implementierungsfreigabe, kein Coding-Agent-Auftrag**.
**Ausgangsbasis:** Prozessarchitektur **v0.10**, bereits vom Coding-Agenten umgesetzt. Vorhandene Angebots-Vorreservierung, Buchungs-/Stornierungslogik und regelbasierte iCal-Ereignisverarbeitung bleiben unverändert.
**Zweck:** Ein schlanker, erweiterbarer Communication Handler für eingehende Informationen, gezielte Datenbeschaffung und kontrollierte Übergabe an die bestehende Fachlogik.
**Änderungsprinzip Fassung 4:** Die vollständige Fassung 3 bleibt die Textgrundlage. Diese Revision ergänzt ausschließlich bestätigte spätere Betreiberpräzisierungen (kurze Klärungsreservierung und deren Kommunikation, Direktbuchungsschutz, zentraler Kanalmanager einschließlich eigenes Portal). Bereits beschlossene CH-01 bis CH-18, Schnittstellen, Abnahmefälle und Ausbaustufen bleiben erhalten. Noch nicht entschiedene Standardwerte und die technische Einpassung in die tatsächlichen v0.10-Dateien werden nicht als Beschlüsse ausgegeben.
## 1. Beschlossene Leitplanken
1. **Fachliche Hoheit:** `CaseActivities` / `CaseAutomation` und bestehende Fachprozesse entscheiden über die nächste Aktivität, Verfügbarkeit, Angebot, Buchung, Storno und Änderung. Der Communication Handler trifft **keine** Buchungs-/Vertragsentscheidung, führt keine neue Workflow-Engine ein und erzeugt keine zweite Fortsetzungslogik.
2. **Ein Vorgang je eigenständigem Geschäftsfall:** Eingehende E-Mails, Portalinformationen, Gastformular und manuelle Angaben können denselben Vorgang anreichern. Gleiche Nächte allein beweisen keine Gastidentität. Keine Buchungswarteschlange, kein automatisches Nachrücken und keine zweite exklusive Zusage.
3. **Phasenbezogener Informationsbedarf:** Unverbindliche Anfragen dürfen unvollständig sein. Vor einem **eigenen verbindlichen Angebot** sind Vorname, Nachname, Personenzahl, An-/Abreise, E-Mail und **vollständige Postanschrift** des Vertragspartners erforderlich. Die Anschrift ist kein übergehbarer Warnhinweis. Die bestehenden Prüfungen zu Preis, Verfügbarkeit, Dokumenten und Freigaben gelten zusätzlich. Namen aller Mitreisenden sowie vollständige Zusatzleistungswahl sind kein allgemeines Erstangebots-Gate. Die Pflicht-Unterteilung Erwachsene/Jugendliche/Kinder bleibt offen.
4. **Drei relevante Zustände:** **P1** unverbindliche Anfrage; **P2** versendetes, noch nicht angenommenes verbindliches eigenes Angebot; **P3** verbindliche Buchung/Vertrag. Nur die bestehende Prozesssteuerung bestimmt die Phase. Fehlende administrative Angaben können auch in P3 kontrolliert ergänzt werden; vertragsrelevante Änderungswünsche in P3 bleiben im MVP **manuell**. **Direktbuchungsportale:** Eine extern bereits verbindliche Portalbuchung bleibt unabhängig von fehlenden Gastdaten und vom Communication Handler verbindlich; sie wird weder auf eine unverbindliche Anfrage herabgestuft noch von einer neu eingeführten Klärungsreservierung abhängig gemacht.
5. **Zwei getrennte Reservierungszwecke:** Die vorhandene **Angebots-Vorreservierung** wird **nicht geändert**. Davon getrennt kann **vor** dem eigenen verbindlichen Angebot bei einer noch unvollständigen **unverbindlichen** Anfrage eine optionale, kurzzeitige **Klärungsreservierung** entstehen. **Mindestqualifikation für den V1-Sofortblock ist nun präzisiert:** eindeutig bestimmte Wohnung, eindeutiger An-/Abreisezeitraum, verwendbarer **E-Mail-Kontakt** und positive bestehende Verfügbarkeits-/Konfliktprüfung. **Name, Anschrift und Personenzahl werden für diesen Kurzblock noch nicht benötigt**, wohl aber gemeinsam mit Zeitraum und E-Mail für das eigene verbindliche Angebot. Ausgangswerte **15 Minuten** bei automatischer Beschaffung und **180 Minuten** bei Freigabe/manuell, jeweils konfigurierbar; **`0` = keine Klärungssperre**. Die später beispielhaft genannten **15–30 Minuten** sind keine beschlossene Ersetzung des bisherigen manuellen 180-Minuten-Ausgangswerts. Beim unmittelbaren V1-Block läuft die Zeit ab Eingang der ausreichend qualifizierten Anfrage, nicht ab späterer Bearbeitung. Antwort, Erinnerung und Folgefrage verlängern weder Klärungs- noch Angebotsfrist. Nach Ablauf vor verbindlicher Fortsetzung Verfügbarkeit erneut prüfen. V2/V3 sind nicht beschlossene spätere Optionen.
6. **Unabhängige Steuerung:** Datenbeschaffung **automatisch / Entwurf mit Versandfreigabe / manuell** ist unabhängig von der Angebotsautomatik. Vorhandene Vererbung Vermieter → Wohnung → Kanal × tatsächliche Eingangsart nutzen; `null` bedeutet erben, `0` und `false` sind ausdrückliche Werte. **Zentraler Kanalmanager:** Alle Kanäle – **einschließlich des eigenen Portals** – werden hinsichtlich Anbindung, iCal-Synchronisation und kanalbezogener Geschäfts-/Kommunikationseinstellungen an einer führenden fachlichen Verwaltungsstelle behandelt; die operative iCal- und Buchungslogik der v0.10 bleibt bestehen. Die Einpassung in den tatsächlich vorhandenen Konfigurationsbestand wird vor der Normierung geprüft.
7. **Antwortwege ohne Gastkonto:** Im MVP sind direkter E-Mail-Antwortweg und personalisierter Ergänzungslink vorgesehen. Keine verpflichtende Registrierung, kein Gast-/Loyalty-Account. Geschäftliche Entscheidungen und vertrauliche Daten werden nicht allein durch Kenntnis eines Links autorisiert.
## 2. Beschlussregister CH-01 bis CH-18
| ID | Beschluss | Bewusste Grenze |
|---|---|---|
| **CH-01** | **IMAP-Basisintegration zum Go-live**: Nachrichten empfangen, Antworten erkennen, Zuordnung und Klärung ermöglichen. | Kein selbstständig handelnder Kommunikationsagent. |
| **CH-02** | Inhaltlich erweiterte Verarbeitung von Portalmerkmalen, Betreff und Nachrichtentext; unstrukturierte/teilweise Antworten und allgemeine Anfragen berücksichtigen. E-Mail ist gleichwertiger Rückkanal neben dem Formular. | Keine autonome KI-generierte Gastkorrespondenz. Die frühere Beschränkung auf ausschließlich regelbasierte Extraktion wurde durch **CH-14** ersetzt. |
| **CH-03** | **Kontrollierte automatische Ergänzung** eindeutig zugeordneter, validierter und bisher fehlender Werte. Widersprüche nicht blind überschreiben. Rein administrative Ergänzungen auch nach Vertragsschluss; vertragsrelevante Änderungen nur als Wunsch an bestehenden Fachprozess/manuelle Bearbeitung. | Weitergehende automatische Korrektur vorhandener Werte (Option C) später. |
| **CH-04** | Unvollständige/unklare Angaben als Kandidaten dokumentieren; gezielte **regelbasierte** Rückfragen je Modus automatisch, mit Freigabe oder manuell ermöglichen. | Kein generatives freies Antwortschreiben. |
| **CH-05** | Datenmodell erlaubt mehrere Postfächer je Mandant; **Go-live: ein aktives dediziertes IMAP-Postfach** mit möglichen Aliasadressen je Mandant. | Mehrere gleichzeitige aktive Postfächer später. |
| **CH-06** | E-Mails erfassen, gegen Doppelverarbeitung sichern, bestehenden Fällen bzw. neuer Anfrage zuordnen oder in manueller **Kommunikations-Klärungsansicht** zeigen. Bekannte Absenderadressen liefern dem Bearbeiter passende Vorgangs-/Kommunikationshinweise. | Allgemeine/unklare E-Mail begründet keinen neuen Buchungsvorgang und keine Reservierungs-Queue; keine mandantenübergreifende Suche. |
| **CH-07** | Regelbasierte Zuordnung anhand technischer Referenzen und Merkmale aus Betreff/Text (Portal-/Buchungsnummer, Wohnung, Zeitraum, Absender). Nur belastbar eindeutige Zuordnung automatisieren. | Einzelindizien oder Widersprüche → Hinweise/manuelle Entscheidung; Buchungsnummer allein ist kein Identitätsnachweis. |
| **CH-08** | Bestehende Portal-Mailparser interpretieren weiterhin bekannte Formate; Handler bündelt Eingang/Kommunikation, gemeinsamer Fakteneingang, idempotente Geschäftswirkung. | Kein Neubau/Ersetzen bestehender Parser; Migration der technischen Abholung nur kontrolliert, wenn nötig. |
| **CH-09** | Eine Portal-Mail kann Buchungsereignis **und** Gastinformationen enthalten: Buchungsereignis über bestehenden Portal-/Buchungsweg, Gastdaten über Fakteneingang, Änderungsabsicht an zuständigen Fachprozess. | Extern verbindliche Buchung zuerst schützen; fehlende Gastdaten ändern ihre Verbindlichkeit nicht. |
| **CH-10** | Keine pauschale Quellenrangfolge. Buchungsereignisse, iCal-Belegung und Gastinformationen nach ihrer jeweiligen Aussagekraft bewerten. | Zweifelhafte Stornos oder Kalenderabweichungen dürfen nicht selbstständig Verfügbarkeit freigeben. |
| **CH-11** | Neue Vertrauens-/Verifikationsregeln gelten für eingehende Nachrichten des Handlers; kritische zweifelhafte Portal-Mailereignisse zur Prüfung. | **Bestehender iCal-Abgleich und dessen regelbasierte Buchungsereignisse v0.10 bleiben unverändert**; kein zusätzliches E-Mail-Gate. |
| **CH-12** | iCal und Portal-Mail dürfen in beliebiger Reihenfolge eintreffen; eindeutig zugeordnete später eintreffende Portal-Mail darf fehlende zulässige Daten des bereits existierenden Vorgangs ergänzen. | Keine zweite Buchungsanlage; bei Unsicherheit manuelle Prüfung. |
| **CH-13** | Deterministische automatische Zuordnung ohne Scoring: bekannter Antwortbezug; belastbare Portalreferenz; bei iCal-vor-Mail eindeutiger Kandidat aus Portal, Wohnung und exakt gleichen Nächten ohne Widerspruch; direkte Gast-Mail anhand eindeutiger Kombination Absender/Wohnung/Zeitraum. | Mehrdeutigkeit → nur Kandidaten; Zuordnung ist **noch keine** Übernahme- oder Änderungsberechtigung. |
| **CH-14** | **Risikobasierte zweistufige KI-Extraktion im MVP** für unstrukturierte Nachrichten: kleines LLM extrahiert strukturierte Fakten, Belegstellen, Konfidenz **je Fakt** und Änderungsabsichten. FewoPortal prüft mit **programmatischen** Regeln Buchungsphase, bestehende Werte, Widersprüche und feld-/folgenbezogene Kritikalität. Ein konfigurierbarer Eskalationsschwellwert aus Kritikalität und Unsicherheit kann eine Prüfung durch ein größeres LLM auslösen; dieses sieht Originalnachricht und Erstextraktion. | Auch hohes Modell entscheidet nichts Verbindliches; Mindestvalidierung für automatische Übernahme unabhängig vom Eskalationswert. Modellkonfidenz ist **keine kalibrierte Wahrscheinlichkeit**. Bekannte Portalparser bleiben nutzbar. |
| **CH-15** | **Initiale Rückfrage**, **gezielte Folgefrage** nach Teil-/unklarer Antwort und **Erinnerung** bei ausbleibender Antwort sind verschiedene Arten. | Folgefragen zählen nicht als Erinnerungen; eigene konfigurierbare Obergrenze verhindert Schleifen. |
| **CH-16** | Ein gemeinsamer ereignisgesteuerter Datenbeschaffungsablauf. Folgefragen- und Erinnerungszähler gelten jeweils für den **gesamten zusammenhängenden Beschaffungsvorgang**; Teilantwort setzt sie nicht zurück. Bei Grenze manuelle Aufgabe, späte Antworten weiter verarbeiten. | Keine neue Workflow-Engine; keine automatische Fristverlängerung. |
| **CH-17** | Pro Beschaffungsvorgang höchstens **eine aktuell offene automatische Rückfrage** mit zugehörigem Erinnerungsplan. Antwort hebt offene Erinnerung auf; bei Bedarf folgt gezielte neue Frage mit eigener Antwortfrist, ohne Zählerreset. Vollständigkeit, Absage oder Abschluss stoppen Nachfassen. | Kommunikationsantwortfrist ≠ Klärungsreservierung ≠ Angebotsfrist. Konkrete Intervalle weiter konfigurierbar. |
| **CH-18** | Personalisierter, zeitlich begrenzter, signierter, mandanten- und vorgangsgebundener Gastlink ohne Registrierung. Mehrfachaufruf möglich; **Lesen schreibt nicht**. Absenden prüft aktuellen Datenstand, verarbeitet idempotent und schützt gegen Konflikte. Abgelaufener Link, Versandfehler, unklare Antwort, abgeschlossener Fall → sicherer Stopp/Neuanforderung/manuelle Klärung nach Zustand. | Weitergabe des gültigen Links technisch möglich, daher minimale Dateneinsicht und keine unbefugten verbindlichen Änderungen. Keine neue Gastkontenverwaltung. |
**Aus CH-14 folgende minimale KI-Verträge:** Versionierte und konfigurierbare Prompts mit definierten Platzhaltern; schema-validierte strukturierte Ausgabe (Fakten, Belegstellen, Unsicherheiten, Änderungsabsichten); austauschbare Modellanbindung. Klein-/Großmodell liefern Kandidaten, **keine** Datenbankänderungen. Fachliche Kritikalität wird im Programm aus Feld, Änderung und Phase ermittelt, nicht vom LLM als verbindliche Geschäftsregel. Es gibt eine **gesonderte Mindestanforderung** für automatische Übernahme; unsichere Werte können auch ohne großes LLM zur manuellen Klärung gehen. Modellwahl, Gewichtung und Schwellen werden anhand repräsentativer Testnachrichten festgelegt; keine frei generierende Gastkommunikation im MVP.
## 2a. Nachträglich bestätigte fachliche Präzisierungen (ohne neue CH-Sonderfallserie)
Diese Festlegungen ergänzen CH-01 bis CH-18, ersetzen aber keine der dort dokumentierten Entscheidungen:
1. **Klärungsreservierung vor Angebots-Vorreservierung:** Nur für unverbindliche Anfragen, nur nach erfolgreicher Verfügbarkeitsprüfung und mit eindeutigem Wohnungs-/Zeitraum-/E-Mail-Bezug. Sie ist ein optionaler, konfigurierbarer Kurzblock. Für das **eigene verbindliche Angebot** werden dagegen Name, vollständige Anschrift, Personenzahl, Reisezeitraum und E-Mail sowie die bestehenden Angebots-Gates verlangt. Der Übergang zur bestehenden Angebots-Vorreservierung erfolgt ausschließlich durch den vorhandenen Angebotsprozess, nicht automatisch durch E-Mail-Antwort oder LLM-Extraktion.
2. **Gastkommunikation folgt dem *tatsächlichen* Sperrstatus:** Bei `0`, fehlgeschlagener Sperre oder bereits abgelaufener Klärungsreservierung darf keine Reservierung behauptet werden; der Gast erfährt, dass der Zeitraum bis zu einem späteren wirksamen Angebot auch anderweitig vergeben werden kann. Bei tatsächlich aktivem Kurzblock dürfen die Rückfrage-/Eingangstexte einen zeitlich befristeten Schutz **nur mit dem realen Ablaufzeitpunkt** ausdrücken und müssen klarstellen, dass noch kein verbindliches Angebot vorliegt. Dafür genügen konditionale Textbausteine innerhalb der bestehenden Nachrichtensteuerung; **keine zweite Kommunikationsprozessvariante**.
3. **Direktbuchungsportale:** Die Verbindlichkeit bereits extern wirksamer Buchungen wird durch fehlende Gastinformationen nicht relativiert. Der Handler fordert erforderliche administrative Angaben nach, ohne eine neue Klärungsreservierung, Angebotsannahme oder Neubuchung auszulösen. Eingangsart und Rechts-/Buchungsstatus ergeben sich aus dem bestehenden Portal-/Vorgangsprozess, nicht allein aus dem Transportweg iCal oder E-Mail.
4. **Zentraler Kanalmanager einschließlich eigener Website:** Ein gemeinsames führendes fachliches Konfigurationsmodell bzw. ein einheitlicher Verwaltungszugang erfasst **alle** Kanäle und kanalbezogenen Einstellungen: eigenes Portal, Anfrageportale, Direktbuchungsportale; Wohnungszuordnung; tatsächliche Eingangsart; iCal-Import/-Export und Synchronisationsparameter; Kommunikationsweg und -modus; Klärungsblock-Einstellungen; Zugriff auf vorhandene Angebots-/Prozessprofile. Allgemeine Mandanten-/Vermieterstandards bleiben zentral pflegbar und gemäß bisheriger Vererbungslogik überschreibbar. **Zielarchitektur beschlossen, konkrete Abbildung im Datenmodell der v0.10 noch anhand der Originaldokumente zu verifizieren.** Der Kanalmanager wird **keine** neue Buchungs-, iCal-Ereignis- oder Reservierungs-Engine.
### Reservierungs- und Nachrichtenzustände – verbindliche fachliche Grenze
| Tatsächlicher Zustand | Was FewoPortal dem Gast sagen darf | Wirkung |
|---|---|---|
| **Keine Klärungsreservierung (`0`)** | „Der Zeitraum ist noch nicht für Sie reserviert. Sobald die fehlenden Angaben vorliegen, prüfen wir die Verfügbarkeit erneut.“ | Anfrage/Rückfrage weiter möglich; keine exklusive Sperre. |
| **Klärungsblock konfiguriert, aber nicht wirksam angelegt** | **Keinen** Hold bestätigen; Status und erforderlichen manuellen Klärungsbedarf korrekt darstellen. | Konfiguration allein ist kein Reservierungsnachweis. |
| **Aktive Klärungsreservierung** | „Der Zeitraum ist zur Klärung bis **[tatsächliches Datum/Uhrzeit]** vorläufig reserviert; für ein verbindliches Angebot fehlen noch Angaben.“ | Kurzblock schützt nur bis zu seinem tatsächlichen Ende; **noch kein verbindliches Angebot**. |
| **Klärungsreservierung abgelaufen** | „Die Klärungsreservierung ist abgelaufen. Ihre Angaben können weiter übermittelt werden; wir prüfen die Verfügbarkeit erneut.“ | Keine rückwirkende Fristverlängerung und kein Vorrang allein durch frühere Anfrage. |
| **Eigenes verbindliches Angebot versendet** | Nur der aus dem **bestehenden** Angebotsprozess feststehende Angebots- und Annahmestatus mit dessen realer Frist. | Angebots-Vorreservierung nach unveränderter v0.10. |
| **Extern verbindliche Direktbuchung** | Tatsächliche Buchungsbestätigung/Informationsanforderung, **keine** unverbindliche Klärungsreservierungs-Mitteilung. | Bestehende Buchung bleibt unabhängig von fehlenden Gastdaten geschützt. |
Die Beispieltexte sind **fachliche Zustandsformulierungen, keine rechtlich freigegebenen E-Mail-Vorlagen**. Der Handler muss vor Versand den tatsächlichen Zustand abfragen; er darf keine Ablaufzeit nur aus einem Defaultwert vortäuschen. `0` deaktiviert ausschließlich die Klärungssperre, nicht Informationsbeschaffung, Erinnerungen oder spätere Prüfung eines verbindlichen Angebots.
## 3. Minimale fachliche Schnittstellen
Die Bezeichnungen beschreiben **logische Verträge**, keine vorgegebene Anzahl neuer Services oder Datenbanken.
| Nr. | Sender → Empfänger | Minimaler Inhalt / Ergebnis |
|---|---|---|
| **S1** | Requirements Check / `CaseAutomation` → Handler | Mandant/Vorgang/Phase, nächste Aktion, fehlende Pflichtangaben, zulässiger Kommunikationsweg, Rückfragemodus, tatsächlicher Sperrstatus/-ablauf → Kommunikationsauftrag oder manuelle Aufgabe. Maßgeblich sind die aus dem zentralen Kanalmanager ermittelten **wirksamen** Kanal- und Vorgangseinstellungen. |
| **S2** | IMAP / bestehende Portalparser / Formular / manuelle Eingabe → Nachrichteneingang | Nachrichtenidentität, Quelle, Zeit, Absender/Empfänger und Antwortbezug, Originalnachricht bzw. strukturierte Eingabe. iCal bleibt auf seinem vorhandenen Ereignispfad. |
| **S3** | Nachrichteneingang → Zuordnung und Extraktion | Ein eindeutig verknüpfter Vorgang, neue Anfrage an vorhandene Eingangserfassung oder ungeklärte Nachricht; Fakten-/Änderungskandidaten mit Herkunft, Beleg, Konfidenz und Prüfbedarf. Eine Nachricht darf mehrere fachliche Inhalte enthalten. |
| **S4** | Handler ↔ ausgehender Mailweg / Gastformular | Zustandsabhängiger Textbaustein **mit oder ohne tatsächlich aktiven Klärungsblock**, ggf. realer Ablaufzeitpunkt, Versand-/Freigabestatus, Antwortfrist/Erinnerungsplan, Antwortbezug; sicherer Formularlink mit relevanten vorbefüllten Daten und erlaubten Korrekturen. Direkte E-Mail-Antwort bleibt möglich. **Antwortfrist ist keine Reservierungsfrist.** |
| **S5** | Formular / Parser / KI / manuelle Eingabe → gemeinsamer Fakteneingang | Validierung, Quellenbeleg, aktuell gültige Phase, bisheriger Wert, Ergänzung vs. Widerspruch vs. Änderungswunsch → zulässige Ergänzung oder Prüfauftrag; nie blindes Überschreiben verbindlicher Daten. |
| **S6** | Fakteneingang → bestehende `CaseAutomation` | Idempotenter Anlass zur Neubewertung der nächsten Aktivität; bestehende Preis-, Verfügbarkeits-, Angebots- und Freigabelogik greift unverändert. |
**Konfigurationsfluss (querschnittlich zu S1–S6):** Der **zentrale Kanalmanager** ist fachlich führender Verwaltungsort für Kanaldefinitionen, iCal-Verbindungs-/Synchronisationskonfiguration, Kommunikations- und Klärungsparameter sowie die Zuordnung zu Vermieter-/Wohnungsstandards – einschließlich des eigenen Portals. Die existierenden Laufzeitkomponenten lesen die jeweils **wirksame Konfiguration**. Das bedeutet **nicht**, dass iCal-Sync oder der Communication Handler technisch in einen einzigen Service umgebaut werden müssen. Die reale Umsetzung/Einpassung wird nach Bereitstellung des v0.10-Dokumentensatzes abgeglichen; keine konkurrierenden neuen Konfigurationsquellen schaffen.
**Kontrollfluss:** IMAP-Erfassung und KI-Extraktion allein verändern keine Buchung. Erst nach zulässiger Datenübernahme wird die bestehende Fachlogik neu bewertet. Ein erkanntes Änderungsbegehren ist **nicht** selbst die Änderung.
## 4. Ein gemeinsamer Datenbeschaffungsablauf
1. Eine unverbindliche Anfrage oder ein bestehender Vorgang hat einen **phasenbezogenen** Informationsbedarf. Der Requirements Check benennt nur die für die nächste Aktivität fehlenden Angaben.
2. Gemäß **wirksamer Kanal- und Eingangsartkonfiguration** wird eine E-Mail automatisch, nach Freigabe oder manuell veranlasst. Bei fehlendem Rückweg entsteht eine Aufgabe; kein fingierter Versand. Eine **optionale Klärungssperre** wird ausschließlich nach den für V1 bestätigten Mindestdaten (Wohnung, Zeitraum, verwendbare E-Mail, Verfügbarkeit) geprüft; `0` heißt ausdrücklich **keine Sperre**. Die Rückfrage nutzt einen Textbaustein für den **wirklichen** Sperrstatus, nicht für den bloß konfigurierten Sollwert.
3. Der Gast antwortet über den **signierten Ergänzungslink** oder direkt per E-Mail. IMAP und Formular liefern an denselben Fakteneingang; unvollständige Antworten bleiben erhalten.
4. Bestehende Portalparser und die KI-Extraktion liefern **Informationskandidaten**. Programmatische Zuordnungs-, Vertrauens-, Validierungs- und phasenabhängige Übernahmeregeln entscheiden über Automatik oder manuelle Klärung.
5. `CaseAutomation` prüft die nächste Aktivität erneut. Bei offenen Angaben folgt nach Konfiguration eine **gezielte Folgefrage** oder manuelle Aufgabe; bei ausbleibender Antwort gegebenenfalls eine **Erinnerung**. Höchstens eine aktive automatische Rückfrage, getrennte nicht rücksetzbare Zähler; Erinnerungs-Standard **maximal zwei zusätzliche Nachrichten**.
6. Nach Datenvollständigkeit führt die **bestehende** Prozesssteuerung weiter. Erst wenn **alle Angebots-Pflichtdaten** einschließlich Name, Anschrift und Personenzahl sowie die bestehenden fachlichen Gates erfüllt sind, kann der **vorhandene Angebotsprozess** mit seiner **unveränderten Angebots-Vorreservierung** greifen. Kommunikationsfristen verändern keine Reservierungs-/Annahmefrist. Bei Ablauf einer Klärungssperre bleibt der Vorgang bearbeitbar; vor verbindlichem Angebot sind Verfügbarkeit/Konditionen erneut zu prüfen. **Bereits verbindliche Direktbuchungen** bleiben unabhängig hiervon geschützt und werden nur nach ihrer bestehenden Eingangs-/Buchungslogik angereichert.
## 5. Go-live-Umfang und Abgrenzung
**Zum ersten Go-live enthalten:**
- Ein aktives dediziertes IMAP-Postfach je Mandant (Aliase möglich); nachvollziehbare Erfassung und Deduplizierung, Zuordnung, manuelle Kommunikations-Klärungsansicht mit Absenderhinweisen.
- Bestehende Portalparser erhalten; Gast- und Portal-E-Mail-Inhalte bei Bedarf durch **kleines LLM → programmatische Risikoprüfung → optional großes Prüf-LLM** strukturieren; Prompts, Platzhalter und Ausgabeformat versionieren. Kein Agentendialog.
- Ausgehende Rückfragen über bestehenden Versand-/Testmodus; sicheres vorbefülltes Ergänzungsformular ohne Registrierung, direkte Antworten per E-Mail, regelbasierte Folgefragen und Erinnerungen mit Grenzen.
- Gemeinsame, phasenabhängige Faktenübernahme und idempotente Neubewertung durch bestehende `CaseAutomation`.
- Optionale Klärungsreservierung V0/V1 mit präzisierter Mindestqualifikation (Wohnung + Zeitraum + verwendbarer E-Mail-Kontakt + positive Verfügbarkeitsprüfung) und **zustandsabhängigen Rückfragehinweisen** bei Sperre `0` bzw. tatsächlich aktivem Kurzblock; keine Änderung der bestehenden Angebots-Vorreservierung. Die bestehende iCal-Ereigniserkennung wird nicht vom Handler ersetzt oder gesperrt.
- **Zentraler Kanalmanager als gemeinsame Verwaltungs-/Konfigurationsverantwortung** für eigenes Portal und externe Kanäle einschließlich iCal-Sync-Einstellungen, Geschäfts-/Kommunikationsparametern und zentralen Vermieterstandards; operative iCal- und Buchungslogik bleibt an ihrem bisherigen Ort. Für den MVP schrittweise Integration in vorhandene Konfiguration statt Neubau einer Channel-Management-Plattform.
**Nicht Bestandteil des Communication-Handler-MVP:**
- Parallele alternativ annehmbare verbindliche Angebotsversionen; automatische Angebotsänderungs-/Reservierungsvarianten und eine einmalige Verlängerung der ursprünglichen Angebotsfrist.
- Automatische vertragsrelevante Änderungen **nach** Vertragsschluss, Teilstorno oder automatische Stornierung/Neubuchung. Allenfalls **manuell zu prüfender** Übergangsweg; kein beschlossener Standard.
- Generative Gastkommunikation, KI-Agenten mit Aktionserlaubnis, Messenger-/Social-Media-Adapter, mehrere aktive Postfächer je Mandant, Benutzerregistrierung und Loyalty-/CRM-Programm.
- Neue Portalparser-/iCal-Engine, umfassende eigenständige Channel-Management-Plattform mit eigenem Buchungskern, Warteliste/Nachrücken oder zusätzliche Klärungsreservierungsvarianten V2/V3.
**P02-Abgrenzung:** Änderungswünsche vor Annahme eines eigenen verbindlichen Angebots werden im MVP **erkannt, zugeordnet und zur kontrollierten manuellen/fachlichen Bearbeitung vorgelegt**. Keine automatische parallele Angebotsverwaltung und keine stillschweigende Änderung des gültigen Angebots oder seiner Frist. Die rechtlich/fachlich vollständige P02-Änderungslogik bleibt gesondert offen. Nach Vertragsschluss gilt zunächst manuelle Bearbeitung vertragsrelevanter Änderungen; administrative Ergänzungen nach CH-03 bleiben möglich.
## 6. Minimale fachliche Abnahmefälle
| ID | Durchgangstest | Erwarteter Nachweis |
|---|---|---|
| **M01** | Unverbindliche Website-Anfrage ohne vollständige Anschrift | Vorgang erfasst, Rückfrage; **kein eigenes verbindliches Angebot** trotz manuellem Warnungs-Override. |
| **M02** | Antwort per E-Mail und/oder Gastformular, auch nur teilweise | Fehlende eindeutige Werte kontrolliert ergänzen, Restbedarf neu bewerten; keine Buchung allein durch Absenden. |
| **M03** | Gleiche Nachricht wiederholt; mehrfacher Formularaufruf/-submit | Idempotente Übernahme/Fortsetzung; keine Doppelbuchung. |
| **M04** | Allgemeine/mehrdeutige E-Mail oder zweifelhafte Zuordnung | Kein automatischer falscher Vorgangsbezug; Klärungsansicht mit Hinweisen. |
| **M05** | Mehrdeutige oder risikobehaftete Nachricht; kleine KI übersieht eventuell ein wesentliches Datum | Eskalations-/Prüfregeln und sicherer Fehlerfallback nachweisen; **übersehene Angaben separat als Fehlerrate messen**. Kein System kann die Erkennung jeder Auslassung garantieren. |
| **M06** | E-Mail enthält eindeutige fehlende Telefonnummer und möglichen Vertragsänderungswunsch | Administrative Ergänzung zulässig; Änderungswunsch nur aufnehmen/weiterreichen; keine Vertragsänderung. |
| **M07** | iCal vor Portal-Mail und umgekehrt | Bestehender iCal-Pfad unverändert; spätere eindeutige Mail ergänzt zulässige Gastdaten, kein zweiter Geschäftsvorgang. |
| **M08** | Teilantwort, Folgefrage, Erinnerung, Fristablauf | Pro Beschaffungsvorgang eine aktive automatische Rückfrage; getrennte Zähler ohne Reset; keine Verlängerung von Klärungs- oder Angebotsfrist. |
| **M09** | Abgelaufener/fremder Link, Konflikt mit zwischenzeitlich geändertem Wert, Versandfehler | Keine unbefugte Datenmutation; idempotente Behandlung und sichtbarer Prüf-/Fehlerfall. |
| **M10** | Test-Mailversand und Bestandsregression | Versand nur an Testziel, nicht als reale Gastzustellung markiert; iCal-Import/-Export unabhängig; vorhandene Angebots- und Portalpfade bestehen. |
| **M11** | Anfrage mit Klärungsblock `0`, mit aktivem 15-/konfiguriertem Kurzblock, mit fehlgeschlagener/abgelaufener Sperre | Nachricht unterscheidet „keine Reservierung“ von tatsächlich reserviertem Zeitraum mit echtem Ablaufzeitpunkt; niemals unbegründete Reservierungsbehauptung; Angebots-Vorreservierung unverändert. |
| **M12** | Eigenes Portal und externes Direktbuchungsportal über zentrale Kanalkonfiguration | Eigenes Portal wird wie ein Kanal konfiguriert; iCal-Sync-Einstellungen bleiben verwaltbar und operativ unverändert. Extern verbindliche Direktbuchung bleibt trotz fehlender Gastdaten gültig und erhält keinen neuen Klärungs-/Angebotsprozess. |
## 7. Wenige noch offene Punkte – geordnet für Abschlussarbeiten
### A. Abschluss- und Integrationsprüfung (bereits geklärte Punkte nicht erneut öffnen)
1. **Klärungsreservierung V1 – Grundsatz abgeschlossen:** Mindestqualifikation **Wohnung + eindeutig datierter Zeitraum + verwendbarer E-Mail-Kontakt + erfolgreiche Verfügbarkeitsprüfung** ist nun festgelegt. **Nur die konkrete Kanalparametrierung** (u. a. `0` für Portale mit trägem iCal-Abruf) ist im Umsetzungs-/Betriebskontext zu bestimmen. Die beschlossenen Ausgangswerte **15/180 Minuten** bleiben bis zu einer ausdrücklichen Änderung bestehen; 15–30 Minuten wurde als Beispiel genannt, **nicht** als neuer Standard beschlossen.
2. **Pflichtdaten und Datenhoheit – Prinzip beschlossen, Detailbedarf begrenzt:** Vor eigenem Angebot sind **Name, vollständige Anschrift, Personenzahl, Zeitraum und E-Mail** zwingend. **Noch offen** bleibt die Pflicht zur Altersunterteilung Erwachsene/Jugendliche/Kinder und die präzise Feldklassifikation bei P1/P2/P3 für die Umsetzung. Die grundlegende kontrollierte automatische Ergänzung administrativer Angaben (CH-03) wird **nicht** neu verhandelt.
3. **Nachrichtenverifikation und KI-Automatik:** Konkrete, testbare Kriterien für hinreichend verlässliche Portal-Mailereignisse; minimaler Feldkatalog/JSON-Schema, Prompt-/Kontextgrenzen, Eskalationsregel und Ausfallverhalten. **LLM-Selbstauskunft zur Konfidenz erst anhand Testdaten kalibrieren**; bestehender iCal-Pfad bleibt ausgenommen.
4. **Kommunikationsparameter und Sicherheit:** Obergrenze automatischer Folgefragen, Antwort-/Erinnerungsintervalle, Stopps, Versandfehler; Gastlink-Laufzeit und Sichtbarkeit; **zustandsabhängige Textbausteine** mit realem Sperrstatus, rechtliche Freigabe konkreter Formulierungen, Berechtigungen, Testbetrieb, Speicher-/Löschfristen und Datenschutz-/Sicherheitsprüfung vor Livebetrieb. **Kein verbindlich beschlossener 30-Tage-Löschwert.**
5. **Kanalmanager / Integrationsabgleich:** Die **fachliche zentrale Verwaltung einschließlich eigenes Portal und iCal-Konfiguration** ist beschlossen. **Offen ist keine neue Grundsatzfrage**, sondern die konkrete Zuordnung zu den vorhandenen v0.10-Modulen, Tabellen, Konfigurationen und Admin-Ansichten nach Sichtung des Repositories. Doppelte „Sources of Truth“ sind zu vermeiden.
### B. Dokumentiert, aber **nicht** MVP-blockierend
- **P02 / Angebotsänderungen:** Änderungswünsche vor Annahme, rechtliche Bindung, Ersetzung gegenüber parallelen alternativ annehmbaren Angeboten, notwendige Verfügbarkeitsabsicherung, bei spätem erstem Änderungswunsch möglicherweise **einmalige begrenzte Fristverlängerung** (nicht beschlossen; keine automatische Fristneustartlogik).
- **Nach Vertragsschluss:** Vertragsänderungen/Verkürzungen, Zahlungs- und Stornofolgen, Teilstorno und etwaiger manuell geprüfter Storno-/Neubuchungs-Workaround; zunächst keine Änderungsautomatik.
- **Spätere Funktionen:** Mehrere aktive Postfächer, zusätzliche Kommunikationskanäle, agentische KI-Gastkommunikation, CRM/Loyalty, optionale Klärungsmodelle V2/V3 und Detailoptimierung gleichzeitig konkurrierender Anfragen ohne Queue.
## 8. Normative Übergabe und Quellen
**Nächster formaler Schritt:** Nach Bereitstellung des **vollständigen tatsächlich gültigen v0.10-Dokumentensatzes aus dem Repository** die bestehenden Dokumente mit dieser **Fassung 4** abgleichen und ein gezieltes Delta **v0.10 → v0.11** in den jeweils zuständigen normativen Dokumenten (z. B. K00/G00/P01, P02 später) ableiten, statt weiterer unverbundener Anhänge. Bis dahin ist **v0.10 unverändert**; insbesondere Angebots-Vorreservierung, bereits verbindliche Portalbuchungen, iCal-Ereignislogik und Buchungs-/Stornierungsregeln.
**Quellengrundlage:**
- `FewoPortal_SESSION_UEBERGABE_Datenbeschaffung_2026-11-02.md` (Session-Übergabe, Abschnitte A–N).
- `FewoPortal_Architekturentscheid_Kommunikationshandler_MVP_2026-11-02.md`.
- `FewoPortal_Entscheidungsstand_Aktualisiert.md` sowie `FewoPortal_Entscheidungsstand_Datenbeschaffung_und_Reservierungen_2026-11-02.md`.
- Konsolidierung Fassung 2 und **Fassung 3** vom 03.11.2026 sowie die **expliziten Entscheidungen CH-14 bis CH-18**. Diese haben im betroffenen Bereich Vorrang vor älteren MVP-Ausschlüssen von IMAP und KI-Extraktion.
- **Spätere Betreiberpräzisierungen im Gespräch vom 03.11.2026** zu Klärungsblock-Mindestdaten, differenzierten Nachrichtentexten (`0`/aktiv/abgelaufen), Verbindlichkeit externer Direktbuchungen und zentralem Kanalmanager inklusive eigenem Portal und iCal-Einstellungen.
**Revisionsnachweis Fassung 4 (gegen Fassung 3):** Nicht gekürzt: CH-01–CH-18, sechsteiliger Schnittstellenvertrag, Kommunikationsablauf, MVP-Abgrenzung, P02-Ausbaupunkte. Ergänzt: vier querschnittliche Betreiberpräzisierungen, zustandsabhängige Kommunikation, Kanalmanager-Konfigurationsfluss, zwei fokussierte Abnahmefälle M11–M12, Bereinigung der überholten offenen Mindestqualifikationsfrage. **Keine** Behauptung, die v0.11 sei bereits normiert, die v0.10-Dokumente lägen vollständig vor oder die genannten Funktionen seien bereits implementiert.
**Statuslegende:** **Beschlossen** = ausdrücklich bestätigtes fachliches Ziel; **Bestand** = unveränderte v0.10; **Offen** = weitere Entscheidung/Prüfung erforderlich; **Später** = kein MVP-Umfang. Konkrete Modell-, Prompt-, Schwellen- und Rechtsprüfungen sind noch **nicht** als bereits abgeschlossen dokumentiert.
@@ -0,0 +1,138 @@
# Entscheidungspapier: Universeller Eingang, Datenbeschaffung und persönlicher Gastlink
**Stand:** 02.11.2026 · **Zweck:** Vorlage für die Strategie-Session zu den Eingangskanälen · **Status:** Arbeitsgrundlage, **nicht normativ**. Die Spezifikation v0.10 bleibt unverändert, bis die Ergebnisse der Session in v0.11 übernommen sind.
Grundlage: [Architekturaudit Eingang und Datenanreicherung](ARCHITEKTURAUDIT_EINGANG_DATENANREICHERUNG.md), das Testen auf dem Testsystem und die Abstimmung mit dem Betreiber am 02.11.2026.
---
## 1. Ausgangslage in drei Sätzen
FewoPortal nimmt Vorgänge heute über feste Wege an: Webseite, iCal, Portal-Mail und Eingabe von Hand. Fehlende Angaben beschafft immer die Vermieterin von Hand. Die Einstellungen sind auf drei Orte verteilt, und die eigene Webseite ist kein eigener, einstellbarer Kanal. Der Vorgangskern trägt eine Erweiterung, eine neue Ablaufsteuerung ist nicht nötig (Audit §1).
## 2. Bereits entschieden
| # | Entscheidung |
|---|---|
| E1 | Es gibt **einen universellen Eingang**. Jede Quelle trägt Angaben zu einem Vorgang bei: Webseite, iCal, Portal-Mail, Gast-Mail, Chat, API, persönlicher Link, Eingabe von Hand. Der Posteingang wird darauf geprüft, ob weitere Angaben zu einem bestimmten Vorgang eingetroffen sind. |
| E2 | Fehlen Angaben, kann der Gast **angeschrieben und um die Angaben gebeten** werden. Er gibt sie auf einer Seite bei uns über einen **persönlichen Link** ein. |
| E3 | Über den Link sieht der Gast **alle seine Daten** und darf sie **korrigieren**. Dass ein Link weitergeleitet werden kann, wird hingenommen. |
| E4 | Der Link zeigt **je nach Stand des Vorgangs andere Inhalte**. Einen „Annehmen“-Knopf gibt es nur, solange ein Angebot zur Annahme offen ist. |
| E5 | **Ändern vor Annahme des Angebots** wird als schaltbare Einstellung vorgesehen. Wird sie genutzt, geht ein **geändertes Angebot** hinaus. Ändert der Gast die Termine, wird die **Verfügbarkeit neu geprüft**. |
| E6 | **Änderungen nach Vertragsschluss** und der Umgang mit **Verkürzungen in den Stornozeiträumen** werden gesondert entschieden (§5 E). |
| E7 | Die Seite „Eingangskanäle“ und die Pflichtangaben werden **erst nach der Session** gebaut, damit nichts zweimal entsteht. |
## 3. Zielbild
### 3.1 Bausteine
Der Eingang besteht aus sechs festen Bausteinen, nicht aus einer allgemeinen Ablaufmaschine:
1. **Quellen-Adapter:** Jede Quelle macht aus ihrer Eingabe einen *Beitrag*, also Angaben mit Herkunft, Zeitpunkt und Verlässlichkeit. Eine neue Quelle ist ein neuer Adapter.
2. **Zuordnung zum Vorgang:** über Buchungsnummer, persönlichen Link oder eine eigene Antwortadresse je Vorgang. Unklare Fälle werden zur Klärung, gleiche Termine allein beweisen keine Identität.
3. **Zusammenführen:** Eine feste Rangfolge der Quellen gilt. Bei Widerspruch entsteht eine Klärungsaufgabe, nichts wird stillschweigend überschrieben. Jede Änderung steht im Verlauf.
4. **Pflichtangaben je Schritt** (Angebot, Bestätigung, Anreise …), je Kanal einstellbar.
5. **Beschaffung:** Rückfrage per Link, Erinnerungen, Übergabe an die Vermieterin.
6. **Weiterführen:** ein einziger Einstieg, der den Vorgang danach fortsetzt, automatisch oder nach Freigabe.
### 3.2 Persönlicher Gastlink je Stand des Vorgangs (Vorschlag)
| Stand | Der Gast sieht | Der Gast kann | Folge |
|---|---|---|---|
| Anfrage, Angaben fehlen | Anfrage, Termine, Preis, seine Daten; Fehlendes hervorgehoben | ergänzen und korrigieren | Prüfung auf Vollständigkeit, dann weiter laut Einstellung (Angebot oder Auskunft) |
| Auskunft unter Vorbehalt (Paket 7) | Auskunft, seine Daten | Daten korrigieren, Buchung anfragen | wie heute; geänderte Termine: neue Prüfung |
| Angebot offen | Angebot mit „Annehmen“, seine Daten | annehmen; Daten oder Termine ändern, wenn eingeschaltet | geändertes Angebot mit neuer Version, der alte Link wird ungültig; bei neuen Terminen erst die Verfügbarkeitsprüfung |
| Buchung verbindlich | Bestätigung, Zahlungen, seine Daten | Daten korrigieren; Änderung **beantragen** (nach §5 E) | Kontaktdaten: Mitteilung; Termine und Leistungen: Antrag an die Vermieterin |
| Vor der Anreise | Anreise-Infos | Anreisezeit, ggf. Meldedaten | Aufgaben der Vorbereitung |
| Portalbuchung | Buchungsdaten laut Portal | Kontaktdaten korrigieren, Anreisezeit | Termine und Preis ändert nur das Portal |
**Sicherheit:** Jede Korrektur steht im Verlauf. Der Gast bekommt eine kurze Mitteilung an die **bisherige** Adresse, bei einer geänderten E-Mail-Adresse an beide. So fällt Missbrauch auf, ohne dass der Gast einen Code eingeben muss. Die Technik ist die vorhandene: signiert, versioniert, mit Ablauf und Begrenzung der Aufrufe.
## 4. Empfohlene Reihenfolge
1. **v0.11 ergänzen:** den Baustein „Eingang und Datenbeschaffung“ und die Entscheidungen aus §5.
2. **Kern:** Beiträge mit Herkunft, Pflichtangaben je Schritt und ein Einstieg zum Weiterführen. Am Vorgang wird sichtbar, was fehlt und woher eine Angabe stammt.
3. **Persönlicher Gastlink**, zuerst mit den Ständen „Anfrage, Angaben fehlen“ und „Angebot offen“. Das löst auch die fehlende Anschrift aus dem Webformular richtig.
4. **Seite „Eingangskanäle“:** alle Einstellungen an einer Stelle. Die eigene Webseite und „Telefon/E-Mail“ werden Kanäle wie die Portale.
5. **Änderung nach Vertragsschluss beantragen**, mit Teilstorno-Berechnung.
6. **Posteingang:** Antwortadresse je Vorgang, Antworten und Gast-Mails erkennen.
7. **Weitere Adapter:** Chat, API, KI-Vorschläge.
Der Link kommt vor dem Posteingang, weil er geordnete und verlässliche Angaben liefert, der Posteingang dagegen ungeordnete.
## 5. Offene Entscheidungen mit Empfehlung
### A. Eingang und Zuordnung
| # | Frage | Empfehlung |
|---|---|---|
| A1 | Welche Quellen in welcher Reihenfolge? Chat und API: was genau, mit welchen Anbietern? | Reihenfolge wie §4; Chat und API erst mit konkretem Anbieter festlegen |
| A2 | Wie werden Mails einem Vorgang zugeordnet? | eigene Antwortadresse je Vorgang (z. B. `anfrage+2026-0007@…`), sonst Buchungsnummer; ohne beides wird die Mail zur Klärung |
| A3 | Bleibt die heutige automatische Zuordnung „gleiches Portal, gleiche Nächte, ohne Buchungsnummer“? | künftig als **Klärung**, nicht mehr automatisch |
| A4 | Darf das System alle Mails im Postfach lesen? Welche Löschfrist gilt? | nur ein eigenes Gästepostfach; Löschfrist wie beim Vorgang; Eintrag in den Datenschutzhinweisen |
| A5 | Wie weit wird KI genutzt, um Mails und Chats auszuwerten? | anfangs nur **Vorschläge mit Bestätigung**; Anschrift, Preis und Termine nie ungeprüft übernehmen |
| A6 | Welche Quelle gewinnt bei Widerspruch? | Vermieterin vor Gast über den Link vor Portal-Mail vor Kalender; ein Widerspruch zu einer schon bestätigten Angabe führt immer zur Klärung |
| A7 | Testbetrieb | eingehende Daten werden als **simuliert** markiert und lösen keine echten Folgen aus |
### B. Pflichtangaben
| # | Frage | Empfehlung |
|---|---|---|
| B1 | Was braucht das **Angebot**? | Vorname, Nachname, E-Mail, vollständige Anschrift (Straße, PLZ, Ort, Land), Personenzahl; Telefon freiwillig |
| B2 | Was braucht die **Bestätigung**? | wie B1 |
| B3 | Was braucht die **Anreise**? | Meldedaten nach rechtlicher Prüfung (§§ 29 f. BMG, Umfang nicht geprüft) |
| B4 | Fragt die Webseite fehlende Pflichtangaben gleich im Formular ab oder später per Link? | je Kanal einstellbar; Grundeinstellung: kurze Anfrage zulassen, fehlende Angaben per Link nachfordern |
### C. Beschaffung und Haltefrist
| # | Frage | Empfehlung |
|---|---|---|
| C1 | Geht die Rückfrage automatisch hinaus oder erst nach Freigabe? | je Kanal einstellbar; zu Beginn „nach Freigabe“ |
| C2 | Erinnerungen und Eskalation | eine Erinnerung nach 24 h, danach eine Aufgabe für die Vermieterin |
| C3 | Wann beginnt die Haltefrist: bei Eingang oder erst bei vollständigen Angaben? | bei Eingang; eine Rückfrage verlängert sie **nicht** stillschweigend (Konzept_workflows F1 Nr. 4) |
| C4 | Was gilt, wenn der Gast nach Ablauf der Frist antwortet? | neue Verfügbarkeitsprüfung, der Vorgang lebt wieder auf, wenn der Zeitraum frei ist |
### D. Ändern vor Annahme des Angebots
| # | Frage | Empfehlung |
|---|---|---|
| D1 | Ist eine Terminänderung ein neuer Vorgang? | nein, derselbe Vorgang mit neuer Angebotsversion |
| D2 | Läuft die Haltefrist nach einer Terminänderung neu an? | **nein**, sonst ließe sich ein Termin durch ständiges Ändern dauerhaft blockieren |
| D3 | Geänderte Termine, Preis oder Mindestnächte | alles neu prüfen und berechnen wie beim Buchungswunsch (Paket 7); ist alles in Ordnung und gilt Automatik, geht das neue Angebot sofort hinaus, sonst entsteht eine Aufgabe |
| D4 | Wie oft darf der Gast ändern? | höchstens drei Änderungen je Vorgang, danach nur noch über die Vermieterin |
### E. Änderungen nach Vertragsschluss
Heute kann die Vermieterin eine Buchung ändern (Paket 5): als schon vereinbart oder als Vorschlag mit Zustimmung des Gastes. **Lücke:** Bei einer Verkürzung wird der Preis für die kürzere Zeit neu berechnet, die Stornostaffel gilt für die wegfallenden Nächte **nicht**.
| # | Frage | Empfehlung |
|---|---|---|
| E1 | Darf der Gast nach Annahme selbst Änderungen beantragen, und welche? | ja (Termine, Personen, Leistungen), wirksam erst nach Bestätigung durch die Vermieterin, nie automatisch |
| E2 | Wie werden wegfallende Nächte bei einer Verkürzung behandelt? | als **Teilstorno**: Auf den Preis der wegfallenden Nächte gilt der Satz der Stornostaffel zum Zeitpunkt der Änderung |
| E3 | Kulanz | nach Ermessen der Vermieterin, im Vorgang als Abschlag mit Begründung; Hinweis, wenn die Nächte anderweitig vermietet wurden |
| E4 | Verschieben bei gleicher Länge | bis zu einer Frist kostenlos (Vorschlag: 60 Tage vor Anreise), danach nur nach Freigabe |
| E5 | Verlängern | Verfügbarkeit prüfen und Mehrpreis berechnen, keine Staffel (wie heute) |
| E6 | Portalbuchungen | Es gelten die Regeln des Portals; der Link zeigt nur Kontaktdaten und Anreisezeit |
**Rechtlich:** Eine Teilstorno-Regel wirkt nur, wenn die Mietbedingungen sie ausdrücklich enthalten. Sie gehört zur ohnehin offenen rechtlichen Prüfung (Gesamtabnahme §4).
### F. Konfiguration
| # | Frage | Empfehlung |
|---|---|---|
| F1 | Eine Seite „Eingangskanäle“ für alle Einstellungen? | ja: oben „Alle Kanäle“ (die heutigen Grundeinstellungen), darunter Webseite, Telefon/E-Mail und je Portal; je Eintrag die Bereiche Ablauf, Pflichtangaben, Beschaffung und Technik |
| F2 | Was bleibt auf „So arbeite ich“? | nur die Dokumentfreigaben, oder die Seite geht ganz in „Eingangskanäle“ auf |
| F3 | Abweichungen je Wohnung | bleiben bei der Wohnung, werden auf „Eingangskanäle“ aber angezeigt |
| F4 | Wird die Herkunft (z. B. Hub direkt oder über ein Partnerportal) eine dritte Einstellungsstufe? | nein, bis ein konkreter Fall es erfordert |
### G. Vermarktung
| # | Frage | Empfehlung |
|---|---|---|
| G1 | Wird ein Interessent aus Social Media oder einer Kampagne ein eigener Vorgangstyp? | nein, bis V02 entschieden ist; bis dahin werden Herkunft und Kampagnenkennung am Vorgang gespeichert |
## 6. Was bis zur Session nicht geändert wird
- Kein Bau der Kanal-Seite, der Pflichtangaben und des Links.
- Das Webformular bleibt, wie es ist: Die Anschrift ist freiwillig. Ein Angebot ohne Anschrift hält in der Automatik an und ist von Hand nur mit Bestätigung möglich.
- v0.10 wird auf dem Testsystem weiter abgenommen.
Loaded 100 of 164 files, more files were not shown because too many files have changed in this diff. Show more