Compare commits

...
Author SHA1 Message Date
LarsandClaude Opus 5.5 33f8f899d6 Prozessarchitektur 0.10
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m57s
Neue hierarchische Struktur der fachlichen Sollbeschreibung (README, Prozesslandkarte,
Buchungsarchetypen, Abwicklungsprofile, Entscheidungen, Offene Fragen, Querschnitt,
Szenarien, V01/V02, Referenzen); die Fassung 0.9 bleibt in der Git-Historie.
Obsidian-Fensterzustand (workspace.json) wird nicht mehr versioniert.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:11:54 +01:00
LarsandClaude Opus 5.5 0c10880e4f Testbetrieb: eine Schranke fuer jede ausgehende E-Mail
Deploy FeWo mit PipelineManager / deploy (push) Failing after 3m10s
EnforceMailTestMode prueft jede Mail unmittelbar vor dem Versand (MessageSending,
jeder Mailer): im Testbetrieb gehen An/Cc/Bcc nur an die Testadresse, ohne
Testadresse wird nichts versendet; der Modus wird je Mail frisch gelesen.
Ersetzt alwaysTo am Standard-Mailer. Tests inkl. Pruefung, dass kein Code am
Mailer vorbei versendet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:03:24 +01:00
LarsandClaude Opus 5.5 ac9d20b812 Ein Eingang fuer alle Kanaele (Paket 4, Prozessarchitektur v0.10)
Portalbuchungen und -anfragen aus Kalender und Mail werden ueber PortalIntake
zum Vorgang (nur bei sicherer Erkennung), Dubletten ueber Buchungsnummer,
gleiches Portal mit gleichen Naechten und Spiegelung; Unsicheres wird geklaert.
Portalstorno und -aenderung als Aufgabe am Vorgang ohne stille Stornierung.
Schalter je Kanal (Aus als Standard, Beobachten, Anlegen, Anlegen + weiter),
Eingangsprotokoll, Bestandsuebernahme mit Vorschau/Bericht/Ruecknahme,
Sperrnachweis in drei Stufen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 20:53:35 +01:00
LarsandClaude Opus 5.5 cf11c8a474 Dokumentenzusammenstellung und Vorlagensteuerung (Paket 3, Prozessarchitektur v0.10)
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m59s
Eine Zusammenstellung vor jedem Dokument (Angebot, Bestaetigung, Buchungsunterlagen
extern), Dokumentart je Vorgangsart, Freigaben fuer Vorlagen und Dokumentarten,
Schutz vor unvereinbarten Bedingungen bei Portalbuchungen (E-004), kein doppelter
Versand, Absicherung Hold 0 bis Paket 7, A6-Aufenthaltsbestaetigung vorbereitet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 19:44:52 +01:00
LarsandClaude Opus 5.5 64248c09fa Preisangaben bei Portalbuchungen für Paket 8 vorgemerkt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:41:38 +01:00
LarsandClaude Opus 5.5 987c67d4d3 Ergebnisdokument Pakete 1 und 2, Projektstand ergänzt
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m48s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:28:02 +01:00
LarsandClaude Opus 5.5 3a728c3255 Vorgangskern und geführte Vorgangsbearbeitung (Pakete 1 und 2, Prozessarchitektur v0.10)
- Buchung ist der einheitliche Vorgang: Eingangsart, Vorgangsart A1–A6, eingefrorenes
  Abwicklungsprofil, gespeicherter Verlauf (booking_events); Gast, Personen und Beträge
  dürfen unbekannt sein, Platzhalter-Gäste werden migriert und nicht mehr angelegt
- Einstellungen in Ebenen: Vermieterstandard (So arbeite ich), Abweichung der Wohnung
  (Experte), Abweichung je Portal und Eingangsart; ersetzt booking_model als Steuergröße
- Ein Weg für extern verbindliche Buchungen (TakeOverExternalBooking) statt
  RecordPortalBooking und "Akte anlegen"; Portalpreis als belegte Gesamtposition
- Startseite "Zu erledigen", neue Vorgangsseite mit nächstem Schritt, Automatik-Schalter,
  "Beenden" mit Storno statt Statusumschaltung; Status von Hand nur im Expertenmodus
- Migration übernimmt bisheriges Verhalten unverändert (abweichende Wohnungswerte bleiben
  als Abweichung), Bericht: php artisan process:settings-report

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 16:25:46 +01:00
Lars 9005c12164 Prozessarchitektur 0.9
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m41s
2026-11-01 10:30:08 +01:00
Lars 2d458d9116 Prozessarchitektur 0.8
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m31s
2026-10-31 22:38:32 +01:00
Lars 65fe8f5c6c Prozessarchitektur 0.7
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m31s
2026-10-31 22:29:18 +01:00
Lars 0dc0470c60 Prozessarchitektur 0.6b
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m32s
2026-10-31 18:30:31 +01:00
Lars 382c1724a3 Prozessarchitektur 0.6a
Deploy FeWo mit PipelineManager / deploy (push) Failing after 2m54s
2026-10-31 18:28:12 +01:00
Lars 4587912e5b Prozessarchitektur: 0.6
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m46s
2026-10-31 15:29:25 +01:00
Lars d0eb79bb9b Prozessarchitektur 0.5
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m49s
2026-10-31 13:43:51 +01:00
Lars 9f3501e045 Merge branch 'develop' of https://gitea.stommer.de/Lars/fewo-stommer into develop
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
2026-10-31 13:11:37 +01:00
Lars 7d7c5db1fd Prozessarchitektur 0.1 2026-10-31 13:11:34 +01:00
LarsandClaude Opus 5.5 a1fc4f7fef Galerie: kein Springen beim Blaettern, Vergleich ohne Pfeile an den Beschriftungen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
- Lightbox: feste Bildgroesse aus dem Seitenverhaeltnis, beim Blaettern wird das grosse Foto erst geladen und dann eingeblendet
- Seebad-Vergleich: Pfeile neben Sommer/Winter entfernt (passten nicht zur Ziehrichtung)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 07:07:26 +01:00
LarsandClaude Sonnet 5.5 545008baab Compliance-Kern: HTTPS-Erzwingung, Datenschutzlink im Buchungsformular, signierte Links/Feeds von Adress-Weiterleitung ausnehmen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m39s
- ForceHttps-Middleware (abschaltbar per FEWO_FORCE_HTTPS)
- Datenschutzerklaerung im Buchungsformular verlinkt
- ResolveTheme: angebot/bewertung/angebote/kalender/automation/health bleiben auf der aufgerufenen Adresse
- Berichte MVP-TECHNICAL-GATE / MVP-COMPLIANCE-ACCEPTANCE, Regeln fuer parallele Agenten (ZUSAMMENARBEIT 7)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 22:28:20 +01:00
LarsandClaude Opus 5.5 4c9e6992f4 Design Stufe 2: Tipp-Karten zum Umdrehen, Sommer/Winter-Vergleich, Galerie mit weichem Vergroessern
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m45s
- Baustein "Ausflugstipps" (tips): Karten mit Foto vorne, Tipp/Weg/beste Zeit hinten; Seebad als Ansichtskarten
- Baustein "Sommer/Winter-Vergleich" (compare): Trennlinie ziehen, Tastatur ueber Range-Input, einmaliger Hinweis-Schwenk
- Lightbox: Foto waechst aus der Vorschau, Blaettern (Pfeile, Tasten, Wischen), Zaehler, Bildunterschrift; partials/lightbox
- Bewegung reduzieren: Ueberblenden statt Drehen, kein Schwenk, keine Zoom-Animation

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:05:16 +01:00
LarsandClaude Sonnet 5.5 c8bb0f6e97 Uebergabe Buchungsprozess: Anforderungen, Stand, Maengel, empfohlenes Vorgehen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m34s
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 19:17:28 +01:00
LarsandClaude Sonnet 5.5 81c025f1ee Akte auch fuer Portal-Reservierungen aus dem Kalender, Ablauf mit Aktivitaeten, Verlauf, Standardprozess je Portal
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m34s
- Akte anlegen aus einer importierten Portal-Reservierung (Belegung bleibt durchgehend belegt, Kalendereintrag wird Spiegelung)
- Akte: Standardprozess (Portal/Vorlage/Storno/Anlagen), Meilensteine mit Aktivitaeten und Aktionshinweis, chronologischer Verlauf
- Kanalformular: Abschnitt Standardprozess je Buchungstyp mit Anzeige, was die Vorlage mitbringt
- Portalpreis als gemeinsame Logik (PortalPrice)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 18:56:32 +01:00
LarsandClaude Sonnet 5.5 5ba9ae08ab Portal-Direktbuchung erfassen, Kontaktdaten-Prozess, manueller Statuswechsel, Archiv, Filter, Menue Verwaltung/Einrichtung
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
- Buchung erfassen: Buchungsweg Portal (Referenz, Portalpreis, ohne Kontaktdaten), Prozess bestaetigen/Vertrag sofort/nur erfassen
- Buchungsakte: Kontaktdaten eintragen (automatisch oder manuell weiter), Gast um Kontaktdaten bitten, Status von Hand aendern, Archivieren
- Liste: Filter Kanal, Anreisezeitraum, Kontaktdaten fehlen; Spalten ausblendbar; Archiv
- Klaerung: verstaendlichere Texte, eigenstaendige Belegung mit Kanal gilt als geklaert (Gitea #4)
- Akte per Button aus Liste und Belegungsplan erreichbar
- Menue: Gruppen Verwaltung (Tagesgeschaeft) und Einrichtung (Konfiguration), einfache Ansicht auf 8 Punkte

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 18:04:03 +01:00
LarsandClaude Sonnet 5.5 0c4187edaf Stornoregeln mit automatischer Kostenberechnung, Storno-Verwaltung, Vertragsanlagen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m34s
- Stornoregel (Stufen nach Tagen vor Anreise, Mietpreis oder Gesamtpreis, Ersatzmieter-Gebuehr), je Vertragsvorlage,
  beim Angebot eingefroren, als Platzhalter im Vertrag
- Stornierung (Gast-Link oder Verwaltung) berechnet die Kosten, legt einen Stornofall an; Verwaltung Stornierungen
  mit Vorschlag, Festlegung, Saldo, Abrechnung und Erlass; Gast sieht die Kosten vorab auf der Storno-Seite
- Vertragsanlagen als eigene versionierte Dokumente mit Bedingung (immer, Zusatzleistung, Portal, von Hand),
  je Angebot ausgewaehlt und eingefroren; Zusatzleistungen in der Buchung erfassbar
- FeWo-direkt-Installation legt die Stornoregel aus Paragraf 13 an

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 16:32:48 +01:00
LarsandClaude Sonnet 5.5 5baf39441f Buchungsakte: Vorgang, naechster Schritt, Vertrag, Mailverlauf, Storno mit Mail, Archiv
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
- Buchungsseite zeigt Art des Vorgangs, Verlaufsleiste und den naechsten Schritt in Klartext
- Vertragsabschnitt (Vorlage, Dokumente mit Pruefsumme, Zustellung) und Vertragstext-Ansicht
- Reiter Aufgaben und Mailverlauf (jede Mail zur Buchung wird protokolliert)
- Stornieren in der Verwaltung informiert Gast und Vermieter und legt eine Aufgabe fuer Stornokosten an
- Stornierte/abgelehnte/abgelaufene Buchungen aus der Hauptliste, Filter Archiv anzeigen

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 16:16:42 +01:00
LarsandClaude Sonnet 5.5 89d569b6c8 Vertragsvorlagen als ganzes Dokument mit Platzhaltern, Wohnungsdaten, Portal-Zuordnung
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m38s
- Vorlage = kompletter Vertragstext plus Anlage mit Platzhaltern ({{ mieter }}, {{ anreise }}, {{ wohnung.x }}),
  eigene Vertrags-PDF, Anzeige auf der Angebotsseite; Text und Wohnungsdaten werden beim Angebot eingefroren
- Wohnungsdaten (WLAN, Codes, ...) als Vertragsdaten der Wohnung statt im Vorlagentext
- Je Portal eigene Vorlage fuer Anfragen und fuer beim Portal verbindliche Buchungen; direkte Bestaetigung
  nutzt dieselbe Aufloesung; Bestaetigungsmail ohne Zahlungsanweisung bei Portalzahlung
- Befehl contracts:install-fewo-direkt legt die FeWo-direkt-Vorlage aus dem Vertragstext des Vermieters an

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 16:04:30 +01:00
LarsandClaude Sonnet 5.5 a73b164ea1 Zahlungsaufgaben, Freigabe-/Storno-Link, Vertragsvorlagen, Anreise-Mail
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m36s
- Zahlungen werden nicht mehr automatisch angemahnt: faellige Anzahlung/Restzahlung werden Aufgaben
  (Zahlungen & Wuensche, Tages-/Wochenuebersicht); Mail nur per Klick; je Portal und Buchungstyp abschaltbar
- Freigabe-Link in der Eingangsbestaetigung, Storno-Link in der Buchungsbestaetigung; je Wohnung
  Wunsch / sofort / sofort bis Frist; Stornowuensche und Kosten bleiben Aufgabe des Gastgebers
- Vertragsvorlagen mit Versionen (je Angebot, Portal oder Wohnung waehlbar), benutzte Versionen gesperrt;
  Angebot und finaler Vertrag als unveraenderliche PDF mit SHA-256, Vertrag wird nie neu geschrieben
- Anreise-Mail je Wohnung einstellbar (Standard 3 Tage), neue Textfelder Schluessel/Parken/Ankunftstag

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:46:29 +01:00
LarsandClaude Sonnet 5.5 eafab8a2cb Buchungsprozess: Angebots-Snapshot, atomare Annahme, Auto-Angebot, Kanalfreigabe
Deploy FeWo mit PipelineManager / deploy (push) Failing after 3m38s
- Angebotsbedingungen und Zahlungsdaten werden je Version eingefroren (offer_terms, offer_hash)
- Annahme in einer gesperrten Transaktion, idempotent, mit Nachweis; Mail- und Portalfehler
  machen eine gespeicherte Buchung nicht ungueltig (Postfach, Nachversand)
- Je Wohnung: manuelle/automatische Angebote, optionale Vorreservierung
- Automatische Freigabe abhaengig von aktuellen Importen und Feed-Abruf bei Sofortbuchungsportalen
- Deutsche Fehlerseiten, Buchungsseite zeigt Angebots- und Zustellstatus
- Dokumentation: BOOKING-E2E-*.md, BOOKING-COMPLIANCE-HANDOVER.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 12:01:02 +01:00
Lars e7cc37a15b Hauptadresse und Abspielgeschwindigkeit zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m6s
2026-10-30 11:30:42 +01:00
LarsandClaude Opus 5.5 cc47cac93e Hauptadresse statt Zweitadresse, Abspielgeschwindigkeit je Video
- Weitere Adressen einer Website (z. B. www.stommer.info) leiten per 301 auf die
  Hauptadresse um; vorher blockierte der Browser Skripte, Schriften und Videos,
  die von der Hauptadresse kamen (kein Titelvideo, Ersatzschrift)
- Site::origin() nimmt verbindlich das Feld domain
- Videos: Abspielgeschwindigkeit 0,5x bis 1x, gilt im Titelbereich und Rundgang

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:30:42 +01:00
Lars b5ff837dcd Titelvideo, Rundgang und Buchungsseite zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m4s
2026-10-30 11:01:52 +01:00
LarsandClaude Opus 5.5 d42c42059c Titelvideo, Rundgang mit Kapiteln, naechste freie Termine, ruhigere Buchungsseite
- Webseite > Videos (Datei, Standbild, Kapitel mit Raum im Grundriss); Upload bis 100 MB
- Titelbereich: Video statt Foto (stumme Schleife, respektiert Bewegung reduzieren/Save-Data)
  und naechste freie Termine mit Gesamtpreis (NextFreeStays)
- Neuer Baustein Rundgang (Video) mit waehlbarer Anordnung; Grundriss springt ins Video
- Buchungsseite: Preis unter dem Kalender, Formular rechts, Ablauf als Grafik
- Seebad: Fahrkarten, Fahrplan-Kapitel, Sonnenaufgang als einmaliges Ereignis

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 11:01:52 +01:00
Lars f5f18cd984 Erinnerungen und Zusammenfassungen zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m4s
2026-10-30 10:11:15 +01:00
LarsandClaude Opus 5.5 1c757f7429 Erinnerungsabstand und taegliche/woechentliche Zusammenfassung einstellbar
System > Betrieb > Benachrichtigungen: offene Meldungen (Doppelbuchungen im
Postfach, Portal-Aufgaben) nur einmal oder alle 1/2/3/7 Tage erneut senden;
Tages- und/oder Wochenuebersicht mit waehlbarer Uhrzeit, Wochentag und Inhalt
(Postfach, Anfragen, Neues, An-/Abreisen, Zahlungen, Portale, Bewertungen).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 10:11:15 +01:00
Lars 70a39315e2 Postfach und einmalige Doppelbuchungsmeldungen zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m58s
2026-10-30 09:52:36 +01:00
LarsandClaude Opus 5.5 b9225f5fb8 Doppelbuchungen nur einmal melden und im Postfach der Verwaltung zeigen
Der Kalenderabgleich alle 5 Minuten hat jede fortbestehende Ueberschneidung
erneut gemailt. ReportChannelConflicts legt jede Ueberschneidung einmal im
neuen Postfach (InboxMessage, Fingerabdruck je Mandant) ab und mailt nur neue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:52:35 +01:00
LarsandClaude Opus 5.5 876a0a20f3 Wohnungsumschalter, Saisonfotos und zentrale Banner zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:02:13 +01:00
333 changed files with 21183 additions and 598 deletions

No files matched your search

+3
View File
@@ -34,3 +34,6 @@ Thumbs.db
/scripts/deploy.*.env
!/scripts/deploy.example.env
storage/app/private/exports/
# Obsidian: persönlicher Fensterzustand des Editors
docs/Prozessarchitektur/.obsidian/workspace.json
+74
View File
@@ -0,0 +1,74 @@
# BOOKING-COMPLIANCE-HANDOVER
Technische Fakten für die nachgelagerte Compliance-Prüfung. **Keine rechtlichen Bewertungen**, keine Änderung von CMS-Rechtstexten. Stand: 30.10.2026, Entwicklungsstand Branch `feature/buchung-e2e` (nicht deployt). Details: `BOOKING-E2E-IMPLEMENTATION.md`.
## 1. Tatsächlicher Ablauf des Vertragsschlusses (Direktbuchung)
1. Gast sendet das Anfrageformular (`/buchen`, Livewire; Bot-Schutz: Honeypot, Zeitsperre, Rate-Limits). Eingabe: Name, E-Mail, optional Telefon/Adresse, Nachricht, Zeitraum, Personen, optional Rabattcode, Einwilligungs-Checkbox Datenschutz, optional Newsletter-Opt-in.
2. System prüft Verfügbarkeit und berechnet den Preis (`PriceCalculator`). Je Wohnung: **Vorreservierung** an (Kalender wird bis zum Ablauf der Haltefrist gesperrt) oder aus (keine Sperre).
3. **Manueller Modus (Standard):** Eingangsbestätigung an den Gast (unverbindlich, ggf. mit Ablaufzeit der Vormerkung), Mitteilung an den Betreiber; Betreiber erstellt/sendet das Angebot im Admin.
**Automatischer Modus:** Angebot geht sofort an den Gast, wenn alle Prüfungen bestanden sind (Details Implementation §Phase 3); sonst Rückfall auf manuell.
4. Angebot (Version n): E-Mail mit Preisaufstellung und PDF-Entwurf (Angebot/Mietvertrag) im Anhang und einem **signierten, befristeten Link** (`/angebot/{id}?v=n`, Ablauf = Angebotsfrist).
5. Der Link öffnet die Angebotsseite (GET, ändert nichts). Sie zeigt Zeitraum, Preiszeilen, Zahlungsplan, Mietbedingungen, Stornobedingungen, „Gültig bis“, Hinweistext (`offer.accept_note`), Checkbox „Ich habe die Angaben und Bedingungen dieses Angebots gelesen“ und die Schaltfläche (Beschriftung `offer.accept_button`, CMS; Standardtext aktuell „Angebot zahlungspflichtig annehmen“). Daneben „Angebot ablehnen“.
6. Annahme = POST auf eine signierte URL (CSRF-geschützt, Rate-Limit 10/min). Eine Transaktion prüft Version, Status, Frist, Prüfsumme des Angebots, Verfügbarkeit (und vorher Aktualität der Portalkalender), schreibt den Nachweis und setzt die Buchung auf `Confirmed`.
7. Danach: Vertrags-PDF (final) wird erzeugt; Bestätigungs-E-Mail mit PDF geht an den Gast; Betreiber erhält eine Annahme-Mail. Fristen: Anzahlung = Annahmetag + `deposit_due_days` (Standard 7), Rest zum vereinbarten Termin.
8. Der Kalender ist sofort belegt (iCal-Ausgangsfeed wird bei jedem Abruf live berechnet); für Portale mit manueller Sperre entstehen Aufgaben (+ optionaler Webhook).
## 2. Angebots- und Annahmenachweise (Datenbank `bookings`)
| Feld | Inhalt |
|---|---|
| `offer_version`, `offer_sent_at`, `hold_expires_at` | Version, Versandzeit, Gültigkeit (nach Annahme `null`) |
| `quote`, `total`, `deposit`, `balance_due_on` | Preis und Zahlungsplan der Version |
| `offer_terms` (JSON) | eingefrorene Texte: Mietbedingungen, Storno, Hausordnung, Vertragseinleitung/-schluss, Vertragshinweis, Annahmehinweis, Button-Beschriftung; Anzahlungsfrist; Vermieter- und Bankdaten; `captured_at` |
| `offer_hash` | SHA-256 über Version, Termine, Personen, Quote, Beträge, Zahlungstermin, Snapshot |
| `acceptance` (JSON), `accepted_at` | Version, Zeitpunkt, Gültigkeit, Gesamtbetrag, `offer_hash`, `quote_sha256`, `terms_sha256` (Hash der **angezeigten** Texte), Button-Text, `via=offer_link` |
| `confirmed_at`, `deposit_due_on`, `contract_path`, `offer_path` | Bestätigungszeit, Fälligkeit, Pfade der PDFs |
| `confirmation_sent_at`, `confirmation_failed_at` | Zustellstatus der Bestätigungsmail (nur Versand an den Mailserver, kein Lesenachweis) |
Es wird **keine IP-Adresse, kein User-Agent und kein Token** im Nachweis gespeichert. Der Nachweis zeigt „diese Angebotsversion mit diesem Inhalt wurde über den signierten Link angenommen“; er identifiziert den Handelnden nur über den Besitz des Links.
Nach Versand geänderte CMS-Texte wirken **nicht** auf bestehende Angebote (Snapshot). Eine Änderung der gespeicherten Angebotsdaten verhindert die Annahme (Hash-Prüfung, Postfachmeldung).
## 3. Technische Darstellung der Vertragsinformationen
- Angebotsseite (HTML) und PDF (Angebot/Entwurf → final) werden aus demselben Snapshot gerendert. PDFs liegen als Dateien (nicht neu gerendert beim Abruf); „Mietvertrag neu erzeugen“ im Admin nutzt den Snapshot.
- Das Angebots-PDF hängt an der Angebotsmail (dauerhaft speicherbar); das finale Vertrags-PDF an der Bestätigungsmail. Auf der Angebotsseite selbst gibt es keinen PDF-Download-Link (Hinweis auf den Anhang).
- Hausordnung steht im PDF, nicht auf der Angebotsseite. Die Texte sind **noch Mustertexte** im CMS (`[MUSTER …]`); im Livebetrieb werden automatische Angebote nur bei freigegebenen (nicht-Muster) Texten und gefüllter IBAN gesendet.
- Zahlungspflicht-Hinweis und Button-Beschriftung sind CMS-Felder (`offer.accept_note`, `offer.accept_button`).
## 4. Speicherorte und Aufbewahrung
- PDFs: `storage/app/private/contracts/tenants/{tenant}/bookings/{booking}/` (nicht per Web erreichbar). Buchungsdaten/Nachweise: Datenbank, Tabelle `bookings`; Gäste: `guests`.
- Löschung/Anonymisierung (`guests:anonymize`, täglich): nie bestätigte Anfragen nach 6 Monaten (`FEWO_RETENTION_INQUIRY_MONTHS`); Gästedaten bestätigter Buchungen 10 Jahre (`FEWO_GUEST_RETENTION_YEARS`) – Vorschlagswerte laut `docs/LOESCHKONZEPT.md`. **Vertragsdokumente haben dort noch keine Löschfrist (als Lücke vermerkt).** `internal_notes`/`acceptance` werden nicht gesondert gelöscht.
- Datenbank-Backup täglich (`backup:database`, 14 Dateien), enthält Gäste- und Buchungsdaten.
- Logs: bei Mail-/Sync-/Auto-Angebot-Fehlern nur Meldungstext, Exception-Klasse und Buchungs-ID, keine Adressen, Links oder Tokens (Laufzeit: Laravel-Log, Kanal `daily`, 14 Tage).
## 5. Automatisch versendete Nachrichtentypen
| Klasse | Empfänger | Auslöser |
|---|---|---|
| `ReservationReceived` | Gast | Anfrage (nicht bei erfolgreichem Auto-Angebot) |
| `NewReservation` | Betreiber | Anfrage (inkl. Hinweis „Angebot automatisch versendet“ bzw. Gründe) |
| `OfferMade` | Gast | Angebot (manuell/automatisch) |
| `OfferAnswered` | Betreiber | Annahme/Ablehnung durch den Gast |
| `BookingConfirmed` (+ Vertrag-PDF) | Gast | Annahme / direkte Bestätigung; Nachversand durch Admin/Befehl |
| `BookingDeclined`, `ReservationExpired` | Gast / Betreiber | Ablehnung durch Betreiber / Ablauf |
| `PaymentReminder`, `ArrivalInformation`, `ReviewRequest` | Gast | Fristen (bestehend, unverändert) |
| `MarketingConsentRequest` | Gast | nur bei Newsletter-Opt-in (bestehend) |
| Digest/Kanal-/Postfach-Meldungen | Betreiber | bestehend |
Im **Testbetrieb** gehen alle Mails ausschließlich an die Testadresse (`App\Support\Settings`, unverändert).
## 6. Technische Stornierungs-/Kündigungsmöglichkeiten
- Gast: Angebot **ablehnen** (Angebotsseite, bis zur Annahme). Eine Stornierung/Kündigung **nach** Annahme ist im Gastbereich **nicht** vorgesehen (kein Kundenkonto, kein Stornolink); sie läuft über Kontakt (Telefon/E-Mail).
- Betreiber: Aktionen *Ablehnen*, *Stornieren* (setzt `Cancelled`, gibt den Kalender frei), Vormerkung verlängern. Eine automatische Berechnung von Stornokosten gibt es nicht; die Stornobedingungen sind reiner CMS-Text im Snapshot.
- Es gibt keine automatische Stornierung bei Nichtzahlung (nur Zahlungserinnerungen).
## 7. Externe Datenquellen und Empfänger
- Eingehend: iCal-Feeds der Portale (nur Zeiträume, ggf. Titel/Beschreibungstexte), Portal-Benachrichtigungs-Mails aus dem Betreiber-Postfach (IMAP) – können Gästedaten enthalten (Aufbewahrung 90 Tage laut Löschkonzept).
- Ausgehend: iCal-Feeds je Portal (nur Belegungen, ohne Gästedaten, Zugriff über zufälligen Token pro Kanal); optional signierter Webhook an die Betreiber-Automation (n8n) mit Aufgabendaten (Zeitraum, Kanal); Mailserver (Strato SMTP).
- Aufgezeichnet: Abrufe der Export-Feeds je Kanal (Zeit, Methode, User-Agent, Status) in `channel_export_requests`.
- Keine externen Dienste im Buchungsweg (kein Captcha, keine Zahlungs-/Tracking-Dienste).
## 8. Cookies / Technologien (neu betroffen)
Keine neuen Cookies oder Browser-Speicher. Die Angebotsseite nutzt die bestehende Laravel-Sitzung und das XSRF-Cookie (CSRF-Schutz des Annahmeformulars). Neue deutsche Fehlerseiten (403/404/419/429/500/503) laden keine externen Ressourcen.
Die Angebotsseite ist `noindex`; Links stehen in Zugriffsprotokollen des Webservers (signierte URL) – Aufbewahrung dort liegt bei Strato.
## 9. Bekannte technische Einschränkungen, die für die Prüfung relevant sind
- Der Nachweis enthält keine IP/Geräteangabe (Entscheidung offen, siehe READINESS Frage 5).
- Standard-Buttontext enthält „zahlungspflichtig annehmen“, nicht wörtlich „Zahlungspflichtig buchen“ (CMS, Betreiber).
- Bestätigungsseite nach Annahme (Erfolgsmeldung) und Bestätigungs-E-Mail sind die einzigen unverzüglichen Bestätigungen; Zustellung der Mail kann scheitern (Statusfeld, Nachversand).
- Widerrufsinformationen, AGB-Link, Datenschutzlink auf der Angebotsseite sind **nicht** automatisch eingebaut (nur CMS-Texte `contract.terms`/`stay.cancellation`); der Datenschutzlink am Anfrageformular ist laut MVP-TECHNICAL-GATE Blocker #2 offen.
+81
View File
@@ -0,0 +1,81 @@
# BOOKING-E2E-ACCEPTANCE
Stand: 30.10.2026 · Branch `feature/buchung-e2e` · Umgebung: lokale Entwicklung, PHP 8.4, **SQLite**, Mails/HTTP gefaket.
## Ergebnis in Kürze
- **Vollsuite: 561 Tests, 561 bestanden** (`php artisan test`, 30.10.2026, 4. Lauf). Davon neu: 14 + 3 in `BookingAcceptanceTest` (17), 12 in `AutoOfferTest`; 1 bestehender Test bereinigt (`dump()`). `vendor/bin/pint --dirty`: sauber.
- Hinweis zur Stabilität: In zwei früheren Läufen schlugen `WebsiteTenancyTest` (Status 301) und `PrivacyHardeningTest` (Datei im Test-Datenträger fehlt) fehl. Diese Läufe liefen zeitgleich mit einem zweiten Testlauf bzw. nach einer Fehlkonfiguration meinerseits (fehlender `use`-Import, inzwischen behoben); im sauberen Einzellauf bestehen sie. Eine Ursachenklärung für `WebsiteTenancyTest` (301 beim Parallellauf) habe ich nicht durchgeführt.
- **NICHT durchgeführt (BLOCKED):** MariaDB-Parallelitätstests, Browser-E2E, Zustellung echter Test-Mails, Sichtprüfung der PDFs, Staging-Durchlauf. Gründe unten.
- **Empfehlung: NO-GO für Staging-Freigabe/Aktivierung echter Buchungen**, solange die BLOCKED-Punkte offen sind. Technisch kein bekannter Fehler im Code; die Lücke ist fehlender praktischer Nachweis.
## Blockierte Nachweise (Warum)
| Nachweis | Status | Grund / nötige Entscheidung |
|---|---|---|
| Echte Parallelität auf MariaDB | **BLOCKED** | Lokal ist kein MariaDB vorhanden. Ich habe ein portables MariaDB (ZIP von archive.mariadb.org) in das Scratch-Verzeichnis geladen, **den Start der heruntergeladenen Binärdatei verweigerte das Berechtigungssystem** („Code from External“). Ich habe das nicht umgangen. Optionen: MariaDB/Docker selbst bereitstellen und `DB_CONNECTION=mariadb` für einen Testlauf freigeben, oder die Tests gegen die Staging-DB laufen lassen (Freigabe nötig). Der Schutz beruht auf `SELECT … FOR UPDATE` (Wohnung + Buchung); unter SQLite ist `lockForUpdate` wirkungslos, die Tests belegen daher die **Logik** (frisches Neuladen unter Sperre, Idempotenz mit veralteter Modellkopie), nicht das Sperrverhalten der Datenbank. |
| Browser-E2E, Tastatur/Screenreader | BLOCKED | nicht ausgeführt |
| Echte Mailzustellung (SPF/DKIM, Anhang öffnen) | BLOCKED | Staging läuft mit `MAIL_MAILER=log` (MVP-TECHNICAL-GATE #3); Staging-Deployment ohne gesonderte Freigabe nicht erlaubt |
| PDF-Sichtprüfung | BLOCKED | PDFs werden in Tests nur auf Existenz und Snapshot-Quelle geprüft, nicht visuell |
| Staging-Durchlauf mit Mail-Umleitung | BLOCKED | Deployment/Migration auf Staging nicht freigegeben |
## Testfälle (Auftrag §13)
Legende: **PASS** = automatisiert ausgeführt und bestanden · **PARTIAL** = Logik getestet, Praxisnachweis offen · **BLOCKED** = nicht ausgeführt · **EXISTING** = durch bereits vorhandenen, bestehenden Test abgedeckt (in der Vollsuite grün).
| # | Fall | Ergebnis | Nachweis (Test) |
|---|---|---|---|
| 1 | Manuelle Anfrage ohne Vorreservierung | PASS | `AutoOfferTest::test_without_pre_reservation_a_request_blocks_nothing` (keine Sperre, Mailtext „noch nicht reserviert“, zweite Anfrage derselben Zeit möglich) |
| 2 | Manuelle Anfrage mit Vorreservierung | PASS | `test_manual_mode_sends_the_receipt_and_no_offer` |
| 3 | Automatisches Angebot mit Vorreservierung | PASS | `test_automatic_mode_sends_the_offer_instead_of_the_receipt`, `…_can_be_accepted_end_to_end` |
| 4 | Auto ohne Vorreservierung | PASS | `test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why` (Grund in Notiz + Betreiber-Mail); Formular lehnt die Kombination ab (Regel in `PropertyForm`, **nicht** per Test geprüft) |
| 5 | Angebot aufrufen und annehmen | PASS (HTTP) / BLOCKED (Mail-Client) | `test_accepting_twice_over_http_…`, `OfferWorkflowTest` |
| 6 | Bestätigung + PDF | PARTIAL | Mail mit Vertrag gesendet, Datei vorhanden (`test_acceptance_records_the_evidence_and_confirms_once`); Inhalt nicht visuell geprüft |
| 7 | Kalender und iCal-Ausgabe | PARTIAL | Belegung/`occupying()` geprüft; Feed-Inhalt nach Annahme nicht eigens neu getestet (Feed wird live aus DB gebaut; `ChannelExportRequestTest` EXISTING) |
| 8 | Abgelaufene Haltefrist | PASS | `test_expired_offer_cannot_be_accepted`; `OfferWorkflowTest::test_offer_holds_the_dates_until_it_expires` |
| 9 | Annahme kurz vor Fristablauf | PARTIAL | Frist wird in der Transaktion gegen die gesperrte Zeile geprüft; Randfall (Sekunden vor Ablauf) nicht eigens getestet. Bekannte Lücke: signierte POST-URL läuft mit der Frist ab → 403 mit neuer deutscher Seite statt Angebots-Hinweis |
| 10 | Doppelte Annahme | PASS | `test_second_acceptance_…_idempotent`, `test_stale_copy_…`, `test_accepting_twice_over_http_…` (1× Bestätigung, 1× Betreiber-Mail) |
| 11 | Gleichzeitige Annahmen | **BLOCKED** (MariaDB) | nur Logik (Fall 10) belegt |
| 12 | Zwei konkurrierende Buchungen | PARTIAL | `test_two_overlapping_stays_cannot_both_become_binding` (sequenziell); echte Parallelität BLOCKED |
| 13 | Konflikt durch externen Kalendereintrag | PASS | `test_conflicting_occupation_prevents_acceptance_and_leaves_no_evidence` |
| 14 | Änderung von Preis/Bedingungen nach Versand | PASS | `test_changed_website_texts_do_not_alter…`, `test_tampered_offer_is_refused…`, `test_changed_terms_snapshot_is_refused` |
| 15 | Erfolgreicher Import | EXISTING | `ChannelSyncTest` |
| 16 | Fehlgeschlagener Import | PASS | `test_stale_calendar_import_blocks_the_automatic_offer` (HTTP 500 gefaket → Kanal bleibt veraltet), `test_acceptance_is_refused_while_a_portal_calendar_is_stale` |
| 17 | Sofortbuchungsportal vor Abruf | PASS | `test_instant_booking_portal_holds_the_offer_back_until_it_fetched_our_feed` |
| 18 | Sofortbuchungsportal nach nachgewiesenem Abruf | PASS | derselbe Test (Angebot nach Abruf per `bookings:auto-offers`); Abruf als Datensatz erzeugt, nicht über den echten Feed-Endpunkt |
| 19 | Kanal ohne Sofortbuchung | PASS | `test_portal_without_instant_booking_needs_no_proof` |
| 20 | Nicht zuordenbarer Abruf | PASS | `test_unattributable_feed_request_is_not_recorded_as_proof`, `test_feed_fetch_before_the_block_or_failed_fetch_or_other_channel_is_no_proof` |
| 21 | Sync-Fehler nach bestätigter Buchung | PASS | `test_failing_portal_task_creation_does_not_fail_the_acceptance` |
| 22 | Anfrage über Portal-Mail | EXISTING | `PortalMailTest` (nicht Teil dieser Änderung) |
| 23 | Portal-Mail unvollständig | EXISTING | `PortalMailTest::…without_readable_dates…` |
| 24 | iCal ohne Gastdaten | EXISTING | `ChannelOccupationResolutionTest`, `ChannelSyncTest` |
| 25 | Bereits verbindliche Portalbuchung | EXISTING | `PortalMailTest::test_booking_mail_blocks_immediately…` (Sperre, kein Annahmeprozess) |
| 26 | Doppelt eintreffende Infos | EXISTING | `ChannelOccupationResolutionTest` (UID-/Alias-Fälle) |
| 27 | Mailfehler bei Angebot | PASS | `test_failing_offer_mail_is_reported_but_the_offer_stays` |
| 28 | Mailfehler bei Bestätigung | PASS | `test_failing_confirmation_mail_keeps_the_binding_booking_and_can_be_resent` (keine Adresse im Postfachtext) |
| 29 | Wiederholter Nachversand | PASS | gleicher Test + `test_command_retries_failed_confirmations_once_the_mail_server_is_back` (genau 1 Zustellung) |
| 30 | Abgelaufener/manipulierter Link | PASS | `test_invalid_signature_shows_the_german_error_page`, `OfferWorkflowTest::test_offer_page_needs_a_valid_signature`, `…older_offer_version…` |
| 31 | Fehlerhafte Session / 419 | PARTIAL | deutsche 419-Seite angelegt; **kein Test**, der ein 419 auslöst |
| 32 | Regression bei deaktivierter Automatik | PASS | Standard `manual`; gesamte bestehende Suite grün (561/561) |
| – | GET löst nichts aus | PASS | `test_get_on_the_offer_link_never_changes_the_booking` |
| – | Testbetrieb/Mail-Umleitung unverändert | EXISTING | bestehende Tests (`MailRoutingTest` u. a.) grün; Code in `Settings` nicht angefasst |
| – | Live: Muster-Texte blockieren Auto-Angebot | PASS | `test_live_operation_needs_released_contract_texts_for_automatic_offers` |
## Kontrolle nach Tests (§13 Abnahmekriterien) – was geprüft wurde
Datenbankstatus, Annahmenachweis (Felder, Hash), gespeicherte Angebotsversion und Snapshot, Postfacheinträge, gesendete Mailklassen und Anzahl: **per Assertion in den Tests**. Belegungskalender: `occupying()`/Verfügbarkeitsprüfung. **Nicht geprüft:** ausgehende iCal-Feeds nach Annahme (kein eigener Test), tatsächliche E-Mail-Inhalte außer den genannten Textstellen, PDF-Inhalt, Admin-Ansicht (Infolist/Aktion „Bestätigung erneut senden“ sind nur durch die Seitenaufrufe der bestehenden Suite „gerendert“, die neue Aktion selbst hat **keinen** Test), Monitoring.
## Bekannte Fehler und Einschränkungen
1. Neue Admin-Aktion und die Property-Formulargültigkeit (auto + ohne Vorreservierung) sind ungetestet.
2. Keine Tests für 419 und die Annahme in der letzten Sekunde.
3. Echte Datenbanksperren unbelegt (siehe oben) – wichtigster offener Punkt.
4. Migrationen wurden nur in der SQLite-Testdatenbank ausgeführt; nicht gegen MariaDB (Syntax ist Standard `json`/`string`/`boolean`/`timestamp`, aber ungeprüft).
5. Das Verhalten „Annahme verlangt aktuellen Import“ gilt für alle Wohnungen mit aktivem Import (nicht nur Automatik) und kann Annahmen bei gestörtem Portalimport verhindern (gewollt, siehe Implementation §Restrisiken).
6. Ursache der früheren Einzelfehler in `WebsiteTenancyTest` nicht geklärt (siehe oben).
## Status produktive Einsatzfähigkeit
Code und automatisierte Tests: bereit zur Überprüfung (Review). **Nicht einsatzbereit für echte Gäste**, solange offen: MariaDB-Parallelitätsnachweis, Staging-Durchlauf mit echter Mailzustellung und PDF-Sichtprüfung, Produktivumgebung (MVP-TECHNICAL-GATE #1–#4), freigegebene Vertragstexte, separate Compliance-Prüfung.
## GO / NO-GO
**NO-GO** für Aktivierung automatischer oder verbindlicher Online-Buchungen mit echten Gästen. **GO** für: Code-Review, Merge in einen Feature-Branch, anschließend MariaDB-Test und Staging-Migration nach ausdrücklicher Freigabe.
## Nächste Schritte (Reihenfolge)
1. Entscheidung, wie MariaDB für den Parallelitätstest bereitgestellt wird (lokal selbst installiert oder Docker; oder Test gegen Staging-DB).
2. Dann: zwei-Prozess-Test (gleichzeitige Annahme, konkurrierende Buchung) und Migrationen auf MariaDB.
3. Freigabe für Staging-Migration + Deployment → Durchlauf mit Mail-Umleitung, PDF- und Feed-Prüfung.
+78
View File
@@ -0,0 +1,78 @@
# BOOKING-E2E-IMPLEMENTATION
Stand: 30.10.2026 · Branch `feature/buchung-e2e` (von `develop`) · nur Entwicklungsumgebung (SQLite-Tests). **Nichts committet, nichts deployt, keine Migration auf Staging/Produktion.**
Grundlage: `BOOKING-E2E-READINESS.md`. Ergebnisse der Prüfungen: `BOOKING-E2E-ACCEPTANCE.md`.
## 1. Umgesetzte Änderungen
### Phase 1 – Sicherheitskern
| Thema | Umsetzung |
|---|---|
| Angebots-Snapshot | `SendOffer` friert pro Version in `bookings.offer_terms` ein: Mietbedingungen, Storno, Hausordnung, Vertragseinleitung/-schluss, Vertragshinweis, Annahmehinweis, Button-Beschriftung, Anzahlungsfrist, Vermieter- und Bankdaten (`App\Documents\OfferTerms`). Angebotsseite, Angebots-PDF, Final-PDF und Annahme lesen aus dem Snapshot (`Booking::offerText()/offerHtml()`); Altbuchungen ohne Snapshot fallen auf die Live-Texte zurück. Direkte Bestätigung durch den Admin friert beim Bestätigen ein. |
| Angebots-Hash | `bookings.offer_hash` = SHA-256 über Version, Termine, Personen, Quote, Beträge, Zahlungstermin und Snapshot (ohne Gültigkeit, die der Betreiber verlängern darf). |
| Atomare Annahme | `AcceptOffer`: eine Transaktion mit Sperre auf Wohnung **und** Buchungszeile (`Booking::lockForTransition()`), dann Version, Status, Frist, Hash und Verfügbarkeit prüfen, Nachweis schreiben **und** `Confirmed` setzen – oder nichts. Dieselbe Wohnungssperre nutzen jetzt `CreateReservation`, `SendOffer`, `ConfirmBooking`, `RejectOffer`. |
| Idempotenz | Zweite Annahme derselben Version: keine zweite Buchung, keine zweite Mail, Gast sieht „bereits verbindlich bestätigt“. Auch eine veraltete Modellkopie wird über die gesperrte Zeile erkannt. |
| Nachweis | `acceptance` (JSON): Angebotsversion, Annahme-/Versandzeit, Gültigkeit, Gesamtbetrag, `offer_hash`, `quote_sha256`, `terms_sha256` (über den **gezeigten** Snapshot), Button-Text, `via`. Keine IP, kein Token. |
| Mail nach Commit | `ConfirmBooking::deliver()` (Vertrag + Mail) läuft nach dem Commit; Fehler setzen `confirmation_failed_at`, schreiben ins Postfach (`InboxMessageKind::ConfirmationFailed`) und lassen die Buchung bestehen. Ohne erzeugtes Vertrags-PDF wird keine Bestätigung ohne Anhang versendet. |
| Nachversand | Admin-Aktion „Bestätigung erneut senden“ (Buchungsseite), Befehl `bookings:resend-confirmations` (alle 15 Min., nur Fehlversuche der letzten 3 Tage). |
| Angebotsmail | `SendOffer::deliver()`: Fehler → Postfach (`OfferMailFailed`), Angebot bleibt gespeichert, Admin erhält verständliche Meldung (Link kann kopiert werden). |
| Portal-Sync | `BookingObserver`: Fehler beim Anlegen von Portalaufgaben schlagen nicht mehr auf den Gast durch; Postfachmeldung `SyncFailed`. |
| Logs | Fehler werden nur mit Klasse + Buchungs-ID geloggt (Mailer-Meldungen können Adressen enthalten). Keine Tokens/Links. |
| Fehlerseiten | Deutsche Seiten 403/404/419/429/500/503 (`resources/views/errors`), 403 erklärt abgelaufene/ungültige Links, 419 „Sitzung abgelaufen – nichts wurde verändert“. Betrifft alle Seiten der Anwendung (vorher englische Standardseiten). |
| Aufräumen | Debug-`dump()` aus `OfferWorkflowTest` entfernt. |
### Phase 2 – Betriebsmodi und Vorreservierung
- Je Wohnung (`properties`): `offer_mode` (`manual` Standard / `automatic`) und `pre_reservation_enabled` (Standard `true`), neben dem vorhandenen `hold_hours`. Einstellbar in der Wohnungsverwaltung (Abschnitt Zahlung/Vorreservierung). Validierung: *automatisch* + *ohne Vorreservierung* wird abgelehnt.
- Ohne Vorreservierung entsteht eine `Reserved`-Anfrage **ohne** `hold_expires_at`; sie sperrt nichts (`occupying()`-Scope), läuft nicht ab und wird erst durch Angebot/Entscheidung des Betreibers weiterbewegt.
- `CreateReservation` entscheidet über Mails: *manuell* → Eingangsbestätigung an Gast + Mitteilung an Betreiber; *automatisch und freigegeben* → nur das Angebot an den Gast, Betreiber-Mail „Angebot automatisch versendet“; *automatisch, aber nicht freigegeben* → Eingangsbestätigung + Betreiber-Mail mit den Gründen, Gründe zusätzlich in den internen Notizen. Keine doppelten Gast-Mails.
- Eingangsbestätigung, Betreiber-Mail und Bestätigungsseite behaupten eine Vormerkung nur, wenn tatsächlich eine aktive Haltefrist besteht (genauer Ablaufzeitpunkt), sonst „noch nicht reserviert“.
- Der bestehende Testbetrieb (`Settings`, Mail-Umleitung) ist **unverändert**; Modus und Testbetrieb sind unabhängig.
### Phase 3 – Kanalabhängige Freigabe
`App\Actions\AutoOffer` + `App\Availability\CalendarClearance`:
1. Stufe Betreiberfreigabe: im **Livebetrieb** müssen Mietbedingungen (kein „[MUSTER“), Storno und IBAN gefüllt sein; im Testbetrieb entfällt die Prüfung, damit der Ablauf mit Mustertexten testbar ist.
2. Import: jeder aktive Importkanal braucht einen erfolgreichen Import innerhalb von `fewo.channels.fresh_within_minutes` (15, `FEWO_CHANNEL_FRESH_WITHIN_MINUTES`); sonst wird **einmal** ein Import versucht (Netzwerk außerhalb jeder Transaktion), danach gilt „nicht aktuell“.
3. Sofortbuchung: Kanäle mit Buchungsmodell *Portalbuchung* oder *Gemischt* gelten als sofortbuchungsfähig (bestehendes Feld `booking_model`, keine neue Spalte). Freigabe nur, wenn dieser Kanal **nach Anlage der Sperre** (`created_at` + 1 s) unseren Feed mit **HTTP 200 und Zustand „live“** abgerufen hat (bestehende Tabelle `channel_export_requests`; Zuordnung über den kanaleigenen Token). Unzuordenbare Abrufe (falscher Token → 404) werden nicht protokolliert und zählen nie. Abrufe vor der Sperre, fehlgeschlagene (503) und Abrufe anderer Kanäle zählen nicht.
4. Kanäle ohne Sofortbuchung: kein Abrufnachweis nötig.
5. Verfügbarkeit erneut prüfen; Vorreservierung muss aktiv sein.
6. Nicht freigegeben → kontrollierter Rückfall auf manuell; `bookings:auto-offers` (alle 5 Min.) versucht es für noch gehaltene Anfragen erneut (z. B. sobald das Portal den Feed abgerufen hat).
7. **Bei der Annahme** (`AcceptOffer`): vor der Transaktion Import aufgefrischt; bleibt ein Importkanal veraltet, wird **nicht** gebucht, der Gast erhält eine verständliche Meldung, der Betreiber eine Postfachmeldung. Danach gesperrte Verfügbarkeitsprüfung (inkl. Portal-Sperren) in der Transaktion.
### Phase 4 – Portalanfragen / Verwaltung
Weitgehend **bereits vorhanden** und durch bestehende Tests belegt (nicht neu implementiert): Portal-Mails → Sperre mit Quelle `email` (`ProcessPortalMail`, `PortalMailTest`), iCal-Einträge ohne Gastdaten bleiben anonyme Sperren mit Kanalbezug (`BlockedPeriod`), manuelle Gast-Zuordnung (`AssignOccupationGuest`), Zusammenführung nur über eindeutige UID bzw. ausdrückliche Betreiber-Entscheidung (`ChannelOccupationResolutionTest`), Doppelmeldungen/Konflikte (`ConflictDetector`, Postfach), Portalbuchungen gehen nie durch den Annahmeprozess. Neu: Buchungsseite zeigt Bearbeitungsmodus, Angebotsversion + Prüfsumme, Annahmezeitpunkt und Zustellstatus der Bestätigung.
## 2. Geänderte / neue Dateien
Neu: `app/Documents/OfferTerms.php`, `app/Actions/AutoOffer.php`, `app/Availability/CalendarClearance.php`, `app/Enums/OfferMode.php`, `app/Console/Commands/ResendBookingConfirmations.php`, `app/Console/Commands/SendPendingAutoOffers.php`, `resources/views/errors/*`, `tests/Feature/BookingAcceptanceTest.php`, `tests/Feature/AutoOfferTest.php`, zwei Migrationen (unten).
Geändert: `AcceptOffer`, `ConfirmBooking`, `SendOffer`, `RejectOffer`, `CreateReservation`, `BookingObserver`, `OfferController`, `Booking`, `Property`, `ReservationException`, `InboxMessageKind`, `Inbox` (optionale `propertyId`), `NewReservation`/`ReservationReceived` (Mail + Views), `offer.blade.php`, `pdf/contract.blade.php`, `booking-request.blade.php`, `PropertyForm`, `BookingInfolist`, `ViewBooking`, `config/fewo.php`, `routes/console.php`, `OfferWorkflowTest`.
### Migrationen (additiv, nullable bzw. mit Default; bestehende Daten unverändert)
1. `2026_10_30_110811_add_offer_snapshot_and_confirmation_tracking_to_bookings_table`: `bookings.offer_terms` (json), `offer_hash` (string 64), `confirmation_sent_at`, `confirmation_failed_at`.
2. `…_add_offer_mode_and_pre_reservation_to_properties_table`: `properties.offer_mode` (Default `manual`), `pre_reservation_enabled` (Default `true`).
Nicht migriert zur Wahrung des Bestands: Altbuchungen bekommen **keinen** nachträglichen Snapshot/Hash.
## 3. Konfiguration der Betriebsarten
- Wohnung bearbeiten → *Vorreservierung halten* (Stunden), *Anfrage blockiert den Kalender*, *Bearbeitung von Anfragen* (manuell/automatisch).
- Kombination automatisch + ohne Vorreservierung ist gesperrt (Formularfehler).
- Kanal bearbeiten → Buchungsmodell: *Vermittlung/Anfrage* = keine Sofortbuchung; *Portalbuchung* oder *Gemischt* = Sofortbuchung (konservativ). Export muss aktiv sein.
- Testbetrieb/Livebetrieb: System › Betrieb, unverändert und unabhängig.
- **Standard bleibt: manuell, Vorreservierung an** → Verhalten wie bisher. Rollback: Modus auf *manuell* stellen.
- Neue Zeitpläne (Scheduler, bestehender n8n-Aufruf genügt): `bookings:auto-offers` (5 Min.), `bookings:resend-confirmations` (15 Min.).
## 4. Restrisiken
1. **Portal-Verzögerung:** Ein erfolgreicher Feed-Abruf beweist die Auslieferung, nicht die Verarbeitung im Portal. Eine gleichzeitige Sofortbuchung im Portal ist nicht ausschließbar; sie wird erst über Import/Portal-Mail erkannt und als Konflikt gemeldet (KONZEPT §7).
2. Veraltete Importe verhindern Annahmen (gewollt) – ein dauerhaft gestörter Kanal blockiert also Buchungen, bis er repariert oder pausiert wird. Postfach zeigt es.
3. Ohne Vorreservierung zählen offene Anfragen nicht in die Obergrenze „offene Anfragen je E-Mail“ (Rate-Limits bleiben aktiv).
4. `bookings:auto-offers` sendet in Automatikwohnungen auch dann, wenn der Betreiber eine vorgemerkte Anfrage noch nicht angefasst hat – wer einzelne Anfragen prüfen will, schaltet die Wohnung auf manuell.
5. Eine später per Wiederholung gesendete automatische Offerte meldet dem Betreiber nichts Zusätzliches (er sieht den Status in der Buchung).
6. Parallelitätsschutz beruht auf `SELECT … FOR UPDATE` (InnoDB). Unter SQLite wirkt die Sperre nicht (Einzelschreiber); **auf MariaDB noch nicht praktisch nachgewiesen** (siehe Acceptance).
7. Keine Datenbank-Constraint gegen überlappende Buchungen (nicht sinnvoll realisierbar); Schutz = einheitliche Wohnungssperre in allen schreibenden Pfaden. Neue Schreibpfade müssen `lockForTransition()` nutzen.
8. Das 403/419-Verhalten gilt für alle Seiten; die Formular-Session des Annahmeformulars (CSRF) läuft weiter nach 120 Min. ab (jetzt mit klarer Seite).
## 5. Nicht umgesetzt / spätere Ausbaustufen
- Portal-APIs, Channel-Manager, Webhook-Bestätigung durch Portale.
- Eigene Tabelle für Ereignisverlauf (Audit-Trail); aktuell JSON `acceptance` + Postfach + Statusfelder.
- Gast-Nachfrage/Kommunikationsverlauf in der Buchung; E-Mail-Verifikation der Anfrage.
- Auswertung `Retry-After`/Portal-Rückmeldungen; kanalspezifische Abrufnachweise für `HEAD`.
- Anzeige der Bedingungen des Snapshots im Admin als Download; Hausordnung auf der Angebotsseite (steht im PDF).
- Portal-Anfragen mit unvollständigen Daten: weiterhin über die bestehende Zuordnungsmaske; keine neuen Importformate.
+194
View File
@@ -0,0 +1,194 @@
# BOOKING-E2E-READINESS – End-to-End-Direktbuchung
Stand: 30.10.2026 · Branch `feature/titelvideo-rundgang` · Phase 1: **Analyse und Plan, nur lesend.**
Es wurden keine Code-, Datenbank-, CMS- oder Serveränderungen vorgenommen. Phase 2 beginnt erst nach ausdrücklicher Freigabe.
**Grenzen dieser Analyse (ehrlich vorab):**
- Geprüft wurde der **Quellcode** (Actions, Controller, Views, Mails, Observer, Tests). Die Testsuite wurde **nicht ausgeführt**, Staging (stommer.info) wurde **nicht** aufgerufen, kein Mail-Versand versucht.
- Die Aussagen zu Nebenläufigkeit (Abschnitt 3) sind **Code-Analyse, nicht durch Lasttest belegt**. Sie sind in Phase 2 mit einem echten Parallel-Test auf MariaDB zu bestätigen.
- Rechtstexte, Button-Wortlaut und Vertragsinhalte wurden nicht rechtlich bewertet (Verantwortung Betreiber).
---
## 1. Fazit in drei Sätzen
Der Weg „Anfrage → Angebot → signierter Link → Annahme → Bestätigung + Vertrag“ **existiert bereits vollständig** (KONZEPT §6a, Weg 1) und ist architektonisch passend. Zum Soll-Prozess fehlen **drei Dinge**: (a) das Angebot wird heute **manuell** durch die Vermieterin erzeugt (Soll: automatisch), (b) die Annahme ist **nicht transaktionssicher und nicht idempotent**, und die Fehlerbehandlung bei Mailproblemen kann einen Gast nach verbindlicher Buchung vor eine Fehlerseite stellen, (c) die **Vertragsbedingungen werden nicht als Angebotsversion eingefroren** – die Annahme-Nachweise hashen die zum Zeitpunkt der Annahme gerade gültigen Texte, nicht die dem Gast gezeigten. Alles ist mit kleinen, rückwärtskompatiblen Änderungen lösbar, ohne Architekturumbau.
---
## 2. Ist-/Soll-Abgleich
| # | Soll-Schritt | Ist (Fundstelle) | Bewertung |
|---|---|---|---|
| 1 | Gast stellt unverbindliche Anfrage | `Livewire\BookingRequest` → `CreateReservation`; Bot-Schutz, Rate-Limits | ✅ vorhanden |
| 2 | Verfügbarkeit prüfen, Preis berechnen | `CreateReservation` (Property-`lockForUpdate`, `AvailabilityChecker`, `PriceCalculator`) | ✅ vorhanden |
| 3 | Zeitraum befristet reservieren, **versioniertes Angebot** mit allen Bedingungen | Reservierung: `Reserved` + `hold_expires_at` (✅). Angebot: `SendOffer` erhöht `offer_version`, speichert `quote`, erzeugt Entwurfs-PDF (✅). **Aber:** nur auf manuelle Aktion im Admin; Bedingungen werden **nicht** als Snapshot gespeichert | ⚠️ **Lücke A + C** |
| 4 | Angebot per E-Mail mit sicherem Annahmelink | `OfferMade` + `SendOffer::offerUrl()` (`temporarySignedRoute`, Ablauf = `hold_expires_at`, Version `v` im Link) | ✅ vorhanden |
| 5 | Link öffnet nur die Angebotsseite, ohne Buchung | `GET /angebot/{booking}` → `OfferController::show` ändert nichts; Annahme nur per `POST` | ✅ vorhanden |
| 6 | Gast prüft Preis, Leistungen, Zahlungs-/Stornobedingungen | `resources/views/offer.blade.php`: Aufenthalt, Preiszeilen, Zahlungsplan, `contract.terms`, `stay.cancellation`, Gültig-bis | ✅ weitgehend. Lücken: Bedingungen kommen aus *aktuellem* CMS-Stand (C); Hausordnung (`stay.house_rules`) steht im PDF, aber nicht auf der Seite; kein speicher-/druckbares Dokument auf der Seite selbst |
| 7 | Ausdrückliche Bestätigung „Zahlungspflichtig buchen“ | Checkbox „gelesen“ + Button, Text aus `offer.accept_button` (Default: „Angebot zahlungspflichtig annehmen“), Hinweis `offer.accept_note` | ✅ technisch; **Wortlaut ist Betreiber-/Rechtsfrage** (Q1) |
| 8 | Gültigkeit **und** Verfügbarkeit erneut prüfen | Gültigkeit/Version/Status: `AcceptOffer::ensureAcceptable`. Verfügbarkeit: `ConfirmBooking` (in Transaktion, ohne Sperre) | ⚠️ **Lücke B** |
| 9 | Annahme dokumentieren, `Confirmed` setzen | `AcceptOffer`: `accepted_at` + JSON `acceptance` (Version, Zeit, Gesamt, `quote_sha256`, `terms_sha256`, `via`) → `ConfirmBooking` | ⚠️ Nachweis unvollständig (C); Schreiben nicht atomar mit Statuswechsel (B) |
| 10 | Bestätigung + Vertragsunterlagen | `BookingConfirmed` mit Vertrags-PDF (`RentalContract::generate`) | ⚠️ Fehlerbehandlung (D); finales PDF wird aus *aktuellen* Texten neu gerendert (C) |
| 11 | Kalender verbindlich gesperrt, Portal-Sync ausgelöst | `occupying()`-Scope; iCal-Feed wird bei Abruf live berechnet (kein Cache, `no-cache`); `BookingObserver` → `CreateChannelTasks` für Portale mit manueller Sperre, Webhook-Automation | ✅ im Kern; Fehlerpfad prüfen (E) |
---
## 3. Gefundene Schwachstellen (aus dem Code belegt)
**B1 – Annahme ist nicht atomar und nicht idempotent** (`AcceptOffer::handle`, `ConfirmBooking::handle`)
- `ensureAcceptable()` liest Status/Frist **außerhalb** einer Transaktion und ohne Zeilensperre. Zwei gleichzeitige POSTs (Doppelklick, Mail-Client-Prefetch ist hier unkritisch, weil POST) können beide die Prüfung bestehen.
- Beide schreiben `accepted_at`/`acceptance`; beide rufen `ConfirmBooking` mit **veraltetem In-Memory-Status** `OfferSent` auf → doppelte `BookingConfirmed`-Mail und doppelte `OfferAnswered`-Mail sind möglich; `confirmed_at` und `deposit_due_on` werden überschrieben.
- Wird `ConfirmBooking` mit `notAvailable` abgewiesen, **bleiben `accepted_at` und `acceptance` bereits gesetzt**, während der Status `OfferSent` bleibt (Schreiben erfolgt vor der Transaktion). Das ist ein falscher Annahmenachweis.
- Zweiter, *nacheinander* erfolgender Klick: Gast sieht die Fehlermeldung „Eine Buchung im Status ‚Bestätigt‘ kann nicht angenommen werden“, obwohl seine Annahme gelungen ist. Soll: idempotent („bereits angenommen am …“).
**B2 – Verfügbarkeitsprüfung ohne Sperre** (`ConfirmBooking`, `SendOffer`)
- `CreateReservation` sperrt die Property-Zeile (`lockForUpdate`), `ConfirmBooking` und `SendOffer` nicht. Unter MariaDB/InnoDB (REPEATABLE READ) ist `exists()` ein nicht sperrender Lesezugriff. Für überlappende Buchungen reicht die Sperre in `CreateReservation` nur, solange alle Schreiber dieselbe Sperre nehmen.
- Konkretes Risiko: Hold einer Anfrage läuft ab (`Expired`-Status wird nur vom 5-Minuten-Cron gesetzt, der Kalender gibt den Zeitraum aber sofort frei) → Dritter reserviert denselben Zeitraum → alte Anfrage wird danach durch den Admin über `ConfirmBooking` bestätigt (Expired ist dort erlaubt, Prüfung läuft ohne Sperre). Für die **Gast-Annahme** ist das durch `ensureAcceptable` (Frist) abgefangen; für Parallelität zweier Bestätigungen gilt B2 trotzdem.
- Es gibt **keine Datenbank-Garantie** gegen überlappende verbindliche Buchungen (kein Constraint; bei MariaDB ohnehin nur mit Exclusion-Tricks möglich). Sinnvoll ist daher die konsequente Property-Sperre in jedem schreibenden Pfad.
- Portal-Importe (`SyncChannel` → `BlockedPeriod`) laufen unabhängig; eine Doppelbelegung durch Portalbuchung zwischen Prüfung und Commit wird erst von `ConflictDetector` / `ReportChannelConflicts` gemeldet (Restrisiko laut KONZEPT §7, nicht lösbar ohne Channel-Manager-API).
**C – Angebotsversion ist nicht unveränderlich** (`SendOffer`, `AcceptOffer`, `offer.blade.php`, `pdf/contract.blade.php`)
- Preis/Quote werden pro Version gespeichert und das Entwurfs-PDF pro Version abgelegt (gut). **Nicht** gespeichert: Mietbedingungen (`contract.terms`), Stornobedingungen (`stay.cancellation`), Hausordnung, Vertragseinleitung/-schluss, Zahlungsdaten (`deposit_due_days`, Bankdaten).
- Die Angebotsseite rendert diese Texte **live** aus `Content`. Ändert der Betreiber nach Versand die Bedingungen, sieht der Gast beim Annehmen *andere* Bedingungen als in der E-Mail/dem PDF.
- `AcceptOffer` berechnet `terms_sha256` **beim Annehmen** aus dem dann aktuellen Text. Der Nachweis belegt also „Texte zum Zeitpunkt der Annahme“, nicht „Texte, die in Version n angeboten wurden“. Eine Änderung zwischen Versand und Annahme bleibt unbemerkt (Testaufgabe 5 würde das aufdecken).
- `ConfirmBooking` erzeugt das finale Vertrags-PDF neu aus **aktuellen** Texten; es kann vom Angebots-PDF abweichen.
- `quote_sha256` wird ebenfalls erst bei Annahme gebildet; eine Änderung von `quote`/`total` zwischen Versand und Annahme (z. B. durch Admin-Bearbeitung) würde mitgehasht statt erkannt.
**D – Fehlerbehandlung bei Mail** (`AcceptOffer`, `ConfirmBooking`, `SendOffer`, `OfferController::answer`)
- `ConfirmBooking` sendet `BookingConfirmed` **ungeschützt** nach dem Commit. Wirft der Mailversand (SMTP down), ist die Buchung bereits `Confirmed`, der Controller fängt nur `ReservationException` → Gast sieht eine **500-Seite** und glaubt, nichts sei passiert. Er klickt erneut → Fehlermeldung „Status Bestätigt“ (B1). Die Betreiber-Mail `OfferAnswered` wird in diesem Fall nicht mehr gesendet (Exception unterbricht `AcceptOffer`).
- Es gibt keine Nachversand-Möglichkeit/-Markierung: kein Feld „Bestätigung gesendet am“, kein Eintrag im Postfach (`AppSupportInbox`) für fehlgeschlagene Gästemails. `CreateReservation` fängt dagegen korrekt ab (`report($exception)`), ist aber ebenfalls nur im Log sichtbar.
- `SendOffer`: wirft der Versand, ist der Status schon `OfferSent` (Frist läuft!), aber der Gast hat nichts bekommen; der Admin sieht den Fehler, ein automatischer Prozess hätte keinen Ort dafür.
- `report($exception)` schreibt die Exception ins Log; Symfony-Mailer-Fehlermeldungen können Empfängeradressen enthalten → **personenbezogene Daten im Log** (Q6).
**E – Portal-Sync-Fehlerpfad** (`BookingObserver::tasks`, `CreateChannelTasks`)
- Der iCal-Export wird live berechnet; die Sperre ist sofort im Feed sichtbar. Portale ziehen den Feed selbst (Verzögerung portalseitig, bekannt).
- Der Observer läuft in `DB::afterCommit`. Exceptions in diesem Closure (z. B. DB-Fehler beim Anlegen der `ChannelTask`) würden **nach** dem Commit nach oben durchschlagen → Gast bekäme 500, obwohl Buchung steht. Mail und Webhook darin sind einzeln mit `rescue`/`try` abgesichert, die Aufgabenanlage selbst nicht.
- Fehlgeschlagene Webhooks landen in `ChannelTask.automation_error` und werden vom bestehenden Erinnerungs-/Monitor-Mechanismus aufgegriffen (✅). Für den Gast-Pfad soll gelten: **Sync-Fehler dürfen die Annahme nie scheitern lassen**, müssen aber für die Betreiber sichtbar werden.
**F – Sonstiges**
- `tests/Feature/OfferWorkflowTest.php` (Test `test_guest_accepts_the_offer_and_the_booking_becomes_binding`) enthält am Ende ein **`dump(strip_tags(...))`** – Debug-Überbleibsel, erzeugt Ausgabe in jedem Testlauf. Beim Umbau entfernen.
- Formular-POST nutzt CSRF + Session. Bleibt die Angebotsseite > 120 Min. offen, liefert der Server eine **englische 419-Standardseite** (bereits in MVP-TECHNICAL-GATE #6 als Fehlerseiten-Thema). Für den Annahmeweg besonders unglücklich → deutsche 419-Seite mit Rücksprung auf die (neu signierte) Angebotsseite.
- Die signierte POST-URL läuft mit `hold_expires_at` ab; der Gast, der bis kurz vor Fristende wartet, kann zwischen Seitenaufruf und Klick in den Ablauf laufen → bekommt dann die (richtige) Meldung „nicht mehr gültig“ über die 403 des `signed`-Middleware (englische Standardseite!), nicht über `offerExpired()`. Zu prüfen/abzufangen.
---
## 4. Wiederverwendbare Bestandteile (nicht neu bauen)
| Bestandteil | Verwendung |
|---|---|
| `CreateReservation` | Schritt 1–2 unverändert; Property-Sperre als Vorlage für B2 |
| `SendOffer` (`handle(..., sendMail)`, `offerUrl()`) | Auto-Angebot: Aufruf mit leerem `$changes`; Preis wird neu berechnet |
| `PriceCalculator` / `PriceQuote` / `QuoteException` | unverändert |
| `AcceptOffer` / `RejectOffer` / `ConfirmBooking` | Kern bleibt, wird gehärtet statt ersetzt |
| `OfferController`, `offer.blade.php`, Routen `offers.*` (signiert, Throttle) | bleiben, Bedingungen kommen künftig aus dem Snapshot |
| `RentalContract` (Draft pro Version, finaler Vertrag) | Snapshot als Datenquelle |
| `OfferMade`, `BookingConfirmed`, `OfferAnswered`, `ReservationReceived`, `NewReservation` | unverändert (Inhalt Betreiber) |
| `Booking::occupying()`, `AvailabilityChecker` | unverändert; nur Sperre ergänzen |
| `BookingObserver` → `CreateChannelTasks`, iCal-Feed, `ConflictDetector` | Sync-Auslösung bleibt; Fehlerpfad absichern |
| `ExpireReservations` / `bookings:expire-holds` | unverändert |
| `AppSupportInbox` (Postfach, Fingerprint, Erinnerungsintervall) | Ablage für Mail-/Sync-Fehler |
| `Settings::notificationRecipients()`, Testmodus | unverändert (alle Tests laufen im Testmodus) |
| `ReservationException` (gast-taugliche Meldungen) | um wenige Fälle erweitern |
---
## 5. Minimal erforderliche Codeänderungen
1. **Auto-Angebot (A):** Neue Action `App\Actions\AutoOffer` (oder Option in `CreateReservation`), die nach erfolgreicher Reservierung `SendOffer->handle($booking)` aufruft. Gesteuert über eine **Einstellung je Wohnung/Mandant** (`auto_offer`, Default **aus** → bisheriges Verhalten bleibt). Fehler des Versands werden abgefangen (siehe D); die Reservierung geht nie verloren. Die bisherige Eingangsbestätigung (`ReservationReceived`) wird bei aktivem Auto-Angebot nicht doppelt gesendet.
*Hinweis:* Das Angebot soll bei Auto-Angebot dieselbe Frist wie `hold_hours` haben (48 h, je Wohnung einstellbar).
2. **Angebots-Snapshot (C):** In `SendOffer` beim Versand Bedingungen, Storno, Hausordnung, Vertragstexte und Zahlungsfristen in einem JSON-Feld festhalten, samt Hash. Angebotsseite, Entwurfs- **und** Final-PDF lesen aus dem Snapshot. Altbuchungen ohne Snapshot: Fallback auf Live-Content (rückwärtskompatibel).
3. **Atomare, idempotente Annahme (B1/B2):** `AcceptOffer::handle` komplett in `DB::transaction`: Property-Zeile `lockForUpdate`, Buchung frisch mit `lockForUpdate` laden, dann Version/Status/Frist/Verfügbarkeit prüfen, Nachweis schreiben **und** Status setzen. Ist die Buchung bereits mit derselben Version angenommen: **kein Fehler, keine zweite Mail**, Erfolgsseite. `ConfirmBooking` bekommt dieselbe Property-Sperre. Mails erst **nach** Commit.
4. **Nachweis (C):** `acceptance` um `offer_hash` (Hash über Quote + Snapshot **bei Versand**), `offer_sent_at`, `valid_until`, `button_label`, `checkbox_label`, `user_agent_hash`-optional ergänzen. Bei Annahme: gespeicherten `offer_hash` mit dem aktuellen vergleichen; Abweichung → Annahme abweisen („Angebot wurde geändert“) und Admin-Postfachmeldung.
5. **Fehlerisolierung (D/E):** Gast-Mails und Betreiber-Mails in `AcceptOffer` einzeln in `try/catch`; bei Fehler Eintrag in `AppSupportInbox` (ohne Empfängeradresse im Text) und Zeitstempel-Felder (`confirmation_sent_at`, `confirmation_failed_at`). Der Gast sieht immer die Erfolgsseite, falls die Buchung committed ist, mit Hinweis „Bestätigung folgt“, wenn die Mail scheiterte. Observer-Closure in `rescue()` kapseln, Fehler → Postfach.
6. **Nachversand:** Admin-Aktion „Bestätigung erneut senden“ (Buchungsseite) und Cron-Fallback `bookings:resend-confirmations`, der Bestätigungen mit gesetztem `confirmation_failed_at` erneut versucht.
7. **Gast-Fehlerseiten:** Deutsche 403/419-Seiten für den Annahmeweg mit Rücksprung auf die Angebotsseite (bündelt sich mit MVP-Gate #6).
8. **Bereinigung:** `dump()` aus `OfferWorkflowTest` entfernen.
Nicht geändert: Preisberechnung, Tenancy, Kanalarchitektur, Themes, Rechnungs-/Zahlungslogik (`RecordPayment`).
---
## 6. Notwendige Datenbankänderungen (eine additive Migration, rückwärtskompatibel)
Tabelle `bookings`:
| Spalte | Typ | Zweck |
|---|---|---|
| `offer_terms` | `json` nullable | eingefrorene Bedingungen/Texte/Zahlungsfristen der aktuellen Angebotsversion |
| `offer_hash` | `string(64)` nullable | SHA-256 über `quote` + `offer_terms` + `total` bei Versand |
| `confirmation_sent_at` | `timestamp` nullable | Gästebestätigung nachweislich versendet |
| `confirmation_failed_at` | `timestamp` nullable | Versand fehlgeschlagen → Nachversand |
Tenant/Property: Einstellung `auto_offer` (bool, Default `false`) – an der Stelle, wo `hold_hours` bereits liegt (`properties`), eine Spalte `auto_offer`.
Alle Spalten nullable bzw. mit Default; bestehende Daten werden nicht verändert; kein Backfill nötig (Fallback für `NULL`). Down-Migration entfernt die Spalten. **Produktionsdaten werden nicht berührt, solange die Migration nicht deployt wird.**
Optional (später): eigene Tabelle `booking_events` (Audit-Trail) statt JSON-Feld – für den MVP nicht nötig.
---
## 7. Tests und Akzeptanzkriterien
Alle Tests laufen in der Entwicklungsumgebung (`php artisan test`), Mail über `Mail::fake()` bzw. `MAIL_MAILER=array`; zusätzlich ein Staging-Durchlauf im **Testmodus** (Mails nur an Testadresse).
| # | Testaufgabe | Konkrete Prüfung | Akzeptanzkriterium |
|---|---|---|---|
| 1 | **Erfolgreiche Buchung inkl. aller Mails** | Anfrage über Livewire → (Auto-)Angebot → GET Angebotsseite → POST Annahme | Status `Confirmed`; genau 1× `OfferMade`, 1× `BookingConfirmed` (mit PDF-Anhang), 1× `OfferAnswered`; Kalender zeigt Nächte belegt; iCal-Feed enthält Sperre; Nachweis vollständig |
| 2 | **Abgelaufenes Angebot** | Zeit hinter `hold_expires_at` schieben (a) vor, (b) nach Cron-Lauf | GET zeigt Hinweis; POST abgelehnt mit deutscher Meldung; Zeitraum frei; Status bleibt unverändert; keine Mail |
| 3 | **Doppelte Annahme** | zweimal POST nacheinander; zusätzlich zwei gleichzeitige Requests (zwei Prozesse gegen MariaDB) | genau **eine** `BookingConfirmed`, eine `confirmed_at`; zweite Anfrage → Erfolgsseite „bereits angenommen“, kein Fehler, keine zweite Mail |
| 4 | **Parallele Buchungen derselben Zeit** | (a) zwei Anfragen gleichzeitig; (b) Annahme von Angebot A, während Angebot B (anderer Gast, abgelaufene Haltefrist) denselben Zeitraum bekam; (c) Admin-`ConfirmBooking` parallel zur Gastannahme | niemals zwei überlappende `occupying`-Buchungen; Verlierer erhält `notAvailable`-Meldung, **kein** Annahmenachweis, kein Statuswechsel |
| 5 | **Geänderte Angebotsbedingungen** | (a) `contract.terms` nach Versand ändern; (b) Admin sendet neue Version; (c) alter Link (`v=1`) | (a) Seite/Annahme/PDF zeigen weiterhin den Snapshot v1 und der Nachweis hasht v1; (b) alter Link → `offerOutdated`; (c) bei manipuliertem `quote`/`total` nach Versand wird die Annahme abgewiesen (Hash-Abweichung) |
| 6 | **Fehlgeschlagener Mailversand** | Mailer wirft Exception bei `BookingConfirmed`, `OfferMade`, `OfferAnswered` | Buchung bleibt `Confirmed`; Gast sieht Erfolgsseite mit Hinweis; `confirmation_failed_at` gesetzt; Postfach-Eintrag ohne E-Mail-Adresse; Nachversand per Admin-Aktion/Command klappt, danach `confirmation_sent_at` gesetzt. Bei `OfferMade`-Fehler: Angebot bleibt, Hinweis im Admin, Nachversand möglich |
| 7 | **Fehlgeschlagene Kalender-Synchronisierung** | `CreateChannelTasks`/Webhook wirft Exception, Kanal mit `requires_manual_blocking` | Annahme erfolgreich (kein 500); `ChannelTask` mit `automation_error` bzw. Postfachmeldung; iCal-Feed enthält die Sperre trotzdem; Erinnerungs-/Monitorlauf meldet die offene Aufgabe |
| 8 | **Gespeicherte Nachweise** | Datenbank/Dateien nach Testlauf 1 prüfen | `acceptance` enthält Version, Zeitpunkte, Gesamtbetrag, `offer_hash`, Texte-Hash, Beschriftungen; Hash stimmt mit nachgerechnetem Wert überein; Angebots-PDF (v), finales PDF und Snapshot sind identisch im Inhalt der Bedingungen; **keine IP-Adresse, kein Token** gespeichert |
| 9 | **Keine Zustandsänderung per GET** | wiederholt GET (auch mit Prefetch-User-Agent) | Status/`accepted_at` unverändert |
| 10 | **Signatur** | manipulierte Signatur, fremde Booking-ID, falsche Version | 403 bzw. `offerOutdated`; keine Datenausgabe |
| 11 | **Log-Hygiene** | Laravel-Log nach Fehlerfällen durchsuchen | keine signierten URLs, keine Tokens, keine E-Mail-Adressen/Namen |
| 12 | **Regression** | komplette bestehende Suite, `vendor/bin/pint --dirty` | grün; Verhalten mit `auto_offer = false` unverändert |
Staging-Durchlauf (nach Freigabe): einmal komplett mit echter Zustellung an die Testadresse (SPF/DKIM unauffällig), PDFs öffnen, Sperre im Portal-Feed prüfen. Bei der Parallelitätsprüfung unbedingt **MariaDB** verwenden (SQLite verhält sich bei Sperren anders).
---
## 8. Kritische rechtlich-technische Fragen (Entscheidung beim Betreiber / Rechtsberatung)
1. **Button-Wortlaut („Zahlungspflichtig buchen“):** Die Vorgabe fordert diesen Wortlaut; aktuell ist der Default „Angebot zahlungspflichtig annehmen“ (CMS-Feld `offer.accept_button`). Änderung ist reine CMS-Sache des Betreibers. Ist die Formulierung bei Vermietung (kein Verbrauchervertrag über Online-Kauf im engeren Sinn?) einschlägig und ausreichend?
2. **Widerrufsrecht:** Für Beherbergung zu bestimmten Terminen gilt regelmäßig eine Ausnahme vom Widerrufsrecht – ist das hier so einzuordnen und muss das vor Annahme angezeigt werden? Das System kann es technisch anzeigen, entscheidet es aber nicht.
3. **Vorvertragliche Informationen / AGB:** Müssen Mietbedingungen, Storno, Datenschutz und Widerrufsinformation als Link **und** als Anhang (dauerhafter Datenträger) vorliegen? Aktuell: Bedingungen auf der Seite + Vertrags-PDF in der Mail. Die Texte `contract.terms` sind noch **[MUSTER]**.
4. **Bestätigung der Zahlungspflicht vs. Kenntnisnahme:** Die aktuelle Checkbox lautet „Ich habe … gelesen“; der Button löst die Verpflichtung aus. Ist zusätzlich eine eigene Checkbox „Ich akzeptiere die Bedingungen“ gewünscht?
5. **Beweis der Annahme ohne IP-Adresse:** Es wird bewusst keine IP gespeichert (Datensparsamkeit). Reicht „Zeit + Version + Hashes + Gesamtbetrag“ als Nachweis, oder wird zusätzlich ein gekürzter IP-Hash/User-Agent gewünscht? (DSGVO-Abwägung.)
6. **Personenbezogene Daten in Logs/Fehlermeldungen:** Mailer-Exceptions können Adressen enthalten. Vorschlag: eigenes Exception-Masking im `report()`-Pfad. Aufbewahrung von Annahmenachweisen und Verträgen ist im Löschkonzept (`docs/LOESCHKONZEPT.md`) noch als offene Lücke vermerkt – Frist festlegen.
7. **Verbindliche Buchung ohne manuelle Prüfung:** Auto-Angebot und sofortige Annahme verzichten auf menschliche Prüfung (KONZEPT §6a sah „manuell, später KI-Entwurf mit Freigabe“ vor). Bewusste Entscheidung bestätigen; **Portalrisiko** (Doppelbuchung durch Verzögerung beim iCal-Abgleich, KONZEPT §7/§7a) bleibt. Vorschlag: Auto-Angebot nur für Zeiträume, die weiter als X Tage entfernt sind, und/oder Sperre der Portale mit Sofortbuchung per Aufgabe.
8. **Reservierung als Zusage?** Die Haltezeit blockiert den Kalender auch für andere Gäste und Portale (wegen `occupying()`); bei Auto-Angeboten kann Missbrauch (Blockieren fremder Termine) leichter werden – bestehende Limits (max. 2 offene Anfragen je E-Mail, Rate-Limits) greifen, ggf. E-Mail-Verifikation erwägen.
9. **Zahlungsfristen:** Anzahlung wird erst mit Annahme fällig (`deposit_due_days`). Rechtlich festlegen, was bei Nichtzahlung passiert (Rücktritt/Storno) – aktuell nur Erinnerungen (`SendBookingReminders`), keine automatische Storno.
---
## 9. Vorschlag: kleine, rückwärtskompatible Implementierung (nach Freigabe)
**Reihenfolge (jeweils eigenständig lauffähig, Standardverhalten unverändert):**
1. **Schritt 1 – Sicherheitskern (ohne Funktionsänderung für Betreiber):** Migration (nur `offer_terms`, `offer_hash`, `confirmation_*`), Snapshot in `SendOffer`, atomare/idempotente `AcceptOffer` mit Sperren, Hash-Prüfung, Fehlerisolierung für Mail und Observer. Tests 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 (+ `dump()` entfernen).
2. **Schritt 2 – Nachsende-Funktion:** Admin-Aktion „Bestätigung erneut senden“ plus Command; Postfach-Einträge. Test 6 erweitern.
3. **Schritt 3 – Auto-Angebot:** `auto_offer` je Wohnung (Default aus), `AutoOffer`-Aufruf nach `CreateReservation`; Staging einschalten, produktiv erst nach Freigabe. Test 1 + 12.
4. **Schritt 4 – Gast-Fehlerseiten** 403/419 deutsch (mit MVP-Gate #6 gemeinsam).
5. **Schritt 5 – Staging-Durchlauf** gemäß Abschnitt 7 mit Protokoll in `docs/STATUS.md`.
**Umfang grob:** 1 Migration, ~5 geänderte Dateien (`SendOffer`, `AcceptOffer`, `ConfirmBooking`, `OfferController`, `BookingObserver`), 1 neue Action, 2 Views (Angebotsseite, Fehlerseiten), 1 Command, Tests; keine neuen Abhängigkeiten, kein neuer Basisordner.
**Rollback:** `auto_offer` ausschalten stellt das bisherige Verhalten sofort wieder her; die Migration ist additiv und reversibel.
**Nicht Teil dieses Vorschlags:** Online-Zahlung, Kundenkonto, KI, Änderung von Preis-/Tenancy-/Kanalarchitektur, CMS-Inhalte (Bedingungen, Button-Text), Produktions-Deployment.
---
## 10. Freigabe
Bitte bestätigen, bevor Phase 2 beginnt:
- [ ] Umfang Schritt 1–2 (Sicherheitskern + Nachversand) in der Entwicklungsumgebung
- [ ] Schritt 3 (Auto-Angebot) ja/nein, und ob zunächst nur auf Staging
- [ ] Antworten bzw. Zuständigkeiten zu den Fragen 1–9
- [ ] Migration in Entwicklung/Staging ausführen (nicht in Produktion)
Bis dahin: **keine Änderungen an Code, Datenbank, CMS oder Servern.**
+1 -1
View File
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. The one gate is `App\Listeners\EnforceMailTestMode` (MessageSending, every mailer; no test address in test mode = nothing is sent) – never send mail around Laravel's mailer (no direct transports, `mail()`, own SMTP; `MailTestModeGateTest` checks this). Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+236
View File
@@ -0,0 +1,236 @@
# MVP-COMPLIANCE-ACCEPTANCE – Abnahmebericht
> **Stand 30.10.2026 (Abstimmung mit dem Betreiber):** Umgesetzt und zu liefern ist nur der rechtlich/sicherheitsrelevante Kern: Datenschutzlink im Buchungsformular, HTTPS-Erzwingung, deutsche Fehlerseiten, Ausnahme in `ResolveTheme` für signierte Links/Feeds. Zurückgestellt (nicht im Code, Patch nur im Scratchpad; erst nach Absprache mit Visual- und Buchungsagent): Rotator-Autoplay-Änderung, Token-Header-Härtung, WordPress-Weiterleitungen, Fokus-/Fehlerhinweis-Logik und noscript-Hinweis im Formular. Aussagen dazu weiter unten sind entsprechend als **zurückgestellt** zu lesen.
Stand: 30.10.2026 · Grundlage: `MVP-TECHNICAL-GATE.md` · Dokumentiert sind nur tatsächlich ausgeführte Arbeiten.
**Wichtig vorab:**
- Alle Codeänderungen liegen **nur lokal** im Arbeitsverzeichnis (Branch `feature/buchung-e2e`, nicht committet, nicht deployt). Dort arbeitet parallel eine zweite Sitzung am Buchungsprozess; deren Dateien wurden nicht angefasst.
- Auf `stommer.info` wurde **nichts verändert**: keine Deployments, kein Formular-Absenden, keine Datenbank-, Feed-, Token- oder Konfigurationsänderung. Es gab nur lesende Abrufe und einen Browserlauf, der Seiten öffnet, Kalendertage markiert (Livewire-Berechnung, nichts gespeichert) und nie absendet.
- Ergebnisse mit **PASS** sind ausgeführt. Was nur aus dem Code folgt oder nicht ausführbar war, steht als **UNKNOWN** bzw. **BLOCKED**.
## Zusammenfassung / Empfehlung
**Technisches Votum: NO-GO für die Umschaltung jetzt, GO-fähig nach den unten genannten Schritten.** Die Codeblocker sind behoben und getestet. Offen sind Dinge, die nur auf dem Server bzw. mit Betreiberfreigabe gehen: Deployment der Änderungen, MariaDB-Restore, Produktions-`.env`, Mailtest über das echte Formular, Ausnahme der Alias-Host-Weiterleitung für signierte Links und Feeds (siehe Risiko R1).
| ID | Thema | Ergebnis |
|---|---|---|
| B1 | HTTPS erzwingen | Code PASS (Test), Server UNKNOWN bis Deployment |
| B2 | Datenschutzlink im Formular | PASS (Test + Browser lokal) |
| B3 | Produktivkonfiguration / Mailtest | UNKNOWN / BLOCKED |
| B4 | Backup + Restore | Restore SQLite PASS, MariaDB UNKNOWN |
| P1-a | Formularfehler | PASS (Test + Browser lokal) |
| P1-b | Rotator | PASS (Code + Test der Struktur), keine Auto-Rotation mehr |
| P1-c | `<noscript>`-Hinweis | PASS (Test) |
| P1-d | Deutsche Fehlerseiten | PASS (Test + Browser lokal) |
| P1-e | Query-Token / interner Pfad | Teilweise: Token-Schalter PASS, Pfad durch B1-Lösung adressiert |
| P1-f | Browser-Cookie-Check | PASS (echter Chromium auf stommer.info) |
| P1-g | Domainwechsel-Vorbereitung | Code PASS, Umschaltung nicht durchgeführt |
---
## Neue Environment-Zuordnung (laut Ergänzung)
| Umgebung | Rolle künftig | Schutz |
|---|---|---|
| `stommer.info` (Ordner `test.fewo-stommer.de/`) | **wird Produktion** (In-place-Promotion), enthält operative Daten, Kalenderimporte, n8n-Scheduler | Nur lesender Zugriff in diesem Auftrag |
| `prod.fewo-stommer.de/` (leer angelegt) | **soll Testsystem werden** | Noch nicht eingerichtet, siehe „Testsystem-Isolation“ |
| `www.fewo-stommer.de` (WordPress) | wird abgelöst | Bis zur Freigabe unverändert |
### Zu schützende Bestände auf stommer.info (aus Code/Doku, nicht am Server gezählt)
- Datenbank `dbs16257975` (Buchungen, Gäste, Angebote, CMS-Seiten, Sites/Domains, Benutzer, Kanäle, Feed-Tokens `channels.export_token`).
- Persistente Dateien in `shared/storage/app` (Fotos/Medien öffentlich, Verträge/Backups privat) und `shared/.env`.
- Integrationen: n8n-Scheduler-Workflow (Header-Auth, jede Minute), Kalenderimport aus Portal-Feeds (5 Min.), ausgehende iCal-Feeds `/kalender/<token>.ics` für Portale, optional `/automation/portal-mail` (HMAC).
- SMTP-Versand mit Testmodus (`App\Support\Settings`) – Testmodus leitet alle Mails an Testadresse.
## Nachweis der Testsystem-Isolation – Status: **UNKNOWN**
Nicht umgesetzt, weil Zugriff auf `prod.fewo-stommer.de` und Strato-Panel zum Anlegen einer zweiten Datenbank Betreiberaktion/Freigabe benötigt. Geplante Isolation (alle Punkte sind Konfiguration, kein Code):
1. **Eigene Datenbank** (zweite Strato-MariaDB), eigener `APP_KEY`, eigene Sessions/Caches (DB-Treiber in eigener DB).
2. `APP_ENV=staging` → automatisch `noindex` (bereits implementiert) und `FEWO_MAIL_REDIRECT_TO=<Testadresse>` als **harte** Mailumleitung.
3. Keine Kanäle mit Schreibwirkung: Beim Befüllen mit synthetischen Daten **keine** Kanäle anlegen bzw. alle Kanäle auf „Import aus/Export pausiert“ lassen. Eigene Feed-Tokens entstehen automatisch neu.
4. `FEWO_AUTOMATION_WEBHOOK_URL`, `FEWO_AUTOMATION_SECRET`, `FEWO_HEALTH_TOKEN`, `FEWO_SCHEDULER_TOKEN` leer oder neu und **nicht** im produktiven n8n eingetragen. `FEWO_MAILBOX_HOST` leer (kein Postfach-Abruf).
5. Eigene Medien unter `prod.fewo-stommer.de/shared`, kein Link auf den Speicher von stommer.info.
6. Daten: synthetisch per Seeder. Kopie produktiver Daten nur nach gesonderter Freigabe und Pseudonymisierung.
7. Hinweis: `pipeline.toml` führt die Produktion derzeit gesperrt. Das Ziel `main → prod.fewo-stommer.de` wird dann praktisch zum Testziel. Umbenennung des Ziels (z. B. in `test`) ist eine Entscheidung am gemeinsam genutzten PipelineManager und wird hier **nicht** vorgenommen.
---
## Finding-Details
### B1 – HTTPS erzwingen
- **Ursprünglicher Befund:** `http://stommer.info/` lieferte `200`, keine Weiterleitung.
- **Maßnahme:** Neue Middleware `ForceHttps` (GET/HEAD → `301`, andere Methoden → `308`) als erste globale Middleware. Bewusst in der Anwendung statt `.htaccess`: Die `.htaccess` im Deploy-Ordner wird bei jedem Umschalten vom **gemeinsamen PipelineManager** (`manager/remote.sh`) bzw. `scripts/deploy.sh` neu geschrieben, eine Regel dort würde überschrieben bzw. erforderte Eingriff in geteilte Infrastruktur. Außerdem sieht die Anwendung bereits den bereinigten Pfad, daher kein interner `/releases/<id>/public`-Pfad im Ziel. Schalter `FEWO_FORCE_HTTPS` (Standard: an, außer `local`/`testing`).
- **Dateien:** `app/Http/Middleware/ForceHttps.php`, `bootstrap/app.php`, `config/fewo.php`, `.env.production.example` nicht nötig (Standard an), `docs/BETRIEB.md`.
- **Tests:** `GoLiveComplianceTest::test_plain_http_is_redirected_to_https_without_internal_paths` – **PASS** (301 mit Pfad+Query, 308 für POST, HTTPS unberührt).
- **Nicht ausgeführt:** echter `curl -I http://stommer.info/` nach Deployment → **UNKNOWN**. Offen: Redirect-Loop-Test hinter Strato (Erkennung von HTTPS über `isSecure()` funktioniert laut vorhandenem HSTS-Header bereits auf dem Server – dieselbe Erkennung).
- **Risiko:** Statische Dateien (`/build/...`, Bilder) werden vom Webserver direkt ausgeliefert und umgehen die Anwendung (kein Sicherheitsproblem, aber keine Umleitung). Strato-Option „SSL erzwingen“ zusätzlich aktivieren.
- **Betreiberaktion:** Deployment freigeben; optional Strato „SSL erzwingen“ aktivieren; Zertifikat für `fewo-stommer.de` **und** `www.fewo-stommer.de` im Paket zuordnen.
### B2 – Datenschutzlink im Formular
- **Maßnahme:** „Datenschutzerklärung“ im Einwilligungssatz ist jetzt Link auf die bestehende CMS-Route (`route('page', 'datenschutz')`), `target="_blank" rel="noopener"`, mit für Screenreader sichtbarem Zusatz „(öffnet in neuem Tab)“. Neuer Tab ⇒ Eingaben gehen nicht verloren. Redaktioneller Text unverändert.
- **Datei:** `resources/views/livewire/booking-request.blade.php`.
- **Tests:** Feature-Test (Link im gerenderten HTML) – **PASS**. Browser lokal: Link im Formular vorhanden (1), per Tab erreichbar – **PASS**.
- **Gesonderter Befund (Betreiberentscheidung, nicht geändert):** Die Pflicht-Checkbox „Ich bin einverstanden …“ formuliert technisch eine Einwilligung und erzwingt sie per `accepted`-Regel. Zur Bearbeitung einer Anfrage genügt rechtlich möglicherweise eine **Datenschutzinformation** (Art. 13 DSGVO, Rechtsgrundlage Vertragsanbahnung). Die Einordnung und ein ggf. geänderter Text liegen beim Betreiber; technisch wäre die Umstellung klein (Checkbox → Hinweis).
### B3 – Produktivkonfiguration
- **Ursprünglicher Befund:** Produktion nicht eingerichtet; Mailzustellung nicht nachgewiesen.
- **Korrigierter Stand laut Auftrag:** SMTP funktioniert bereits, Testmodus vorhanden. Keine neue Mailfunktion gebaut.
- **Maßnahme:** `.env.production.example` um `FEWO_ALLOW_QUERY_TOKEN` ergänzt. Die Soll-Konfiguration für die **In-place-Promotion** von stommer.info ist unten im Promotion-Plan als Differenz zur bestehenden `.env` aufgelistet. Es wurde **keine** `.env` gelesen oder verändert (Geheimnisse).
- **Nicht ausgeführt (BLOCKED):** Testanfrage über das Formular auf stommer.info. Sie würde eine echte Reservierung im realen Kalender anlegen und ist laut Ergänzung untersagt. Stattdessen laufen die vorhandenen Feature-Tests mit `Mail::fake()` (Bestätigungs- und Benachrichtigungsmails werden erzeugt: siehe Suite). **Mail-Trennung beachten:** Transport (funktioniert) vs. Auslöser im Workflow – bei „Anfrage → Angebot“ versendet der Betreiber das Angebot manuell; das ist Gegenstand des separaten Buchungsauftrags.
- **Empfohlener Abnahmetest nach Freigabe:** Im **Testmodus** (alle Mails an Testadresse) eine Anfrage über das Formular mit Testdaten für ein weit entferntes Datum stellen, Mails prüfen, Reservierung anschließend im Admin stornieren/löschen. Alternativ im isolierten Testsystem.
### B4 – Backup und Restore
- **Maßnahme/Test (lokal, ausgeführt):** `backup:database` gegen eine frisch migrierte und gesäte SQLite-Datenbank (42 Tabellen, 98 Zeilen), Dump per PDO in eine leere Datei zurückgespielt. Ergebnis: Tabellenliste identisch, **alle Zeilenzahlen gleich**, `migrate:status` auf der Wiederherstellung: 66 „Ran“, 0 „Pending“. – **PASS (SQLite)**.
- **Nicht ausgeführt:** Restore des **MariaDB**-Dumps aus stommer.info in eine zweite leere Datenbank. Das braucht eine zweite Strato-Datenbank (Betreiberaktion). Der MariaDB-Dumpcode (`SHOW CREATE TABLE`, Batch-Inserts, Fremdschlüssel-Schalter) ist damit **nicht durch Ausführung belegt** → **UNKNOWN**.
- **Backup-Bestand:** Täglich 02:30 per Scheduler, 14 Dateien unter `shared/storage/app/private/backups` (privat, nicht webzugänglich). Externe Kopie: `scripts/backup-pull.sh` (manuell) und Sicherung vor jedem Pipeline-Deploy auf dem Pi. **Ein Zeitplan für `backup-pull.sh` ist nicht nachgewiesen.**
- **Lücke:** `backup:database` sichert **nur die Datenbank**. Medien (`storage/app/public`) und Verträge (`storage/app/private`) werden nur über `backup-pull.sh` bzw. die Pipeline-Sicherung erfasst.
- **Betreiberaktionen:** zweite Datenbank anlegen und MariaDB-Restore ausführen (Anleitung in `docs/BETRIEB.md` §7a); Zeitplan für `backup-pull.sh` festlegen.
### P1-a – Formularfehler
- **Maßnahme:** Fehlermeldungen mit `role="alert"`, alle Felder inkl. Datenschutz-Checkbox und Datumsfelder mit `aria-invalid` + `aria-describedby`, Zusammenfassung „Bitte prüfen Sie Ihre Angaben: n Eingaben …“ als `role="alert"`; nach fehlgeschlagenem Absenden springt der Fokus in das erste fehlerhafte Feld (Livewire-Event `form-invalid`).
- **Dateien:** `resources/views/livewire/booking-request.blade.php`, `app/Livewire/BookingRequest.php`.
- **Tests:** Feature-Test – **PASS**. Browser (Chromium, lokal): nach leerem Absenden Fokus auf „Vorname“, 5 Alerts, 4 `aria-invalid` – **PASS**. Auf stommer.info (alter Stand) zuvor 0/0, also behoben durch die Änderung, **sobald deployt**.
### P1-b – Rotator
- **Maßnahme:** Einfachere Lösung gewählt: Automatischer Wechsel entfernt; Wechsel nur durch Pfeile/Punkte. Damit kein Pausenschalter nötig (WCAG 2.2.2). Reduced-Motion-Logik entfällt für den Rotator, weil keine Bewegung mehr automatisch erfolgt.
- **Datei:** `resources/themes/ostsee-licht/theme.js` (auch vom Theme `seebad` geerbt).
- **Test:** Code-Änderung; ein Browsertest war nicht möglich, weil in den Testdaten (lokal und stommer.info) **kein Rotator-Abschnitt** ausgespielt wird (`rotator_present = 0`) → **UNKNOWN (Verhalten), Code-Review PASS**.
### P1-c – Betrieb ohne JavaScript
- `<noscript>`-Hinweis mit E-Mail/Telefon aus `config('fewo.owner.*')` im Formular. Feature-Test **PASS**. Ohne-JS-Browserlauf nicht ausgeführt.
### P1-d – Fehlerseiten
- **Maßnahme:** `resources/views/errors/{403,404,419,429,500,503}.blade.php` plus gemeinsame `message.blade.php`; eigenständig (ohne Vite/Theme/Datenbank), deutsch, `lang="de"`, `noindex`, Link zur Startseite, Kontaktdaten aus Konfiguration.
- **Tests:** Feature-Test (alle sechs rendern, 404 deutsch) **PASS**; Browser lokal: Titel „Seite nicht gefunden“ **PASS**. Live-Stand (alt): englisches „Not Found“.
- **Hinweis:** Fehlerseiten gelten auch für das Admin-Panel bei 403/404/419.
### P1-e – Sicherheitsbefunde (Finding 10)
- **Tokens in URLs:** Aufrufer ermittelt: n8n-Scheduler-Workflow nutzt laut `scripts/n8n-fewo-scheduler.json` bereits **Header-Auth**. Ob ein produktiver Gesundheits-Workflow noch `?token=` nutzt, ist **UNKNOWN** (n8n liegt auf dem Pi, nicht eingesehen). Maßnahme: Schalter `FEWO_ALLOW_QUERY_TOKEN` (Standard **an**, um bestehende Automationen nicht zu unterbrechen); jede `?token=`-Nutzung wird ohne Tokenwert als Warnung geloggt. Header-Token gehen immer. Test **PASS** (an/aus/Header). Docs `DEPLOYMENT.md`/`PORTALE.md` nennen noch `?token=` in Beispielen (nicht geändert).
- **Interner Release-Pfad:** Der Redirect `/storage/app/private/backups/` → `/releases/<id>/public/…` entsteht in der `.htaccess`-Slash-Regel (`public/.htaccess`, Apache-Ebene) und im Strato-Rewrite. Er liefert `403`, legt aber die Release-ID offen. Eine sichere Korrektur an `public/.htaccess` (Slash-Regel nur für Verzeichnisse innerhalb von `public`) wurde **nicht** ausgeführt, weil sie ohne Serverprobe das Routing der gesamten Seite stören kann → **IMPROVE, offen**. Privater Zugriffsschutz bleibt wirksam (403/404 geprüft).
### P1-f – Cookie- und Browserprüfung (echter Chromium/Playwright)
Gegen `https://stommer.info` (Seiten `/`, `/wohnung`, `/kuehlungsborn`, `/kontakt`, `/impressum`, `/datenschutz`, `/buchen`; auf `/buchen` Kalendertage gewählt und Formularfeld bedient, **nicht abgesendet**). 126 Requests insgesamt.
| Prüfpunkt | Ergebnis |
|---|---|
| Cookies | genau zwei: `XSRF-TOKEN` (Secure, Lax, 120 Min.), `ferienwohnung-stommer-session` (Secure, HttpOnly, Lax, 120 Min.) |
| Local Storage / Session Storage | leer |
| Requests an Fremddomains | **0** (Schriften, Skripte, Bilder alle von stommer.info) |
| Konsolenfehler | keine |
| Karten, Tracking, Drittanbieter-Skripte | keine; OpenStreetMap nur als Link |
| Tab-Reihenfolge | Sprunglink zuerst; Footer-Link „Datenschutz“ per Tab erreichbar |
**Befund: ausschließlich unbedingt notwendige Technologien. Kein Cookie-Banner.** Rechtliche Einordnung beim Betreiber.
### P1-g – Domainwechsel-Vorbereitung
- **WordPress-URLs erfasst** (aus `wp-sitemap-posts-page-1.xml` der öffentlichen Seite): `/datenschutzerklaerung/`, `/herzlich-willkommen-im-ostseebad-kuehlungsborn/`, `/ferienwohnung/`, `/about/`, `/contact/`, `/home/`, `/impressum/`, `/intressante-links/`, `/`, `/kuehlungsborn/` sowie sieben Demo-Blogartikel (`/2020/10/18/…`).
- **Maßnahme:** 301-Weiterleitungen in `config('fewo.legacy_redirects')` (Zuordnung unten) und Route für datierte Blogartikel → Startseite. Eine eigene veröffentlichte Seite mit gleichem Slug hat Vorrang. Pfade mit Schrägstrich am Ende werden bereits von `public/.htaccess` auf die Form ohne Schrägstrich geleitet.
| Alt | Neu |
|---|---|
| `/datenschutzerklaerung` | `/datenschutz` |
| `/ferienwohnung` | `/wohnung` |
| `/herzlich-willkommen-im-ostseebad-kuehlungsborn` | `/kuehlungsborn` |
| `/intressante-links` | `/kuehlungsborn` |
| `/about`, `/contact` | `/kontakt` |
| `/home` | `/` |
| `/impressum`, `/kuehlungsborn`, `/` | unverändert |
| `/2020/…/…` (Blog) | `/` |
Die Zuordnung ist ein Vorschlag; über `/ferienwohnung` → `/wohnung` und die Sammelziele entscheidet der Betreiber. Nicht erfasst: WordPress-Medien unter `/wp-content/uploads/…`, Feeds, Kategorie-/Autorenseiten.
- **Test:** `GoLiveComplianceTest::test_former_wordpress_addresses_redirect_permanently` – **PASS**.
- **Hauptdomain:** Der Code erwartet **eine** Hauptadresse je Website (`sites.domain`), weitere Adressen leitet die parallel entwickelte Änderung in `ResolveTheme` per 301 dorthin. Empfohlene Hauptdomain: **`https://www.fewo-stommer.de`**, `fewo-stommer.de` (ohne www) als Alias.
- **Canonical/Sitemap:** nutzen `url()->current()` bzw. die Hauptadresse der Website – nach Umstellung von `sites.domain` automatisch korrekt (lokal geprüft: Canonical nutzt die erzwungene Wurzel-URL). Echter Abruf nach Umschaltung **UNKNOWN**.
- **Noindex:** Auf stommer.info solange `APP_ENV` ≠ `production`. **Achtung:** Beim In-place-Promotion `APP_ENV=production` setzen, sonst bleibt `noindex` auf der Produktivseite; umgekehrt Testsystem **nicht** auf `production`.
---
## Mobile Darstellung / Zoom
- Chromium, 320 px Breite, Live-Seite stommer.info: Layout-Viewport wird auf 380 px aufgeweitet (Seite erscheint leicht verkleinert), obwohl kein ungeclippter Inhalt breiter als 320 px ist; ein horizontales Scrollen ist nicht möglich (`overflow-x: hidden`). Lokal mit dem **aktuellen** Code (Theme `seebad`): 320 px, kein Überlauf; mit Theme `ostsee-licht`: 329 px. Das Live-Verhalten stammt vermutlich von einem älteren Stand → **nach dem nächsten Deployment erneut prüfen** (UNKNOWN). 200-%-Zoom und echte Geräte nicht geprüft.
## Tastatur / Screenreader
- Per Playwright geprüft: Sprunglink, Menüfolge, Footer-Links, Fokus auf erstes Fehlerfeld. **Nicht** geprüft: vollständige Kalender-Tastaturbedienung, NVDA/VoiceOver (UNKNOWN).
---
## Risiken für signierte Links und Kalenderfeeds (Domainwechsel)
**R1 – behoben am 30.10.2026 (Code, getestet), vor der Umschaltung am Server nachzuprüfen.** Ausnahme `staysOnRequestedAddress` in `ResolveTheme` für `angebot/*`, `bewertung/*`, `angebote/*`, `kalender/*`, `automation/*`, `health/*`; Test `GoLiveComplianceTest::test_signed_links_and_feeds_are_not_redirected_from_a_further_address`. Ursprüngliche Beschreibung:
- Laravels `signed`-Prüfung bindet die Signatur an **Schema + Host des Aufrufs** (geprüft in `UrlGenerator::hasCorrectSignature`). Bereits versendete Angebots-, Bewertungs- und Newsletter-Links zeigen auf `https://stommer.info/…`. Solange `stommer.info` die Anwendung **ohne Umleitung** ausliefert, bleiben sie gültig (der Host des Aufrufs bleibt gleich).
- Die parallel entwickelte Änderung in `ResolveTheme` (`toMainAddress`) leitet **jeden** Aufruf über eine Nebenadresse per 301 auf die Hauptadresse um. Nach der Umstellung würde `https://stommer.info/angebot/123?signature=…` auf `https://www.fewo-stommer.de/angebot/123?signature=…` geleitet – dort ist die Signatur **ungültig (403)**. Alte Angebotslinks wären tot.
- **Erforderliche Gegenmaßnahme (Entscheidung nötig, nicht von mir umgesetzt, weil die Datei in einer parallelen Arbeit steckt):** Die Alias-Weiterleitung muss `angebot/*`, `bewertung/*`, `angebote/*`, `kalender/*` und `automation/*` ausnehmen (diese Pfade weiter unter `stommer.info` ausliefern), **oder** `stommer.info` bleibt dauerhaft als zweite Adresse ohne Weiterleitung für diese Pfade erreichbar. Ablaufdatum der Angebotslinks prüfen: danach kann die Ausnahme entfallen.
- Neue Links entstehen nach der Umstellung automatisch mit der neuen Hauptadresse (`sites.domain`/`APP_URL`).
**R2 – Kalenderfeeds.** Portale rufen `https://stommer.info/kalender/<token>.ics` ab. Die Tokens sind im Pfad und unabhängig vom Host; mit der Ausnahme aus R1 laufen die Feeds weiter. Ohne Ausnahme folgen viele iCal-Clients einer 301, manche nicht → Portal-Kalender würden still veralten. Vorgehen: Feed-URLs bei den Portalen **nicht sofort**, sondern geplant auf die neue Domain umstellen; vorher `/health/sync` und Importzeit (`last_success_at`) im Blick behalten. Ob ein Portal die Kalender-URL manuell umgestellt bekommen muss, ist je Portal **UNKNOWN**; sicher ist die Ausnahme-Variante (alte URL funktioniert weiter).
**R3 – Sessions/Cookies.** Cookie-Domain wird nicht gesetzt (host-only). Nach dem Wechsel gelten neue Sitzungen; Administratoren müssen sich auf der neuen Domain neu anmelden (2FA bleibt). Offene Reservierungsformulare gehen beim Wechsel verloren.
**R4 – Automationen.** n8n ruft `https://stommer.info/automation/scheduler` auf. Mit der Ausnahme in R1 weiter gültig; sonst muss die Workflow-URL umgestellt werden (Aufruf kontrolliert, Header-Auth bleibt). Auch `FEWO_AUTOMATION_WEBHOOK_URL` zeigt in die Gegenrichtung (App → n8n) und ist vom Wechsel unberührt.
**R5 – Konfigurationscache.** `APP_URL` und `sites.domain` ändern; danach `php artisan optimize` (Konfigurations- und Routen-Cache), sonst gilt die alte URL (`docs/BETRIEB.md` §5).
---
## In-place-Promotion von stommer.info → www.fewo-stommer.de (Plan, nicht ausgeführt)
**Vorbedingungen (alle vor der Umschaltung):**
1. Betreiberfreigabe; Zeitfenster mit geringem Buchungsgeschehen.
2. Entscheidung zu R1 (Ausnahmepfade) umgesetzt, getestet, im Testsystem geprüft.
3. Änderungen dieses Auftrags **und** des Buchungsauftrags zusammen getestet; Deployment per Pipeline (develop → Test-Deploy). Vollständige Suite grün.
4. MariaDB-Restore-Test erfolgreich (B4), externe Kopie frisch (`backup-pull.sh staging <ziel>`), enthält DB, Fotos, Verträge.
5. Kopie von `shared/.env` an geschütztem Ort (Vaultwarden), nicht im Chat.
6. Zertifikate für `fewo-stommer.de` und `www.fewo-stommer.de` in Strato verfügbar.
7. Liste der Portal-Kalender mit Feed-URLs und Zuständigkeiten (wer stellt um) vorliegend.
**Ablauf (Schritt für Schritt, jeweils freigeben):**
1. Deployment des geprüften Stands auf die bestehende Installation (nur Code; **keine** neuen Migrationen ohne Freigabe – die parallelen Buchungsmigrationen sind **additiv**, aber gesondert zu beurteilen). Danach Smoke-Test auf stommer.info (Startseite, `/buchen`, Admin-Login, `/health/sync` mit Header).
2. `shared/.env` anpassen: `APP_ENV=production`, `APP_DEBUG=false`, `APP_URL=https://www.fewo-stommer.de`, `SESSION_SECURE_COOKIE=true`, `LOG_LEVEL=warning`, SMTP unverändert, Testmodus erst nach Freigabe auf „live“.
3. In Strato: `www.fewo-stommer.de` und `fewo-stommer.de` dem Deploy-Ordner `test.fewo-stommer.de/` zuordnen (zusätzlich zu `stommer.info`). Altes WordPress-Ziel dabei bewusst ablösen (vorher WordPress-Sicherung durch Betreiber).
4. Im Admin die Hauptadresse der Website auf `www.fewo-stommer.de` setzen (Datenänderung an `sites.domain` – freigabepflichtig), `stommer.info` bleibt als weitere Adresse.
5. `bash scripts/deploy.sh <env> artisan optimize` (bzw. Pipeline), danach prüfen: Startseite, `curl -I http://www.fewo-stommer.de/` → 301 HTTPS, Canonical, `/sitemap.xml`, `robots.txt` (Produktion: indexierbar), Altadressen-Weiterleitungen, ein alter signierter Angebotslink unter `stommer.info`, ein Feed unter `stommer.info/kalender/…`.
6. n8n-Scheduler: Lauf in den nächsten 5 Minuten prüfen (`channels:sync`, `last_success_at`).
7. Search Console für die neue Domain einrichten (Betreiber).
8. Portal-Kalender-URLs nach Vereinbarung stufenweise umstellen; `stommer.info` als Alias dauerhaft belassen, bis alle Angebotslinks abgelaufen und alle Portale umgestellt sind.
## Rollback
- **Domain:** Zuordnung von `www.fewo-stommer.de` in Strato wieder auf das alte WordPress-Ziel zurücksetzen. Die neue Anwendung bleibt unter `stommer.info` erreichbar; Daten wurden nicht umgezogen, es gibt also **keine Datenrückspielung**.
- **Anwendung:** `bash scripts/deploy.sh <env> rollback` bzw. Pipeline-Rückfall (Git-Tag `deploy/<env>/<ts>`); `sites.domain` zurück auf `stommer.info`; `APP_URL` zurück, `optimize`.
- **Abhängigkeiten außer der Domain:** (a) nach Wechsel versendete Links zeigen auf die neue Domain und sind nach Rollback tot, daher Mails im Zeitfenster minimieren; (b) bereits umgestellte Portal-Feeds müssen zurückgestellt werden; (c) Suchmaschinen können kurzzeitig neue Adressen kennen. Eine reine Domain-Rückstellung genügt nur, solange kein Portal umgestellt und keine Mail mit neuer Domain versendet wurde.
---
## Ausgeführte Tests
| Test | Ergebnis |
|---|---|
| `GoLiveComplianceTest` (6 Tests, 38 Assertions): HTTPS-Redirect, Datenschutzlink + `noscript`, Formularfehler/ARIA, Fehlerseiten, WordPress-Weiterleitungen, Query-Token | **PASS** |
| Bestehende Tests `BookingRequestPageTest`, `SchedulerEndpointTest` nach Änderung | **PASS** |
| Browser-Cookie-/Netzwerkprüfung stommer.info (Playwright/Chromium) | **PASS** |
| Browser lokal: Fehlerfokus, ARIA, Datenschutzlink, deutsche 404 | **PASS** |
| Restore-Test SQLite (lokal) | **PASS** |
| Vollständige Feature-Suite (561 Tests, 556 bestanden) | **FAIL (nicht durch diese Änderungen)**, Details unten |
| `vendor/bin/pint --dirty` | **PASS** |
| HTTP→HTTPS am echten Server, Mailtest, MariaDB-Restore, Handtest NVDA/Zoom/Geräte, Rotator im Browser | **UNKNOWN / BLOCKED** |
## Ergebnis der vollständigen Feature-Suite (30.10.2026)
561 Tests, 556 bestanden, 3 Fehlschläge, 2 Fehler. Gleichzeitig arbeitet eine zweite Sitzung im selben Arbeitsverzeichnis, daher ist die Suite nicht sauber isolierbar.
- `TenantFilesTest` und `WebsiteContentTest` (3 Tests): in einer Wiederholung einzeln **PASS** (13/13). Ursache vermutlich ein zeitgleicher Testlauf der anderen Sitzung auf demselben temporären Testspeicher.
- `SeasonManagementTest::test_admin_pages_render`: Klasse `OfferMode` fehlt in `PropertyForm.php` – unfertige Änderung der Buchungsarbeit, **nicht von diesem Auftrag**.
- `WebsiteTenancyTest::test_a_website_answers_on_every_address_entered_for_it`: erwartet 200, erhält 301 – direkte Folge der neuen Alias-Host-Weiterleitung in `ResolveTheme` (ebenfalls die parallele Arbeit; Test dort ebenfalls in Bearbeitung). Betrifft das Risiko R1.
- Die in diesem Auftrag geänderten Bereiche (Buchungsformular, Planungsseiten, Scheduler-Endpunkt, Weiterleitungen) sind grün. **Eine fehlerfreie Gesamtsuite steht noch aus (Nachtrag: am 30.10.2026 später 561/561 bestanden, mit den Änderungen aller drei Agenten)** und ist nach Abschluss der parallelen Arbeit erneut auszuführen.
## Noch erforderliche Betreiberaktionen
1. Freigabe für Deployment der Änderungen auf die bestehende Installation.
2. Entscheidung zur Alias-Weiterleitung (R1) und Hauptdomain `www.fewo-stommer.de`.
3. Zweite Strato-Datenbank für Restore-Test und Testsystem anlegen.
4. Einwilligung vs. Datenschutzinformation am Formular juristisch klären.
5. Bestätigung der Weiterleitungszuordnung (WordPress-Seiten).
6. Zeitplan für `backup-pull.sh`; WordPress-Sicherung vor der Ablösung.
7. Zuständigkeiten für Portal-Kalender-URLs.
8. Strato „SSL erzwingen“ aktivieren (optional, zusätzlich).
## Abschließende Empfehlung
**NO-GO für eine sofortige Umschaltung; GO-fähig**, sobald (1) die Änderungen deployt und auf stommer.info nachgeprüft sind, (2) R1 gelöst ist, (3) der MariaDB-Restore bestanden ist und (4) die Produktions-`.env` laut Plan gesetzt ist. Es sind keine weiteren Architekturänderungen nötig.
+215
View File
@@ -0,0 +1,215 @@
# MVP-TECHNICAL-GATE – Phase 1 (Read-only-Prüfung) und Umsetzungsstand
> **Umsetzungsstand 30.10.2026 (Details und Nachweise: [MVP-COMPLIANCE-ACCEPTANCE.md](MVP-COMPLIANCE-ACCEPTANCE.md)).** Die Codeänderungen liegen lokal, nichts ist deployt, auf stommer.info wurde nichts verändert. Die Installation auf stommer.info gilt künftig als Produktion (In-place-Promotion).
>
> | # | Stufe | Stand |
> |---|---|---|
> | 1 | BLOCKER HTTPS | Code umgesetzt (`ForceHttps`) und getestet; Wirkung am Server nach Deployment prüfen |
> | 2 | BLOCKER Datenschutzlink | umgesetzt, getestet (Test + Browser lokal) |
> | 3 | BLOCKER Produktivkonfiguration/Mail | Plan erstellt; Mailtest am echten Formular wegen Produktivdaten **nicht ausgeführt** |
> | 4 | BLOCKER Restore | SQLite-Restore bestanden; **MariaDB-Restore offen** (zweite Datenbank nötig) |
> | 5 | IMPROVE WordPress-Weiterleitungen | umgesetzt (301-Tabelle), Zuordnung vom Betreiber zu bestätigen |
> | 6 | IMPROVE Fehlerseiten | umgesetzt, getestet |
> | 7 | IMPROVE Formularfehler | umgesetzt, getestet (Fokus, ARIA) |
> | 8 | IMPROVE Rotator | Auto-Wechsel entfernt |
> | 9 | IMPROVE ohne JavaScript | `<noscript>`-Hinweis umgesetzt |
> | 10 | IMPROVE Token/Release-Pfad | Token-Schalter umgesetzt; Release-Pfad in `.htaccess` offen |
>
> **Neu entdeckt:** (a) Alias-Host-Weiterleitung der parallelen Arbeit würde nach dem Domainwechsel alte signierte Angebotslinks und ggf. Feeds ungültig machen (R1). (b) Auf stommer.info (aktueller Stand) wird das Layout bei 320 px auf 380 px aufgeweitet (lokal mit aktuellem Code nicht reproduzierbar). (c) Browser-Cookiecheck bestätigt: nur zwei notwendige Cookies, kein Storage, keine Drittanfragen.
> **Empfehlung weiterhin NO-GO bis Deployment, MariaDB-Restore, R1 und Produktions-`.env`.**
>
> *Der folgende Text ist der unveränderte Phase-1-Bericht.*
Stand: 30.10.2026 · Geprüft: Quellcode (Branch `feature/erinnerungen-zusammenfassung`) und der Testauftritt **https://stommer.info** (Staging, per HTTP-Abruf).
Status: **Phase 1 abgeschlossen. Es wurden keine Code-, CMS-, Datenbank- oder Serveränderungen vorgenommen.** Phase 2 beginnt erst nach ausdrücklicher Freigabe des Betreibers.
**Grenzen der Prüfung (ehrlich vorab):**
- Der Testauftritt wurde mit HTTP-Abrufen und Quellcode-Analyse geprüft, **nicht** in einem interaktiven Browser mit DevTools. Cookies, Header und eingebundene Ressourcen sind aus den Antworten belegt. Echte Browser-Laufzeitprüfungen (Local/Session Storage, Tastatur-Durchlauf, Screenreader, Zoom) stehen deshalb als UNKNOWN oder IMPROVE da.
- Produktion (`prod.fewo-stommer.de`) ist laut `docs/BETRIEB.md` **noch nicht eingerichtet** (keine `.env`, keine Datenbank). Produktionswerte sind Soll-Werte aus `.env.production.example`, nicht verifiziert.
- Rechtstexte und CMS-Inhalte wurden **nicht inhaltlich** geprüft. Nur Erreichbarkeit und sichere Ausgabe.
## Gesamtbild
| Bereich | Ergebnis |
|---|---|
| Cookies / externe Dienste | Nur unbedingt notwendige Cookies, keine Drittanbieter → **kein Banner empfohlen** (Details A) |
| Barrierefreiheit | Gute Grundlage, einige kleine Verbesserungen, ein Formular-Link fehlt (B) |
| Security | Solide (2FA, Rate-Limits, Tokens, Sperren). Offen: HTTP→HTTPS, Restore-Nachweis, Produktivkonfiguration (C) |
| Domainwechsel | Noindex/Canonical technisch richtig; Weiterleitungen und Mailversand noch nicht verifiziert (E) |
**Vorläufige Empfehlung: NO-GO**, bis die 4 BLOCKER (1–4) behoben und abgenommen sind. Kein BLOCKER erfordert einen Architekturumbau. Zwei sind Konfiguration oder Nachweis ohne Codeänderung.
---
## Priorisierte Maßnahmen (max. 10)
| # | Stufe | Maßnahme | Art |
|---|---|---|---|
| 1 | BLOCKER | HTTP wird nicht auf HTTPS umgeleitet | Server-Konfiguration |
| 2 | BLOCKER | Datenschutzhinweis am Anfrageformular ist kein Link | Code (1 Zeile) |
| 3 | BLOCKER | Produktivumgebung nicht eingerichtet und Mailversand nie echt getestet | Konfiguration + Abnahmetest |
| 4 | BLOCKER | Backup-Restore nie nachgewiesen | Nachweis, kein Code |
| 5 | IMPROVE | Weiterleitung der alten WordPress-URLs beim Domainwechsel | Konfiguration |
| 6 | IMPROVE | Fehlerseiten sind englische Laravel-Standardseiten | Code (klein) |
| 7 | IMPROVE | Fehlermeldungen im Anfrageformular nicht barrierefrei verknüpft | Code (klein) |
| 8 | IMPROVE | Auto-Rotator ohne Pausenschalter (WCAG 2.2.2) | Code (klein) |
| 9 | IMPROVE | Formular ohne JavaScript nicht nutzbar, kein Hinweis | Code (klein) |
| 10 | IMPROVE | Token auch per URL-Parameter akzeptiert; interner Release-Pfad in Redirect sichtbar | Code (klein) |
---
## BLOCKER (Detail)
### 1. BLOCKER – Keine Weiterleitung von HTTP auf HTTPS
- **Problem:** `http://stommer.info/` antwortet mit `200 OK` statt mit einer Weiterleitung. Gäste, die per HTTP einsteigen, erreichen das Formular unverschlüsselt. Session- und XSRF-Cookies sind `secure`, werden über HTTP also nicht angenommen. Das Formular liefe dort in Fehler (419), und Anfragedaten könnten unverschlüsselt übertragen werden. HSTS wird nur über HTTPS ausgeliefert und hilft beim Erstbesuch nicht.
- **Komponente:** Server-/Domain-Konfiguration bei Strato, bzw. die vom Deploy-Skript geschriebene `.htaccess` im Deploy-Ordner (`scripts/deploy.sh`, `docs/BETRIEB.md` §2). `public/.htaccess` enthält keine Umleitung.
- **Minimale Korrektur:** Bei Strato „HTTPS erzwingen“ für die Domain aktivieren, oder in der Deploy-`.htaccess` `RewriteCond %{HTTPS} !=on` → `RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]` (Strato-Besonderheit: ggf. `%{HTTP:X-Forwarded-Proto}` prüfen).
- **Abnahme:** `curl -sI http://<domain>/` und `curl -sI http://<domain>/buchen` liefern `301` mit `Location: https://…`. Gilt für `fewo-stommer.de` **und** `www.fewo-stommer.de`.
### 2. BLOCKER – Datenschutzhinweis am Anfrageformular ist nicht verlinkt
- **Problem:** Im Einwilligungstext steht „(siehe Datenschutzerklärung)“ als reiner Text. Der Link erreicht die Seite nur über den Footer. Die Informationspflicht (Art. 13 DSGVO) verlangt, dass der Hinweis bei der Erhebung leicht auffindbar ist. Das ist technisch ohne Link nicht gegeben, und für Screenreader ist der Footer weit entfernt.
- **Komponente:** `resources/views/livewire/booking-request.blade.php` (Checkbox `privacyAccepted`).
- **Minimale Korrektur:** „Datenschutzerklärung“ als `<a href="{{ route('page', 'datenschutz') }}" target="_blank" rel="noopener">` setzen (Hinweis „öffnet in neuem Tab“ für Screenreader). Der Text der Einwilligung selbst bleibt unverändert. Das ist reine UI-Technik, keine inhaltliche Änderung.
- **Abnahme:** Feature-Test: gerenderte `/buchen`-Seite enthält einen Link auf `/datenschutz` innerhalb des Formulars. Manuell: Tab-Reihenfolge erreicht den Link, Seite lädt, Rückkehr zum Formular behält Eingaben.
### 3. BLOCKER – Produktivumgebung nicht eingerichtet; Mailzustellung nie echt getestet
- **Problem:** Laut `docs/BETRIEB.md` fehlen für Produktion `.env`, Datenbank und Domainzuordnung. Auf Staging gilt `MAIL_MAILER=log`, es wurde also nie eine echte E-Mail zugestellt. Ohne funktionierende Mails (Eingangsbestätigung an Gäste, Benachrichtigung an die Betreiber) ist das Anfrageformular nicht betriebsfähig. Produktions-Härtung (Debug, Logging, Cookies) ist nur als Vorlage belegt.
- **Komponente:** `shared/.env` auf dem Server (Vorlage `.env.production.example`), `App\Support\Settings` (Testmodus/Live), `pipeline.toml` (Produktion gesperrt).
- **Minimale Korrektur (nur Konfiguration, kein Code):** Produktions-`.env` mit `APP_ENV=production`, `APP_DEBUG=false`, `APP_URL=https://www.fewo-stommer.de`, `LOG_CHANNEL=daily`, `LOG_LEVEL=warning`, `SESSION_SECURE_COOKIE=true`, `MAIL_MAILER=smtp`, eigene Datenbank, lange zufällige `FEWO_HEALTH_TOKEN`, `FEWO_SCHEDULER_TOKEN`, `FEWO_AUTOMATION_SECRET`. Admin-Konten mit `users:create`, 2FA einrichten. Mail zunächst im Testmodus (Empfänger = Betreiber), erst danach „Live“.
- **Abnahme:**
1. `php artisan config:show app.debug` → `false`, `app.env` → `production`.
2. Test-Anfrage über das Formular → Gäste-Bestätigung **und** Betreiber-Benachrichtigung kommen real an (Testadresse), SPF/DKIM-Header unauffällig (nicht als Spam).
3. Ein erzeugter Fehler (z. B. `/nichtda`) zeigt keinen Stacktrace.
4. `<meta name="robots" content="noindex">` ist auf Produktion **nicht** mehr vorhanden, `robots.txt` enthält die Produktions-Sitemap.
5. Scheduler läuft (n8n oder Cron): `channels:sync` und `backup:database` erscheinen im Log.
### 4. BLOCKER – Backup-Restore nicht nachgewiesen
- **Problem:** `backup:database` läuft täglich und behält 14 Dateien. Ein Wiederherstellungstest ist in `docs/BETRIEB.md` und `docs/LOESCHKONZEPT.md` nirgends belegt („❓ nicht belegt“). Die Sicherung liegt auf demselben Webspace; die Kopie außerhalb (`scripts/backup-pull.sh`, Pipeline-Sicherung auf dem Pi) ist manuell bzw. an Deployments gekoppelt. Der Dump überspringt bewusst `sessions`, `cache`, `jobs`.
- **Komponente:** `app/Console/Commands/BackupDatabase.php`, `scripts/backup-pull.sh`, `docs/BETRIEB.md` §7a.
- **Minimale Korrektur:** Kein Code. Einmaliger Restore-Test: aktuellen Dump auf eine **leere Test-Datenbank** einspielen (nicht in Produktion), Ergebnis mit Datum in `docs/BETRIEB.md` festhalten. Außerdem festlegen, wie oft `backup-pull.sh` läuft (mind. wöchentlich) und wo die Kopie liegt.
- **Abnahme:** Nach dem Einspielen `php artisan migrate:status` ohne Fehler, Zeilenzahlen von `bookings`, `guests`, `pages` stimmen mit dem Original überein, Admin-Login mit der wiederhergestellten Datenbank funktioniert. Wichtig: Dump enthält Gästedaten, daher nur verschlüsselt/zugriffsgeschützt ablegen.
---
## A. Cookies und externe Dienste
**Methode:** Antwort-Header und gerenderte HTML-/CSS-Dateien der Startseite, `/buchen`, `/impressum`, `/datenschutz`, `/admin/login`; Suche im Quellcode nach `localStorage`, `sessionStorage`, `document.cookie`, Analytics, Karten-Einbettungen, `iframe`.
**Nicht erfolgt:** Beobachtung im Browser-Netzwerk-Tab.
| Technologie | Zweck | Anbieter | Speicherdauer | Technisch erforderlich? | Einwilligung? |
|---|---|---|---|---|---|
| `ferienwohnung-stommer-session` (Cookie, HttpOnly, Secure, SameSite=Lax) | Sitzung des Buchungsformulars (Livewire), Spam-Zeitsperre | Eigene Domain | 120 Min. (`Max-Age=7200`) | Ja, Formularbetrieb | Nein, wenn nur dafür genutzt (Einordnung durch Betreiber) |
| `XSRF-TOKEN` (Cookie, Secure, SameSite=Lax) | CSRF-Schutz des Formulars | Eigene Domain | 120 Min. | Ja | Nein |
| Livewire-Skript, Theme-JS/CSS | Funktion der Seite | Eigene Domain (`/build`, `/livewire-…`) | – | Ja | Nein |
| Schriften (Atkinson Hyperlegible, Cormorant Garamond) | Darstellung | **Selbst gehostet** (`/build/assets/*.woff2`) | – | – | Nein, keine Verbindung zu Drittanbietern |
| Bilder (`/storage/…`) | Inhalt | Eigene Domain | – | – | Nein |
| OpenStreetMap | Nur ein **Link** („Karte öffnen“), keine Einbettung | OSM Foundation | – | – | Nein, Verbindung erst nach Klick des Gastes |
| Local/Session Storage | Im Quellcode der Webseite **nicht verwendet** (keine Treffer). Nur Filament-Admin nutzt Browser-Speicher intern. | – | – | – | Nein |
| Tracking, Analytics, Werbung, Social-Widgets, Maps-iframes, Captcha | **Keine gefunden** (Bot-Schutz läuft ohne externen Dienst) | – | – | – | – |
- **PASS – Keine Drittanbieter-Verbindungen** im ausgelieferten HTML/CSS von Start- und Buchungsseite. Das einzige fremde Ziel ist der OSM-Link.
- **PASS – Kein STRATO-spezifischer Skript-/Cookie-Zusatz** im HTML (keine Fremdskripte, keine Zusatz-Cookies). Der Server sendet nur die zwei Laravel-Cookies.
- **Empfehlung: Kein Cookie-Banner.** Es werden ausschließlich notwendige Technologien eingesetzt. Hinweis für den Betreiber: Die Cookies werden schon beim ersten Seitenaufruf gesetzt (auch ohne Formular), weil Laravel die Sitzung global startet. Die rechtliche Einordnung („unbedingt erforderlich“) und die Erwähnung in der Datenschutzerklärung liegen beim Betreiber. Technisch ließe sich das später auf `/buchen` beschränken (kein MVP-Thema).
- **UNKNOWN:** Browser-Gegenprobe (DevTools › Application/Network) auf Staging; zusätzlich das Cookie-Verhalten, sobald Produktions-Domain und Strato-Einstellungen live sind. 5-Minuten-Check vor Go-live.
---
## B. Technische Barrierefreiheit (WCAG 2.2 als Qualitätsmaßstab)
**Rechtliche Einordnung (Betreiber):** Ob die Kleinstunternehmensausnahme nach § 3 Abs. 3 BFSG greift, entscheidet der Betreiber. Unabhängig davon ist die Grundlage technisch gut. Hier nur technische Empfehlungen, keine gesetzliche Anforderung bestätigt.
**PASS (aus Quellcode und HTML belegt):**
- Sprunglink „Zum Inhalt springen“, `lang="de"`, Landmarks (`header`, `nav` mit `aria-label`, `main#inhalt`, `footer`).
- Sichtbarer Fokus global: `:focus-visible { outline: 2px solid var(--accent) }` (`theme-base.css`).
- Viewport ohne Zoomsperre (`width=device-width, initial-scale=1`), keine `maximum-scale`/`user-scalable`.
- Alle Formularfelder haben sichtbare `<label>`, Pflichtfelder `required`, `autocomplete`-Attribute (WCAG 1.3.5).
- Kalender: echte Tabelle mit `<th scope="col">`, jeder Tag ein `<button>` mit vollständigem Datum und „(Nacht belegt)“ im `aria-label`, `aria-pressed`. Belegt ist nicht nur Farbe (durchgestrichen + Text).
- Vergangene Tage `disabled`; Preisbereich `aria-live="polite"`; Erfolgsmeldung `role="status"`.
- Lightbox als natives `<dialog>` (Escape, Fokusrückgabe nativ); Buttons mit `aria-label`.
- `prefers-reduced-motion` wird berücksichtigt (CSS und Rotator).
- Dekorative Grafiken (Wellen-Trenner) `aria-hidden`. Mobile Menü ohne JavaScript über `<details>`.
- Standard-Token-Kontraste rechnerisch ausreichend (z. B. Text `#4E5C66` auf `#F6F2EA` ≈ 6:1, Akzent `#2C5F7C` auf Weiß ≈ 7:1).
**IMPROVE (nicht Go-live-kritisch, kleine Änderungen):**
- **#7 Formularfehler:** Fehlermeldungen der Textfelder sind per `aria-describedby` verknüpft, aber nicht als `role="alert"`; Fehler der Einwilligungs-Checkbox (`privacyAccepted`) haben weder `aria-invalid` noch Verknüpfung; kein Sprung zum ersten Fehler (das Formular nutzt `novalidate`). Folge: Screenreader-Nutzer bemerken ein abgelehntes Absenden nicht (WCAG 3.3.1, 4.1.3). Korrektur: `role="alert"` bzw. Fokus auf erstes Fehlerfeld, Checkbox mit `aria-describedby`.
- **#8 Auto-Rotator** (Sonderangebote, wechselt alle 7 s): pausiert bei Hover/Fokus, hat aber keinen sichtbaren Pausenschalter (WCAG 2.2.2, > 5 s). Korrektur: Pause-Button oder Auto-Wechsel nur ohne Interaktion deaktivieren. Alternativ komplett ohne Auto-Wechsel.
- **Mehrere `<h1>`** auf den Rechtstexten: Die Seite rendert die Überschrift des Abschnitts als `<h1>` und die im CMS-Text enthaltene Überschrift ebenfalls. Das ist eine Inhaltsfrage (CMS-Text), kein Fehler der Vorlage. Hinweis an Betreiber: Überschriften im Text als H2/H3 anlegen.
- **UNKNOWN:** Tastatur-Durchlauf von Menü, Kalender (Pfeiltasten nicht implementiert, Tab durch alle Tage = ca. 60 Stopps), Zoom 200 %/Reflow 320 px, Screenreader-Test (NVDA/VoiceOver), Kontraste der **Saison-Erscheinungsbilder** (z. B. `herbst` überschreibt Farb-Token), `Kalender-Target-Size` (WCAG 2.5.8). Empfohlen: 30-Minuten-Handtest mit Tastatur und NVDA vor Go-live.
---
## C. Security und Datenschutztechnik
| Prüfpunkt | Stufe | Befund |
|---|---|---|
| HTTPS / HSTS | **BLOCKER** (#1) | HTTPS aktiv, HSTS `max-age=31536000` gesetzt, aber keine HTTP→HTTPS-Weiterleitung |
| Sicherheits-Header | PASS | `X-Content-Type-Options`, `X-Frame-Options: SAMEORIGIN`, `Referrer-Policy`, `Permissions-Policy` (`SecurityHeaders`). Kein CSP (bewusst, Livewire/Filament inline; `IMPROVE`, nicht MVP) |
| Debug-Modus (Produktion) | **UNKNOWN** (#3) | Vorlage `APP_DEBUG=false`. Staging liefert auf `/nichtda` nur die Standard-404, keine Debug-Seite. Produktion nicht verifizierbar |
| Logging | PASS (Vorlage) | `LOG_CHANNEL=daily`, `LOG_LEVEL=warning`, 14 Tage. Nicht live verifiziert |
| Session / Cookies | PASS | `HttpOnly`, `Secure`, `SameSite=Lax`, DB-Sessions, 120 Min. |
| CSRF | PASS | Laravel `PreventRequestForgery` aktiv. Ausnahmen nur für `/automation/portal-mail` und `/automation/aufgaben/…`, beide mit HMAC-Signatur (`hash_equals`, leeres Secret → 403) |
| Admin-Zugang | PASS | `/admin/login` erreichbar (erwartet); 2FA (TOTP) mit Wiederherstellungscodes für jedes Konto verpflichtend; Konten nur über `users:create`; Rollen/Policies |
| Vertrauliche Dateien | PASS | `/.env` → 403, `/composer.json` → 404, `/releases/` → 403, `/storage/app/private/…` nicht erreichbar, nur `storage/app/public` ist verlinkt. Backups und Verträge liegen privat |
| Technische Tokens | PASS | Health (`/health/sync`), Scheduler und Portal-Mail: ohne Token 404/403; Vergleich mit `hash_equals`; leere Konfig = gesperrt; Rate-Limit 10–60/min. Hinweis: `?token=` wird übergangsweise noch akzeptiert → IMPROVE #10. iCal-Feeds nur mit zufälligem `export_token`, Token-Rotation vorhanden |
| Eingabevalidierung / Spam | PASS | Serverseitige Regeln, Honeypot, Zeitsperre 4 s, 5/Std je IP, 3/Tag je E-Mail, 30/Std gesamt, max. 2 offene Anfragen je E-Mail, Link-Limit; signierte URLs (`signed`) + Throttle für Angebot, Bewertung, Newsletter |
| Ausgabe von CMS-Inhalten | PASS | Texte werden mit `{{ }}` escaped; Rich-Text läuft über Filament `RichContentRenderer` (bereinigt). Die wenigen `{!! !!}`-Stellen geben Theme-eigene Motive, `json_encode` mit `JSON_HEX_TAG` oder escaped Titel aus |
| Datenlöschung bei erfolglosen Anfragen | PASS (technisch) | `guests:anonymize` täglich 03:00: nie bestätigte Anfragen nach 6 Monaten (`FEWO_RETENTION_INQUIRY_MONTHS`) anonymisiert, Portal-Mailauszüge 90 Tage, UTM 24 Monate. Frist **rechtlich** bestätigen lässt der Betreiber (`docs/LOESCHKONZEPT.md`). Offene Lücken laut Löschkonzept (Bewertungen, Vertragsdokumente, `internal_notes`) sind nicht Teil des MVP-Pfads → IMPROVE |
| Backup | **BLOCKER** (#4) | Erstellung vorhanden, Restore nicht nachgewiesen |
| Gästedaten in Versandwegen | PASS | Testmodus-Schalter leitet alle Mails an Testadresse; `FEWO_MAIL_REDIRECT_TO` als harte Sperre |
| Produktivkonfiguration | **BLOCKER** (#3) | Nicht eingerichtet |
---
## D. CMS und technische Informationspflichten
| Prüfpunkt | Stufe | Befund |
|---|---|---|
| Impressum und Datenschutz erreichbar | PASS | `/impressum` und `/datenschutz` liefern `200`, mit `<h1>` und Titel (Inhalt nicht bewertet) |
| Links auf jeder öffentlichen Seite | PASS | Footer-Navigation `aria-label="Rechtliches"` ist Teil des gemeinsamen Layouts; gerendert aus dem Menü „footer“. Hinweis: Wird das Menü im CMS geleert, verschwinden die Links. Betreiber-Hinweis, kein Code-Befund |
| Mobil | PASS (Code) / UNKNOWN (Gerät) | Footer-Links sind nicht ausgeblendet; die mobile feste Buchungsleiste (`z-30`) verdeckt keine Footer-Links dank 5-rem-Abstandhalter. Echtgerätetest offen |
| Datenschutzhinweis am Formular | **BLOCKER** (#2) | Nur Text, kein Link |
| Ohne JavaScript | IMPROVE (#9) | Seiten, Navigation, Legal-Links, Kontaktdaten (`mailto:`/`tel:`) funktionieren ohne JS. Das **Anfrageformular und der Kalender sind vollständig Livewire** und ohne JS nicht nutzbar, es gibt keinen `<noscript>`-Hinweis. Praktikable Korrektur: `<noscript>` mit Telefon/E-Mail der Betreiber. Eine Neuimplementierung als klassisches Formular ist für den MVP nicht angemessen |
| Sichere Ausgabe | PASS | siehe C |
---
## E. Funktionsfähigkeit und Domainwechsel
| Prüfpunkt | Stufe | Befund |
|---|---|---|
| Anfrageformular (Logik) | PASS (Code/Tests) | Validierung, Preisberechnung, Bot-Schutz, Hold-Mechanik vorhanden; Pipeline führt die Feature-Suite vor jedem Deploy aus (laut `docs/STATUS.md` grün) |
| E-Mail-Zustellung | **BLOCKER** (#3) | Staging `MAIL_MAILER=log`, nie real zugestellt |
| Kalender / iCal-Sync | PASS (Staging) | Automatischer Import alle 5 Min. per n8n laut `docs/STATUS.md` nachgewiesen (zuletzt 28./29.10.2026); Feed-Token-Schutz geprüft; Portal-Verbindung 5 ist bewusst auf „Import aus“. **UNKNOWN:** Live-Schaltung der Kanäle auf Produktion; Fremd-Feeds ohne `DTSTAMP` sind abgedeckt |
| Fehlerseiten | IMPROVE (#6) | 404 ist die englische Laravel-Standardseite (`lang="en"`, „Not Found“). Es gibt keine `resources/views/errors/`. Gäste sehen auf einer deutschen Seite englischen Text ohne Navigation. Korrektur: `404`, `419`, `429`, `500`, `503` als schlichte deutsche Seiten mit Link zur Startseite |
| Canonical | PASS | `<link rel="canonical">` auf die aktuelle URL, mit `URL::forceRootUrl(APP_URL)` also immer auf der Hauptdomain |
| Indexierung des Testauftritts | PASS | `<meta name="robots" content="noindex">` auf Staging (alles außer `APP_ENV=production`); `robots.txt` sperrt Admin, Livewire, Automation, Angebote |
| Doppelte Hosts auf Staging | IMPROVE | `www.stommer.info` und `stommer.info` liefern beide `200`. Auf Produktion eine Variante festlegen und die andere mit `301` umleiten (sonst zwei erreichbare Hosts). Canonical verhindert Dubletten nur teilweise |
| Weiterleitungen alter URLs (#5) | IMPROVE | `www.fewo-stommer.de` ist heute noch WordPress (`200`). Beim Umschalten fallen alte WordPress-URLs auf `404`. Vor dem Wechsel Liste der bekannten alten Adressen sammeln und per `.htaccess` `301` auf die neuen Seiten umleiten |
| Interner Pfad in Redirect (#10) | IMPROVE | Ein Pfad mit Slash am Ende (`/storage/app/private/backups/`) wird per `301` auf `/releases/<id>/public/…` umgeleitet und endet in `403`. Es werden nur Release-ID und Ordnerstruktur offengelegt, kein Inhalt. Beheben, wenn sich in `public/.htaccess` ohnehin etwas ändert |
| Sitemap | PASS | `/sitemap.xml` `200`, enthält nur veröffentlichte Seiten |
| Produktionskonfiguration | **BLOCKER** (#3) | siehe oben |
---
## Trennung: gesetzlich relevant vs. technische Empfehlung
**Gesetzlich relevante Anforderungen (Betreiber/Recht bewertet, technische Umsetzung hier):**
- Verschlüsselte Übertragung personenbezogener Daten (Art. 32 DSGVO) → BLOCKER #1
- Datenschutzinformation bei der Datenerhebung erreichbar (Art. 13 DSGVO) → BLOCKER #2
- Impressum/Datenschutz leicht erreichbar (DDG § 5) → PASS (technisch)
- Notwendigkeit einer Einwilligung für Cookies (§ 25 TDDDG) → nach Befund keine Einwilligung nötig, Einordnung beim Betreiber
- Wiederherstellbarkeit / Verfügbarkeit (Art. 32 DSGVO) → BLOCKER #4
- Barrierefreiheit (BFSG): Anwendbarkeit/Kleinstunternehmensausnahme entscheidet der Betreiber
**Technische Empfehlungen (keine gesetzliche Pflicht festgestellt):** BLOCKER #3 (Betriebsfähigkeit), alle IMPROVE-Punkte, CSP, Weiterleitungen, Fehlerseiten.
---
## Vorgeschlagener Umfang für Phase 2 (nach Freigabe)
1. **Code (klein):** Datenschutz-Link am Formular (#2). Optional zugleich #6 (deutsche Fehlerseiten), #7 (Formularfehler barrierefrei) und #9 (`<noscript>`), wenn gewünscht.
2. **Konfiguration (durch Betreiber/Technik, Freigabe nötig):** HTTPS-Weiterleitung (#1), Produktions-`.env`, SMTP, Datenbank, Domainzuordnung (#3).
3. **Nachweis:** Restore-Test in Wegwerf-Datenbank (#4), Test-Anfrage inkl. Mailempfang, 5-Minuten-Browser-Cookiecheck, Handtest Tastatur/NVDA.
4. **Phase 3:** Feature-Tests für Datenschutz-Link und Fehlerseiten, vollständige Suite, `vendor/bin/pint --dirty`, danach GO/NO-GO.
**Keine Änderungen, Migrationen, CMS-Anpassungen oder Deployments erfolgen ohne ausdrückliche Freigabe.**
+141 -24
View File
@@ -2,53 +2,91 @@
namespace App\Actions;
use App\Availability\CalendarClearance;
use App\Documents\OfferTerms;
use App\Enums\BookingStatus;
use App\Enums\InboxMessageKind;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\OfferAnswered;
use App\Models\Booking;
use App\Support\Content;
use App\Support\Inbox;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The guest accepts the offer on the signed offer page: the booking is concluded. A record of what was
* accepted is kept (offer version, time, fingerprints of price and terms – no IP address), then the booking
* is confirmed as usual (contract + confirmation mail as electronic acknowledgement).
* The guest accepts the offer on the signed offer page: the booking is concluded. Everything happens in one
* locked transaction (property + booking row): status, validity, integrity of the frozen offer and availability
* are checked, the acceptance record is written and the booking becomes binding – or nothing changes at all.
* Accepting the same version again is idempotent (no second booking, no second mail). Mails follow after the commit
* and never undo the acceptance.
*/
class AcceptOffer
{
public function __construct(private ConfirmBooking $confirm) {}
public function __construct(private ConfirmBooking $confirm, private Inbox $inbox, private CalendarClearance $clearance) {}
/**
* @return bool true when this call concluded the booking, false when the version had already been accepted
*
* @throws ReservationException
*/
public function handle(Booking $booking, int $offerVersion): void
public function handle(Booking $booking, int $offerVersion): bool
{
$this->ensureAcceptable($booking, $offerVersion);
$booking->update([
'accepted_at' => now(),
'acceptance' => [
'offer_version' => $booking->offer_version,
'accepted_at' => now()->toIso8601String(),
'total' => $booking->total,
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
'terms_sha256' => hash('sha256', (string) Content::get('contract.terms').'|'.Content::get('stay.cancellation')),
'via' => 'offer_link',
],
]);
$this->confirm->handle($booking);
if ($booking->status === BookingStatus::OfferSent) {
$this->ensureCalendarFresh($booking);
}
try {
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
} catch (Throwable $exception) {
report($exception);
$accepted = DB::transaction(function () use ($booking, $offerVersion): bool {
$booking->lockForTransition();
if ($this->alreadyAccepted($booking, $offerVersion)) {
return false;
}
$this->ensureAcceptable($booking, $offerVersion);
$this->ensureUnchanged($booking);
$validUntil = $booking->hold_expires_at?->toIso8601String();
$this->confirm->bind($booking);
$booking->update([
'accepted_at' => now(),
'acceptance' => [
'offer_version' => $booking->offer_version,
'accepted_at' => now()->toIso8601String(),
'offer_sent_at' => $booking->offer_sent_at?->toIso8601String(),
'valid_until' => $validUntil,
'total' => $booking->total,
'offer_hash' => $booking->offer_hash,
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
'terms_sha256' => hash('sha256', json_encode($booking->offer_terms['texts'] ?? [])),
'accept_button' => $booking->offerText('offer.accept_button'),
'via' => 'offer_link',
],
]);
return true;
});
} catch (ReservationException $exception) {
$this->noteRejection($booking, $offerVersion, $exception);
throw $exception;
}
if ($accepted) {
$this->confirm->deliver($booking);
$this->notifyLandlord($booking);
}
return $accepted;
}
/**
* Checks that make the offer page show the form: version, status and validity (no locks, read only).
*
* @throws ReservationException
*/
public function ensureAcceptable(Booking $booking, int $offerVersion): void
@@ -65,4 +103,83 @@ public function ensureAcceptable(Booking $booking, int $offerVersion): void
throw ReservationException::offerExpired();
}
}
/**
* The frozen offer must still match its fingerprint (price, dates, terms); offers made before the
* fingerprint existed have none and are not checked.
*
* @throws ReservationException
*/
public function ensureUnchanged(Booking $booking): void
{
if ($booking->offer_hash !== null && ! hash_equals($booking->offer_hash, OfferTerms::hash($booking))) {
throw ReservationException::offerChanged();
}
}
/**
* Before the guest becomes bound, the imported portal calendars must be recent (an import is tried first –
* network access, so outside the transaction). Otherwise nothing is concluded and the landlord is told.
*
* @throws ReservationException
*/
private function ensureCalendarFresh(Booking $booking): void
{
$property = $booking->property;
$this->clearance->refresh($property);
$stale = $this->clearance->staleImports($property);
if ($stale->isEmpty()) {
return;
}
$this->inbox->post(
InboxMessageKind::SyncFailed,
'accept-'.$booking->id.':'.now()->format('YmdH'),
'Annahme von '.$booking->reference.' zurückgestellt: Kalenderstand nicht aktuell',
'Der Gast wollte das Angebot annehmen, aber der Import von '.$stale->pluck('name')->implode(', ').' ist nicht aktuell. Bitte Kalenderabgleich prüfen und den Gast kontaktieren.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
throw ReservationException::calendarUnverified();
}
private function alreadyAccepted(Booking $booking, int $offerVersion): bool
{
return in_array($booking->status, BookingStatus::occupying(), true)
&& $booking->accepted_at !== null
&& ($booking->acceptance['offer_version'] ?? null) === $offerVersion;
}
private function noteRejection(Booking $booking, int $offerVersion, ReservationException $exception): void
{
if ($offerVersion !== $booking->offer_version || $booking->status !== BookingStatus::OfferSent) {
return;
}
$reasonIsUnexpected = $exception->getMessage() === ReservationException::offerChanged()->getMessage()
|| $exception->getMessage() === ReservationException::notAvailable()->getMessage();
if (! $reasonIsUnexpected) {
return;
}
$this->inbox->post(
InboxMessageKind::OfferRejected,
'booking-'.$booking->id.':v'.$offerVersion,
'Annahme von Angebot '.$booking->reference.' abgewiesen',
'Der Gast wollte das Angebot annehmen, aber: '.$exception->getMessage().' Bitte den Gast kontaktieren oder ein neues Angebot senden.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
}
private function notifyLandlord(Booking $booking): void
{
try {
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
} catch (Throwable $exception) {
Log::warning('Benachrichtigung über Annahme nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
}
+110
View File
@@ -0,0 +1,110 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Availability\CalendarClearance;
use App\Documents\DocumentComposer;
use App\Documents\DocumentFinding;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Pricing\QuoteException;
use App\Support\Content;
use App\Support\Settings;
/**
* Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every
* release rule is met, otherwise leaves the request untouched for manual processing and says why.
*
* Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract
* texts released by the landlord (not the sample text; skipped while mails only go to the test recipient),
* the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed) and an
* offer composition without anything to confirm ({@see DocumentComposer}: template released, contract data complete).
*/
class AutoOffer
{
public function __construct(
private SendOffer $sendOffer,
private CalendarClearance $clearance,
private AvailabilityChecker $availability,
) {}
public function applies(Booking $booking): bool
{
return $booking->processingMode() === ProcessingMode::Automatic;
}
/**
* @return list<string> reasons why the offer cannot be sent automatically (empty = may be sent)
*/
public function blockers(Booking $booking): array
{
$property = $booking->property;
$reasons = [];
if (! $booking->process()->preReservation()) {
$reasons[] = 'Anfragen reservieren den Zeitraum nicht (Einstellung „Vorreservierung“); ohne Sperre im Kalender wird kein Angebot automatisch erteilt.';
}
if ($booking->status !== BookingStatus::Reserved || ! $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.';
}
if (! $this->availability->isAvailable($property, $booking->arrival, $booking->departure, ignore: $booking)) {
$reasons[] = 'Der Zeitraum ist inzwischen belegt.';
}
if (! $this->contractTextsReleased()) {
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
}
// Status, e-mail, dates and the missing reservation are checked above; the composition adds what concerns the document.
$reasons = [...$reasons, ...app(DocumentComposer::class)->compose($booking, DocumentKind::Offer)->toConfirm(except: [DocumentFinding::HOLD_ZERO])];
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
}
/**
* Tries to send the offer. Imports of stale channels are refreshed first (network access, outside transactions).
*
* @return list<string> reasons for the manual fallback; empty when the offer was sent
*/
public function handle(Booking $booking): array
{
$booking->loadMissing(['property', 'guest']);
if ($booking->process()->preReservation()) {
$this->clearance->refresh($booking->property);
}
$reasons = $this->blockers($booking);
if ($reasons !== []) {
return $reasons;
}
try {
$this->sendOffer->handle($booking->fresh(), ['expected_version' => 0]);
} catch (QuoteException|ReservationException $exception) {
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
return [$exception->getMessage()];
}
return [];
}
private function contractTextsReleased(): bool
{
if (! Settings::isLive()) {
return true;
}
$terms = (string) Content::get('contract.terms');
return filled($terms) && ! str_contains($terms, '[MUSTER')
&& filled(Content::get('stay.cancellation'))
&& filled(config('fewo.bank.iban'));
}
}
+97
View File
@@ -0,0 +1,97 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingCancelled;
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Support\CancellationCost;
use App\Support\Money;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
* the cancellation costs is created. Open cancellation requests of the guest are completed.
*/
class CancelBooking
{
/**
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
*
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung', string $initiatedBy = 'landlord'): bool
{
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
}
DB::transaction(function () use ($booking, $costsTask, $by, $initiatedBy): void {
$booking->lockForTransition();
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, $initiatedBy);
if ($booking->caseType()->isExternallyBinding()) {
// The contract was made on the portal: the cancellation has to happen (or be checked) there as well.
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::PortalCancellation], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => 'Stornierung auch im Portal „'.($booking->processChannel()?->name ?? 'Portal').'“ veranlassen bzw. prüfen, ob sie dort wirksam ist.',
]);
}
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
if ($costsTask) {
$cost = CancellationCost::calculate($booking);
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
'status' => BookingTaskStatus::Open,
'due_on' => today(),
'note' => $cost ? 'Vorschlag nach Stornoregel „'.$cost['policy'].'“: '.Money::format($cost['fee']).' ('.$cost['tier_text'].')' : 'Keine Stornoregel hinterlegt – Kosten von Hand festlegen.',
]);
}
});
$booking->loadMissing(['guest', 'property']);
return $this->notify($booking, $notifyGuest);
}
private function notify(Booking $booking, bool $notifyGuest): bool
{
$informed = true;
try {
Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, cancelled: true));
} catch (Throwable $exception) {
Log::warning('Stornomitteilung an den Vermieter nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
if ($notifyGuest) {
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, cancelled: true));
} catch (Throwable $exception) {
$informed = false;
Log::warning('Stornomail an den Gast nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
return $informed;
}
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CancellationMode;
use App\Exceptions\ReservationException;
use App\Mail\BookingCancelled;
use App\Mail\CancellationRequested;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Support\CancellationCost;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The guest uses the cancellation link of the booking confirmation. Depending on the property's setting the
* booking is cancelled at once (dates released) or only a request task is created for the landlord – costs
* are never settled automatically. Repeating the click changes nothing.
*/
class CancelBookingByGuest
{
/**
* What a click on the link does for this booking today.
*/
public function modeFor(Booking $booking): CancellationMode
{
$property = $booking->property;
$freeUntil = $booking->arrival->subDays($property->free_cancellation_days);
return match ($property->cancellation_mode) {
CancellationMode::Instant => CancellationMode::Instant,
CancellationMode::InstantWhenFree => ($cost = CancellationCost::calculate($booking)) !== null
? ($cost['free'] ? CancellationMode::Instant : CancellationMode::Request)
: (today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request),
default => CancellationMode::Request,
};
}
/**
* @return CancellationMode|null what happened (Instant = cancelled, Request = request recorded); null when it had happened before
*
* @throws ReservationException
*/
public function handle(Booking $booking, ?string $message = null): ?CancellationMode
{
$outcome = DB::transaction(function () use ($booking, $message): ?CancellationMode {
$booking->lockForTransition();
$alreadyAsked = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->exists();
if ($booking->status === BookingStatus::Cancelled || $alreadyAsked) {
return null;
}
if (! in_array($booking->status, BookingStatus::occupying(), true) || $booking->arrival->isPast()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
}
$mode = $this->modeFor($booking);
if ($mode === CancellationMode::Instant) {
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
app(RecordCancellation::class)->handle($booking, 'guest');
}
BookingTask::query()->create([
'booking_id' => $booking->id,
'kind' => BookingTaskKind::CancellationRequest,
'status' => BookingTaskStatus::Open,
'note' => trim(($mode === CancellationMode::Instant ? 'Vom Gast storniert – bitte Stornokosten und Rückzahlung prüfen. ' : '').($message ?? '')) ?: null,
]);
return $mode;
});
if ($outcome !== null) {
$this->notify($booking, $outcome);
}
return $outcome;
}
private function notify(Booking $booking, CancellationMode $mode): void
{
$booking->loadMissing(['guest', 'property']);
$cancelled = $mode === CancellationMode::Instant;
$sends = [
fn () => Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, $cancelled)),
fn () => $booking->guest?->email ? Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, $cancelled)) : null,
];
foreach ($sends as $send) {
try {
$send();
} catch (Throwable $exception) {
Log::warning('Stornomitteilung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
}
}
+99 -14
View File
@@ -3,56 +3,141 @@
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation;
use App\Models\Booking;
use App\Process\CaseLog;
use App\Support\Inbox;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Makes a booking binding: payment due dates are fixed, the rental contract is generated and sent with the
* confirmation. Used when the guest accepts an offer (AcceptOffer) and when the landlord confirms directly
* (e.g. a booking agreed on the phone). Expired requests/offers can still be confirmed while the dates are free.
*
* Binding is one locked database step ({@see bind()}); contract and mail follow afterwards ({@see deliver()}).
* A failing mail server never undoes a binding booking – the failure is recorded and the mail can be resent.
*/
class ConfirmBooking
{
public function __construct(
private AvailabilityChecker $availability,
private RentalContract $contract,
private Inbox $inbox,
) {}
/**
* @return bool whether the guest has the confirmation (true when no mail was requested)
*
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true): void
public function handle(Booking $booking, bool $notifyGuest = true): bool
{
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
DB::transaction(fn () => $this->bind($booking));
return $this->deliver($booking, $notifyGuest);
}
/**
* Locks the property and the booking, checks status and availability and makes the booking binding.
* Must run inside a transaction; every writer of bookings takes the same property lock, so two
* overlapping stays can never both become binding.
*
* @throws ReservationException
*/
public function bind(Booking $booking): void
{
$booking->lockForTransition();
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
}
DB::transaction(function () use ($booking): void {
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
throw ReservationException::notAvailable();
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$terms = $booking->offer_terms ?? OfferTerms::capture(OfferTerms::templateFor($booking), $booking);
$booking->update([
'status' => BookingStatus::Confirmed,
'hold_expires_at' => null,
'confirmed_at' => now(),
'offer_terms' => $terms,
'deposit_due_on' => today()->addDays((int) ($terms['deposit_due_days'] ?? config('fewo.deposit_due_days')))->toDateString(),
]);
}
/**
* Generates the contract and sends the confirmation – after the booking is saved, with every failure
* contained: the booking stays binding, the failure is marked and shown in the admin inbox.
*
* @return bool whether the guest has the confirmation (true when no mail was requested)
*/
public function deliver(Booking $booking, bool $notifyGuest = true, ?DocumentKind $kind = null): bool
{
$booking->loadMissing(['guest', 'property']);
$kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Confirmation;
try {
$created = $booking->contract_path === null;
$this->contract->generate($booking, kind: $kind);
if ($created) {
CaseLog::record($booking, 'document', $kind->getLabel().' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: [
'kind' => $kind->value,
'template' => $booking->offer_terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])),
'pdf_sha256' => $booking->contract_pdf_sha256,
]);
}
$booking->update([
'status' => BookingStatus::Confirmed,
'hold_expires_at' => null,
'confirmed_at' => now(),
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
]);
});
if (! $notifyGuest) {
return true;
}
$this->contract->generate($booking);
Mail::to($booking->guest->email, $booking->guest->full_name)->send($kind === DocumentKind::ExternalRecord ? new BookingDocumentation($booking) : new BookingConfirmed($booking));
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->save();
if ($notifyGuest) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
return true;
} catch (Throwable $exception) {
// Only class and booking id are logged: mail errors can contain the recipient's address.
Log::warning('Buchungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$booking->forceFill(['confirmation_failed_at' => now()])->save();
$this->inbox->post(
InboxMessageKind::ConfirmationFailed,
'booking-'.$booking->id,
'Buchungsbestätigung '.$booking->reference.' nicht zugestellt',
'Die Buchung ist verbindlich gespeichert, aber der Vertrag konnte nicht erzeugt oder die Bestätigung nicht versendet werden. Auf der Buchungsseite kann die Bestätigung erneut gesendet werden.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
return false;
}
}
/**
* Sends the confirmation again (admin action / command). Does nothing for bookings that are not binding.
*/
public function resend(Booking $booking): bool
{
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'erneut bestätigt');
}
return $this->deliver($booking);
}
}
+46 -12
View File
@@ -4,25 +4,29 @@
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Exceptions\ReservationException;
use App\Mail\NewReservation;
use App\Mail\ReservationReceived;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\ProcessSettings;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* Turns a guest request into a reservation that holds the dates for the property's hold time,
* Turns a guest request into a case (intake "request") that holds the dates for the hold time of the process settings,
* and sends the quote to the guest and a notification to the landlord.
*/
class CreateReservation
@@ -39,7 +43,7 @@ public function __construct(
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = [], ?Channel $originChannel = null): Booking
{
$tenant = $property->tenant;
@@ -49,7 +53,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution, $originChannel),
);
}
@@ -57,9 +61,13 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution, ?Channel $originChannel): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
if ($originChannel !== null && $originChannel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution, $originChannel): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
@@ -69,11 +77,14 @@ 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);
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
'intake' => IntakeKind::Inquiry,
'origin_channel_id' => $originChannel?->id,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
@@ -84,7 +95,7 @@ private function create(Property $property, StayRequest $stay, array $guestData,
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => now()->addHours($property->hold_hours),
'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,
]);
@@ -107,8 +118,8 @@ private function create(Property $property, StayRequest $stay, array $guestData,
*/
private function guestFor(array $guestData): array
{
$email = mb_strtolower($guestData['email']);
$guest = Guest::query()->where('email', $email)->first();
$email = mb_strtolower(trim((string) ($guestData['email'] ?? '')));
$guest = $email === '' ? null : Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([
@@ -138,15 +149,38 @@ private function guestFor(array $guestData): array
}
/**
* A failing mail server must not lose the reservation; failures are reported and visible in the log.
* Automatic mode first tries to send the offer; the guest then gets the offer instead of the receipt, the
* landlord a note either way (with the reasons when the automatic offer was not possible). A failing mail
* server or any other error must not lose the reservation; failures are logged without personal data.
*/
private function sendMails(Booking $booking): void
{
$blockers = [];
$offerSent = false;
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking));
$auto = app(AutoOffer::class);
if ($auto->applies($booking)) {
$blockers = $auto->handle($booking);
$offerSent = $blockers === [];
if (! $offerSent) {
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
}
$booking->refresh();
}
} catch (Throwable $exception) {
report($exception);
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
$offerSent = false;
}
try {
if (! $offerSent && 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));
} catch (Throwable $exception) {
Log::warning('Eingangsmail nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Actions;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use Carbon\CarbonImmutable;
/**
* Takes over a reservation found in a portal calendar as a case ({@see TakeOverExternalBooking}). The calendar only
* says "these nights are taken"; the case gives the reservation its handling. The calendar entry stays as the portal's
* mirror of the case. A first name from the calendar is no guest identity – it is kept as a note, not as a guest.
*/
class OpenPortalFile
{
public function __construct(private TakeOverExternalBooking $takeOver) {}
/**
* @throws ReservationException
*/
public function handle(BlockedPeriod $block): Booking
{
if ($block->channel === null) {
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
}
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
$name = trim((string) ($fields['guest_first_name'] ?? ''));
return $this->takeOver->handle(
$block->property,
$block->channel,
CarbonImmutable::parse($block->starts_on),
CarbonImmutable::parse($block->ends_on),
['notes' => 'Aus dem Portalkalender „'.$block->channel->name.'“ übernommen.'.($name !== '' ? ' Name laut Kalender: '.$name.'.' : '')],
$block,
);
}
}
+25 -4
View File
@@ -3,19 +3,21 @@
namespace App\Actions;
use App\Channels\ConflictDetector;
use App\Channels\Intake\PortalIntake;
use App\Channels\Mail\ParsedPortalMail;
use App\Channels\Mail\PortalMail;
use App\Channels\Mail\PortalMailParser;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Enums\TenantServiceKey;
use App\Mail\ChannelConflict;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\IntakeObservation;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -75,17 +77,31 @@ public function handle(PortalMail $mail): ?PortalEmail
]);
});
// One intake for all channels (package 4): bookings, requests and cancellations reach their case.
rescue(fn () => $this->intake($channel, $parsed, $record));
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
}
if ($conflicts !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
}
return $record;
}
private function intake(Channel $channel, ParsedPortalMail $parsed, PortalEmail $record): void
{
$intake = app(PortalIntake::class);
match ($parsed->type) {
PortalEmailType::Booking => $record->blocked_period_id !== null ? $intake->process(BlockedPeriod::query()->findOrFail($record->blocked_period_id), IntakeObservation::SOURCE_MAIL) : null,
PortalEmailType::Cancellation => $intake->cancellationMail($channel, $parsed, $record),
PortalEmailType::Inquiry => $intake->inquiryMail($channel, $parsed, $record),
PortalEmailType::Unknown => null,
};
}
/**
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
*/
@@ -126,7 +142,7 @@ public function senders(Channel $channel): array
}
/**
* @param list<string> $conflicts
* @param array<string, CarbonInterface> $conflicts description => first night
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
@@ -158,7 +174,7 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
$block->forceFill(['needs_review' => true, 'review_note' => 'Überlappende Portalrepräsentationen ohne gemeinsame Kennung persönlich prüfen.'])->saveQuietly();
}
$conflicts = $this->conflictDetector->conflictsFor($block);
$conflicts = array_fill_keys($this->conflictDetector->conflictsFor($block), $block->starts_on);
return [PortalEmailStatus::Blocked, $block, null];
}
@@ -177,6 +193,11 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array
default => null,
};
// A block that belongs to a case is never released by a mail: the case leads, the landlord decides (E-019).
if ($block && $block->linked_booking_id !== null) {
return [PortalEmailStatus::NeedsReview, $block, 'Stornierung zu einem gebuchten Vorgang gemeldet – nichts automatisch freigegeben; Aufgabe am Vorgang prüfen.'];
}
if ($block) {
$block->delete();
+90
View File
@@ -0,0 +1,90 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Guest;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* The guest's contact data arrived (portal message, e-mail, phone) and is entered on the booking. The landlord chooses
* whether the process continues automatically – a binding portal booking gets its contract, a request gets the
* offer – or by hand (data only). An already existing e-mail confirmation of the guest can be recorded as well.
*/
class ProvideGuestContact
{
public const AUTOMATIC = 'automatic';
public const MANUAL = 'manual';
public function __construct(private ConfirmBooking $confirm, private AutoOffer $autoOffer, private SendBookingDocuments $documents) {}
/**
* @param array<string, ?string> $contact first_name, last_name, email, phone, street, postal_code, city, country
* @return string what was done, for the notification
*
* @throws ReservationException
*/
public function handle(Booking $booking, array $contact, string $process = self::MANUAL, bool $guestConfirmed = false): string
{
$contact = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($contact, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']));
if (isset($contact['email'])) {
$contact['email'] = mb_strtolower($contact['email']);
}
if ($process === self::AUTOMATIC && blank($contact['email'] ?? $booking->guest?->email)) {
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 ($guestConfirmed) {
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->save();
}
$booking->refresh()->load('guest');
if ($process !== self::AUTOMATIC) {
return 'Kontaktdaten gespeichert';
}
$booking->update(['processing_mode' => ProcessingMode::Automatic]);
if (in_array($booking->status, BookingStatus::occupying(), true)) {
$reasons = $this->documents->automatically($booking);
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons));
}
return 'Kontaktdaten gespeichert, Unterlagen gesendet';
}
if ($booking->intake === IntakeKind::Booking) {
DB::transaction(fn () => $this->confirm->bind($booking));
$reasons = $this->documents->automatically($booking->fresh());
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert und Buchung bestätigt. Die Unterlagen werden noch nicht automatisch versendet: '.implode(' ', $reasons));
}
return 'Kontaktdaten gespeichert, Buchung bestätigt und Unterlagen gesendet';
}
$reasons = $this->autoOffer->handle($booking);
if ($reasons !== []) {
throw new ReservationException('Kontaktdaten gespeichert. Das Angebot wird noch nicht automatisch gesendet: '.implode(' ', $reasons));
}
return 'Kontaktdaten gespeichert, Angebot gesendet';
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Actions;
use App\Models\Booking;
use App\Models\Cancellation;
use App\Support\CancellationCost;
/**
* Records the cancellation of a booking with the cost proposed by the frozen cancellation rule. Called when a booking
* is cancelled (by the landlord or through the guest's link); safe to call twice.
*/
class RecordCancellation
{
public function handle(Booking $booking, string $initiatedBy): Cancellation
{
$cost = CancellationCost::calculate($booking);
return Cancellation::query()->firstOrCreate(
['booking_id' => $booking->id],
[
'cancelled_on' => today(),
'initiated_by' => $initiatedBy,
'has_policy' => $cost !== null,
'policy_name' => $cost['policy'] ?? null,
'days_before' => $cost['days_before'] ?? null,
'percent' => $cost['percent'] ?? null,
'base_amount' => $cost['base_amount'] ?? null,
'calculated_fee' => $cost['fee'] ?? null,
'paid_amount' => $booking->paidAmount(),
'status' => Cancellation::OPEN,
],
);
}
}
+16 -11
View File
@@ -7,6 +7,7 @@
use App\Mail\OfferAnswered;
use App\Models\Booking;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Throwable;
@@ -20,19 +21,23 @@ class RejectOffer
*/
public function handle(Booking $booking, int $offerVersion): void
{
if ($offerVersion !== $booking->offer_version) {
throw ReservationException::offerOutdated();
}
DB::transaction(function () use ($booking, $offerVersion): void {
$booking->lockForTransition();
if ($booking->status !== BookingStatus::OfferSent) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
}
if ($offerVersion !== $booking->offer_version) {
throw ReservationException::offerOutdated();
}
$booking->update([
'status' => BookingStatus::Declined,
'declined_by' => 'guest',
'hold_expires_at' => null,
]);
if ($booking->status !== BookingStatus::OfferSent) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
}
$booking->update([
'status' => BookingStatus::Declined,
'declined_by' => 'guest',
'hold_expires_at' => null,
]);
});
try {
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\OfferAnswered;
use App\Models\Booking;
use App\Support\Settings;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The guest releases a held request or offer through the link in the mail – the dates are free again at once.
* Repeating it is harmless. The link only reaches requests that are still held; a binding booking is never touched.
*/
class ReleaseReservation
{
/**
* @return bool true when this call released the dates, false when they had been released before
*
* @throws ReservationException
*/
public function handle(Booking $booking): bool
{
$released = DB::transaction(function () use ($booking): bool {
$booking->lockForTransition();
if ($booking->status === BookingStatus::Declined && $booking->declined_by === 'guest') {
return false;
}
if (! in_array($booking->status, BookingStatus::holding(), true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'freigegeben');
}
$booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'guest', 'hold_expires_at' => null]);
return true;
});
if ($released) {
try {
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
} catch (Throwable $exception) {
Log::warning('Meldung über Freigabe nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
}
}
return $released;
}
}
+8 -2
View File
@@ -5,18 +5,24 @@
use App\Mail\ChannelTasksNotification;
use App\Models\ChannelTask;
use App\Support\Settings;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Mail;
/**
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
* Reminds the landlord about blocking tasks that are still open after the reminder time, and again after
* the landlord's reminder interval while they stay open (Settings::reminderIntervalDays(), 0 = only once).
*/
class RemindChannelTasks
{
public function handle(): int
{
$interval = Settings::reminderIntervalDays();
$tasks = ChannelTask::query()
->open()
->whereNull('reminded_at')
->where(fn (Builder $query) => $query
->whereNull('reminded_at')
->when($interval > 0, fn (Builder $query) => $query->orWhere('reminded_at', '<=', now()->subDays($interval))))
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
->with('channel')
->get();
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Actions;
use App\Enums\InboxMessageKind;
use App\Filament\Pages\OccupancyCalendar;
use App\Mail\ChannelConflict;
use App\Models\Channel;
use App\Support\Inbox;
use App\Support\Settings;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Mail;
/**
* Reports possible double bookings found while importing portal occupations (calendar sync or portal
* e-mail). Every conflict lands in the admin inbox once; only conflicts not reported before are e-mailed,
* so a lasting overlap does not trigger a mail on every sync. Unread ones are repeated after the landlord's
* reminder interval while the overlap persists (App\Support\Inbox).
*/
class ReportChannelConflicts
{
public function __construct(private Inbox $inbox) {}
/**
* @param array<string, CarbonInterface> $conflicts description => first night of the portal occupation
* @return list<string> the conflicts e-mailed now (new ones and due reminders)
*/
public function handle(Channel $channel, array $conflicts): array
{
$new = [];
$reminders = [];
foreach ($conflicts as $description => $startsOn) {
$message = $this->inbox->post(
InboxMessageKind::ChannelConflict,
$channel->id.':'.sha1($description),
'Mögliche Doppelbuchung über '.$channel->name,
$description,
$channel,
OccupancyCalendar::getUrl(['monat' => $startsOn->format('Y-m'), 'wohnung' => $channel->property_id]),
);
if ($message?->wasRecentlyCreated) {
$new[] = $description;
} elseif ($message) {
$reminders[] = $description;
}
}
if ($new !== [] || $reminders !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new, $reminders)));
}
return [...$new, ...$reminders];
}
}
+3 -1
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\Responsibility;
use App\Mail\ReviewRequest;
use App\Models\Booking;
use Illuminate\Support\Facades\Mail;
@@ -25,7 +26,8 @@ public function handle(): int
->whereDoesntHave('review')
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->with('guest')
->get();
->get()
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord);
foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReviewRequest($booking));
+5
View File
@@ -2,6 +2,7 @@
namespace App\Actions;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
@@ -44,6 +45,10 @@ public function handle(BlockedPeriod $block, string $resolution, ?int $targetId
'linked_booking_id' => $resolution === 'booking' ? $target->id : null,
'review_note' => 'Persönlich zugeordnet; nur die führende Belegung steuert Verfügbarkeit und Export.'];
}
// A stay confirmed as independent with a known booking channel (or privately) is no longer "unclear".
if ($resolution === 'independent' && ($originId !== null || $attributes['is_private']) && in_array($block->occupationKind(), [OccupationKind::Unknown], true)) {
$attributes['occupation_kind'] = OccupationKind::Reservation;
}
$block->forceFill(['representation_automatic' => false])->fill($attributes)->save();
app(ReconcileChannelRepresentations::class)->handle($block->property);
+113
View File
@@ -0,0 +1,113 @@
<?php
namespace App\Actions;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Enums\DocumentKind;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Process\CaseLog;
use Illuminate\Support\Facades\Cache;
/**
* Sends the documents of a binding case – the confirmation with the rental contract, or the booking documentation of a
* booking already binding on a portal – from its composition ({@see DocumentComposer}). Automatically only when nothing
* is missing and nothing has to be confirmed; by hand after the landlord confirmed every point. The documents go out
* once: a lock and a fresh look at the case keep repeated runs, double clicks and parallel jobs from sending twice.
* Until the first document exists the terms are taken from the composition (template and annexes as chosen); after
* that they stay as they were sent.
*/
class SendBookingDocuments
{
public function __construct(private DocumentComposer $composer, private ConfirmBooking $confirm) {}
/**
* @param array<string, mixed> $changes
*/
public function compose(Booking $booking, array $changes = []): DocumentComposition
{
return $this->composer->compose($booking, self::kindFor($booking), $changes);
}
/**
* The automatic run: sends when the composition allows it.
*
* @return list<string> why nothing was sent (empty: sent or nothing to send)
*/
public function automatically(Booking $booking): array
{
if ($booking->confirmation_sent_at !== null) {
return [];
}
$composition = $this->compose($booking);
if (! $composition->canSendAutomatically()) {
return [...$composition->blockers(), ...array_map(fn (string $point): string => 'Bitte prüfen: '.$point, $composition->toConfirm())];
}
return $this->send($booking, $composition, acknowledged: false, automatic: true) ? [] : ['Die Unterlagen konnten nicht versendet werden (siehe Postfach).'];
}
/**
* Sending by hand after the landlord saw the composition.
*
* @param array<string, mixed> $changes contract_template_id, annex_ids
* @return bool whether the guest has the documents
*
* @throws ReservationException
*/
public function handle(Booking $booking, array $changes = [], bool $acknowledged = false): bool
{
if (! $booking->isBinding()) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'mit Unterlagen bestätigt');
}
$composition = $this->compose($booking, $changes);
if ($composition->blockers() !== []) {
throw new ReservationException(implode(' ', $composition->blockers()));
}
if (! $composition->canSendByHand($acknowledged)) {
throw new ReservationException('Bitte die Hinweise prüfen und ausdrücklich bestätigen: '.implode(' ', $composition->toConfirm()));
}
return $this->send($booking, $composition, $acknowledged, automatic: false);
}
/**
* The document kind of a binding case (a case whose documents the portal sends has none from us).
*/
public static function kindFor(Booking $booking): DocumentKind
{
$kind = DocumentKind::forCase($booking);
return in_array($kind, [DocumentKind::Confirmation, DocumentKind::ExternalRecord], true) ? $kind : DocumentKind::Confirmation;
}
private function send(Booking $booking, DocumentComposition $composition, bool $acknowledged, bool $automatic): bool
{
$lock = Cache::lock('booking-documents-'.$booking->id, 120);
if (! $lock->get()) {
throw new ReservationException('Die Unterlagen werden gerade versendet. Bitte kurz warten und die Seite neu laden.');
}
try {
$booking->refresh();
if ($booking->confirmation_sent_at !== null) {
return true;
}
if (! $composition->termsFrozen && $booking->contract_path === null && $composition->terms !== null) {
$booking->update(['offer_terms' => $composition->terms]);
}
if ($acknowledged && $composition->toConfirm() !== []) {
CaseLog::record($booking, 'document', 'Hinweise vor dem Versand bestätigt', data: ['confirmed' => $composition->toConfirm()]);
}
return CaseLog::context(fn (): bool => $this->confirm->deliver($booking, kind: $composition->kind), actor: $automatic ? CaseLog::SYSTEM.' (automatisch)' : null);
} finally {
$lock->release();
}
}
}
+32 -16
View File
@@ -3,22 +3,28 @@
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\Responsibility;
use App\Mail\ArrivalInformation;
use App\Mail\PaymentReminder;
use App\Models\Booking;
use App\Models\BookingTask;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
/**
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
* Every message is sent at most once per booking.
* Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord
* (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click
* ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured
* number of days before arrival. Completion after departure.
*/
class SendBookingReminders
{
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
/** Upper bound of the per-property setting; the property decides the actual day. */
private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14;
/**
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
@@ -33,7 +39,7 @@ public function handle(): array
->whereNull('deposit_reminded_at')
->whereDate('deposit_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
$depositTasks = $this->createTasks($depositOverdue, BookingTaskKind::DepositReminder, fn (Booking $booking) => $booking->deposit_due_on);
$balanceRequest = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
@@ -41,20 +47,22 @@ public function handle(): array
->whereDate('balance_due_on', '>=', $today)
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
$requestTasks = $this->createTasks($balanceRequest, BookingTaskKind::BalanceRequest, fn (Booking $booking) => $booking->balance_due_on);
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
->whereNull('balance_reminded_at')
->whereDate('balance_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
$overdueTasks = $this->createTasks($balanceOverdue, BookingTaskKind::BalanceReminder, fn (Booking $booking) => $booking->balance_due_on);
$arrivals = $this->bookings(fn (Builder $query) => $query
->whereIn('status', BookingStatus::occupying())
->whereNull('arrival_info_sent_at')
->whereDate('arrival', '>=', $today)
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => $booking->process()->guestMessages() === Responsibility::Landlord
&& $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->process()->arrivalInfoDaysBefore())));
foreach ($arrivals as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
$booking->update(['arrival_info_sent_at' => now()]);
@@ -67,9 +75,9 @@ public function handle(): array
$completed->each->update(['status' => BookingStatus::Completed]);
return [
'deposit_overdue' => $depositOverdue->count(),
'balance_request' => $balanceRequest->count(),
'balance_overdue' => $balanceOverdue->count(),
'deposit_overdue' => $depositTasks,
'balance_request' => $requestTasks,
'balance_overdue' => $overdueTasks,
'arrival_info' => $arrivals->count(),
'completed' => $completed->count(),
];
@@ -81,7 +89,7 @@ public function handle(): array
*/
private function bookings(callable $constraints): Collection
{
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
return $constraints(Booking::query()->with(['guest', 'property', 'payments', 'importChannel', 'originChannel']))
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->get()
->toBase();
@@ -89,12 +97,20 @@ private function bookings(callable $constraints): Collection
/**
* @param Collection<int, Booking> $bookings
* @param callable(Booking): mixed $dueOn
* @return int the number of tasks created now
*/
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
private function createTasks(Collection $bookings, BookingTaskKind $kind, callable $dueOn): int
{
foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
$booking->update([$sentAtColumn => now()]);
$created = 0;
foreach ($bookings->filter(fn (Booking $booking): bool => $booking->wantsPaymentTasks()) as $booking) {
$task = BookingTask::query()->firstOrCreate(
['booking_id' => $booking->id, 'kind' => $kind],
['status' => BookingTaskStatus::Open, 'due_on' => $dueOn($booking)],
);
$created += $task->wasRecentlyCreated ? 1 : 0;
}
return $created;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Actions;
use App\Enums\DigestSection;
use App\Mail\Digest;
use App\Models\Tenant;
use App\Support\DigestReport;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Mail;
/**
* Sends the landlord's daily and/or weekly summary once the chosen hour has come (System › Betrieb ›
* Benachrichtigungen). On the weekly day only the weekly summary goes out, never both. Runs per landlord
* from the scheduler; the sent dates on the landlord make every summary go out at most once a day.
*/
class SendDigests
{
public function __construct(private DigestReport $report) {}
/**
* @return 'daily'|'weekly'|null which summary was due (also when it was skipped for being empty)
*/
public function handle(Tenant $tenant): ?string
{
$now = CarbonImmutable::now();
$today = $now->startOfDay();
if ($now->hour < $tenant->digest_hour) {
return null;
}
$weekly = $tenant->digest_weekly && $today->isoWeekday() === $tenant->digest_weekday && ! $tenant->digest_weekly_sent_on?->isSameDay($today);
$daily = $tenant->digest_daily && ! $tenant->digest_daily_sent_on?->isSameDay($today);
if (! $weekly && ! $daily) {
return null;
}
$this->send($tenant, $weekly);
$tenant->forceFill([
'digest_daily_sent_on' => $today->toDateString(),
...($weekly ? ['digest_weekly_sent_on' => $today->toDateString()] : []),
])->save();
return $weekly ? 'weekly' : 'daily';
}
/**
* Builds and mails one summary. Without anything to report it is skipped unless the landlord wants it
* anyway or $force is set (button „Zusammenfassung jetzt senden“).
*
* @return bool whether a mail was sent
*/
public function send(Tenant $tenant, bool $weekly, bool $force = false): bool
{
$since = CarbonImmutable::now()->sub($weekly ? '7 days' : '1 day');
$sections = $this->report->build(DigestSection::chosen($tenant->digest_sections), $weekly, $since);
if ($sections === [] && ! $tenant->digest_when_empty && ! $force) {
return false;
}
Mail::to(Settings::notificationRecipients())->send(new Digest($weekly, $sections));
return true;
}
}
+72 -5
View File
@@ -3,10 +3,15 @@
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\DocumentComposer;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\InboxMessageKind;
use App\Enums\QuoteLineType;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Mail\OfferMade;
use App\Models\Booking;
use App\Pricing\PriceCalculator;
@@ -14,11 +19,15 @@
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use App\Process\CaseLog;
use App\Support\Inbox;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Booking path 1 (docs/KONZEPT.md §6a): the landlord turns a request into an offer. Dates, guests, promo
@@ -32,10 +41,16 @@ public function __construct(
private PriceCalculator $calculator,
private AvailabilityChecker $availability,
private RentalContract $contract,
private Inbox $inbox,
) {}
/**
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, guest?: array<string, ?string>} $changes
* The offer is checked through its composition ({@see DocumentComposer}) like every other document: points the
* landlord has to confirm (e.g. an unreleased template, missing contract data, a request that by the settings
* reserves nothing) stop it unless `acknowledged` is set. `expected_version` makes a repeated call harmless: when
* another offer was sent in the meantime, nothing is sent again.
*
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>, acknowledged?: bool, expected_version?: ?int} $changes
*
* @throws QuoteException
* @throws ReservationException
@@ -50,7 +65,22 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
}
$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));
}
DB::transaction(function () use ($booking, $changes): void {
$booking->lockForTransition();
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
}
if (isset($changes['expected_version']) && $booking->offer_version !== (int) $changes['expected_version']) {
throw new ReservationException('Inzwischen wurde schon ein Angebot gesendet (Version '.$booking->offer_version.'). Es wurde nichts erneut gesendet.');
}
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
@@ -62,7 +92,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->quoteWithAdjustment($booking, $stay, $adjustment, $adjustmentLabel);
$quote = $this->quoteFor($booking, $stay, $adjustment, $adjustmentLabel);
if (filled($changes['guest'] ?? null)) {
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
@@ -80,23 +110,60 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
'total' => $quote->total(),
'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->property->hold_hours),
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? null,
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
]);
$booking->refresh();
$booking->update(['offer_hash' => OfferTerms::hash($booking)]);
});
$booking->refresh();
$this->contract->generate($booking, draft: true);
CaseLog::record($booking, 'document', 'Angebot Version '.$booking->offer_version.' erstellt'.(isset($booking->offer_terms['template']['name']) ? ' (Vorlage '.$booking->offer_terms['template']['name'].', Version '.$booking->offer_terms['template']['version'].')' : ' (Texte der Webseite)'), data: array_filter([
'kind' => DocumentKind::Offer->value,
'template' => $booking->offer_terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['name'].' (Version '.$annex['version'].')', (array) ($booking->offer_terms['annexes'] ?? [])),
'pdf_sha256' => $booking->offer_pdf_sha256,
'offer_hash' => $booking->offer_hash,
'confirmed' => $toConfirm,
]));
if ($sendMail) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new OfferMade($booking, $this->offerUrl($booking)));
$this->deliver($booking);
}
return $booking;
}
/**
* Sends the offer mail. The offer is already saved (and its validity runs), so a failing mail server is
* recorded in the admin inbox and reported to the caller instead of being lost.
*
* @throws ReservationException
*/
public function deliver(Booking $booking): void
{
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new OfferMade($booking, $this->offerUrl($booking)));
} catch (Throwable $exception) {
// Only class and booking id are logged: mail errors can contain the recipient's address.
Log::warning('Angebot nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
$this->inbox->post(
InboxMessageKind::OfferMailFailed,
'booking-'.$booking->id.':v'.$booking->offer_version,
'Angebot '.$booking->reference.' nicht zugestellt',
'Das Angebot ist gespeichert und der Zeitraum gehalten, aber die E-Mail konnte nicht versendet werden. Auf der Buchungsseite kann der Angebotslink kopiert und dem Gast anders übermittelt werden.',
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
propertyId: $booking->property_id,
);
throw new ReservationException('Das Angebot wurde gespeichert, aber die E-Mail konnte nicht versendet werden. Der Angebotslink kann über „Angebotslink“ kopiert werden.');
}
}
/**
* The guest's link to the offer page; valid while the offer is valid and only for this offer version.
*/
@@ -113,7 +180,7 @@ public function offerUrl(Booking $booking): string
*
* @throws QuoteException
*/
private function quoteWithAdjustment(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
public function quoteFor(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
{
$quote = $this->calculator->calculate($booking->property, $stay);
if ($adjustment === 0) {
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Actions;
use App\Exceptions\ReservationException;
use App\Mail\PaymentReminder;
use App\Models\BookingTask;
use Illuminate\Support\Facades\Mail;
/**
* Sends the payment mail belonging to a task – only when the landlord decides to, after checking the payment.
* The task is completed and the dispatch is recorded on the booking; a failing mail server leaves the task open.
*/
class SendPaymentReminder
{
/**
* @throws ReservationException
*/
public function handle(BookingTask $task, string $by): void
{
$reminder = $task->kind->reminder();
$booking = $task->booking->loadMissing(['guest', 'property', 'payments']);
if ($reminder === null) {
throw new ReservationException('Zu dieser Aufgabe gibt es keine Zahlungs-E-Mail.');
}
if (blank($booking->guest?->email)) {
throw new ReservationException('Der Gast hat keine E-Mail-Adresse.');
}
if ($booking->openAmount() <= 0) {
throw new ReservationException('Die Buchung ist bereits vollständig bezahlt.');
}
[$kind, $column] = $reminder;
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
$booking->update([$column => now()]);
$task->complete($by);
}
}
+82
View File
@@ -0,0 +1,82 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Process\CaseLog;
use Illuminate\Support\Facades\DB;
/**
* Manual status change for processes the system does not drive itself (bookings entered by hand, portal bookings):
* the landlord moves the booking along the stages and gives a reason, which is added to the internal notes.
* Cancelling and declining are separate actions (they inform people and record costs). Making a booking binding
* again checks the calendar like every other writer; no mail is sent and no contract is generated here.
*/
class SetBookingStatus
{
/** @var list<BookingStatus> */
public const TARGETS = [BookingStatus::Reserved, BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid, BookingStatus::Completed];
public function __construct(private AvailabilityChecker $availability) {}
/**
* @throws ReservationException
*/
public function handle(Booking $booking, BookingStatus $status, string $reason, string $by = 'Verwaltung'): Booking
{
if (! in_array($status, self::TARGETS, true)) {
throw new ReservationException('Auf diesen Status kann nicht von Hand gewechselt werden. Stornieren und Ablehnen haben eigene Aktionen.');
}
if ($status === BookingStatus::Reserved && in_array($booking->status, BookingStatus::occupying(), true)) {
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden. Soll sie enden, bitte „Beenden“ wählen – dann wird sie ordentlich storniert.');
}
if (blank(trim($reason))) {
throw new ReservationException('Bitte einen Grund für die Statusänderung angeben.');
}
DB::transaction(function () use ($booking, $status, $reason, $by): void {
$booking->lockForTransition();
$from = $booking->status;
if ($from === $status) {
throw new ReservationException('Die Buchung hat diesen Status bereits.');
}
if ($status === BookingStatus::Reserved && in_array($from, BookingStatus::occupying(), true)) {
throw new ReservationException('Eine verbindliche Buchung kann nicht wieder zur Anfrage gemacht werden.');
}
$becomesBinding = in_array($status, BookingStatus::occupying(), true) && ! in_array($from, BookingStatus::occupying(), true);
if ($becomesBinding && ! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$changes = ['status' => $status];
if ($becomesBinding) {
$changes += ['hold_expires_at' => null, 'confirmed_at' => $booking->confirmed_at ?? now(), 'cancelled_at' => null];
}
if ($status === BookingStatus::Reserved) {
$changes['hold_expires_at'] = null;
}
$line = now()->format('d.m.Y H:i').' '.$by.': Status von „'.$from->getLabel().'“ auf „'.$status->getLabel().'“ gesetzt – '.trim($reason);
CaseLog::context(fn () => $booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]), actor: $by, reason: 'Von Hand gesetzt: '.trim($reason));
// A booking taken back into the process no longer needs the cancellation follow-up.
if ($becomesBinding) {
BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)
->whereIn('kind', [BookingTaskKind::CancellationFee, BookingTaskKind::CancellationRequest])
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
}
});
return $booking->refresh();
}
}
+8 -8
View File
@@ -5,18 +5,16 @@
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Channels\Intake\PortalIntake;
use App\Enums\ChannelEchoBehavior;
use App\Mail\ChannelConflict;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
class SyncChannel
@@ -129,18 +127,20 @@ public function handle(Channel $channel): ChannelSyncLog
}
$warnings[] = $note;
}
array_push($conflicts, ...$foundConflicts);
foreach ($foundConflicts as $conflict) {
$conflicts[$conflict] ??= $block->starts_on;
}
}
$warnings = array_values(array_unique($warnings));
$locked->forceFill(['last_synced_at' => now(), 'last_success_at' => now(), 'last_error' => null,
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
});
if ($conflicts !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, array_values(array_unique($conflicts)))));
}
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
// One intake for all channels (package 4); a failure there never fails the sync itself.
rescue(fn () => app(PortalIntake::class)->afterSync($channel->fresh()));
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
'conflicts' => count(array_unique($conflicts)), 'warnings' => $warnings,
'conflicts' => count($conflicts), 'warnings' => $warnings,
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
} catch (ChannelSyncException $exception) {
$channel->forceFill(['last_synced_at' => now(), 'last_error_at' => now(), 'last_error' => $exception->getMessage()])->save();
+148
View File
@@ -0,0 +1,148 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\OccupationKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Guest;
use App\Models\Property;
use App\Pricing\PortalPrice;
use App\Process\CaseAutomation;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Takes over a booking that a portal already made binding (case types A3–A5): one case with the portal as origin
* channel (owner), its reference and the facts the portal delivered – nothing more. There is no offer and no second
* acceptance; the agreed portal price is taken over as it is; guest, number of guests and price may be unknown and
* stay unknown until somebody enters them. The case is binding at once and occupies the dates.
*
* Used for the manual entry ("Buchung von einem Portal") and for a reservation found in a portal calendar – then the
* calendar entry stays as the portal's mirror of the case.
*/
class TakeOverExternalBooking
{
public function __construct(private ConfirmBooking $confirm, private PortalPrice $price) {}
/**
* @param array{guest?: ?array<string, ?string>, guests?: ?int, portal_reference?: ?string, portal_total?: ?int, notes?: ?string, guest_confirmed?: bool, processing_mode?: ?ProcessingMode} $facts
*
* @throws ReservationException
*/
public function handle(Property $property, Channel $channel, CarbonImmutable $arrival, CarbonImmutable $departure, array $facts = [], ?BlockedPeriod $evidence = null): Booking
{
if ($channel->property_id !== $property->id) {
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
}
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Die Abreise muss nach der Anreise liegen.');
}
$booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $facts, $evidence): Booking {
Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if ($evidence !== null) {
$evidence = BlockedPeriod::query()->whereKey($evidence->id)->lockForUpdate()->firstOrFail();
$existing = $this->checkEvidence($evidence);
if ($existing !== null) {
return $existing;
}
}
$guests = isset($facts['guests']) && (int) $facts['guests'] > 0 ? (int) $facts['guests'] : null;
$guest = $evidence?->guest ?? $this->guestFrom((array) ($facts['guest'] ?? []));
$portalTotal = isset($facts['portal_total']) && $facts['portal_total'] !== '' ? (int) $facts['portal_total'] : null;
$reference = filled($facts['portal_reference'] ?? null) ? trim((string) $facts['portal_reference']) : ($evidence?->ical_interpretation['fields']['booking_reference'] ?? null);
$booking = $property->bookings()->create([
'guest_id' => $guest?->id,
'status' => BookingStatus::Reserved,
'source' => 'portal',
'intake' => IntakeKind::Booking,
'origin_channel_id' => $evidence?->origin_channel_id ?? $channel->id,
'portal_reference' => $reference,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $guests,
'hold_expires_at' => null,
'guest_confirmed_at' => ($facts['guest_confirmed'] ?? false) ? now() : null,
'internal_notes' => filled($facts['notes'] ?? null) ? trim((string) $facts['notes']) : null,
'processing_mode' => $facts['processing_mode'] ?? null,
...$this->price->columns($property, $arrival, $departure, $guests, $portalTotal, $channel->name),
]);
if ($evidence !== null) {
$evidence->forceFill([
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest?->id,
'review_note' => 'Als Vorgang übernommen; der Vorgang führt diese Belegung.',
])->save();
}
$this->confirm->bind($booking);
if ($evidence !== null) {
app(ReconcileChannelRepresentations::class)->handle($property);
}
return $booking->refresh();
});
app(CaseAutomation::class)->advance($booking);
return $booking->refresh();
}
/**
* A portal calendar entry can become a case once: returns the case it already belongs to, or throws when the entry
* is no reservation of a portal.
*
* @throws ReservationException
*/
private function checkEvidence(BlockedPeriod $evidence): ?Booking
{
if (! in_array($evidence->source, ['channel', 'email'], true) || $evidence->channel_id === null) {
throw new ReservationException('Übernehmen lassen sich nur Reservierungen aus einem Portalkalender.');
}
if ($evidence->occupationKind() === OccupationKind::Block) {
throw new ReservationException('Eine Sperrzeit ist keine Buchung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
}
if ($evidence->is_representation && $evidence->linked_booking_id !== null) {
return Booking::query()->findOrFail($evidence->linked_booking_id);
}
if ($evidence->is_representation) {
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Der Vorgang gehört an die führende Belegung.');
}
return null;
}
/**
* The guest the portal named – only with a real name. A known e-mail address finds the existing guest without
* overwriting his data; nothing is invented.
*
* @param array<string, ?string> $data
*/
private function guestFrom(array $data): ?Guest
{
$data = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']));
if (blank($data['first_name'] ?? null) || blank($data['last_name'] ?? null)) {
return null;
}
$email = filled($data['email'] ?? null) ? mb_strtolower($data['email']) : null;
if ($email !== null && ($known = Guest::query()->where('email', $email)->whereNull('anonymized_at')->first()) !== null) {
return $known;
}
return Guest::query()->create([...array_filter($data, fn ($value) => $value !== null), 'email' => $email ?? '']);
}
}
+63
View File
@@ -0,0 +1,63 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\Booking;
use App\Models\Channel;
use App\Process\CaseAutomation;
use App\Process\ProcessSettings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* A non-binding request through a portal (case type A2) as it arrives: dates and the portal's reference, nothing
* invented. Guest, number of guests and price stay unknown until the landlord enters them; the case then asks for
* exactly that and continues like a request of the own website. Whether the dates are reserved follows the channel's
* settings for requests.
*/
class TakeOverPortalInquiry
{
public function __construct(private AvailabilityChecker $availability, private ProcessSettings $settings) {}
/**
* @throws ReservationException
*/
public function handle(Channel $channel, CarbonImmutable $arrival, CarbonImmutable $departure, ?string $reference = null, ?string $notes = null, ?ProcessingMode $processingMode = null): Booking
{
$property = $channel->property;
if ($departure->lessThanOrEqualTo($arrival)) {
throw new ReservationException('Die Abreise muss nach der Anreise liegen.');
}
$booking = DB::transaction(function () use ($property, $channel, $arrival, $departure, $reference, $notes, $processingMode): Booking {
$property->newQuery()->whereKey($property->id)->lockForUpdate()->firstOrFail();
if (! $this->availability->isAvailable($property, $arrival, $departure)) {
throw ReservationException::notAvailable();
}
$profile = $this->settings->resolve($property, $channel, IntakeKind::Inquiry);
return $property->bookings()->create([
'status' => BookingStatus::Reserved,
'source' => 'portal',
'intake' => IntakeKind::Inquiry,
'origin_channel_id' => $channel->id,
'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,
]);
});
app(CaseAutomation::class)->advance($booking);
return $booking->refresh();
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Availability;
use App\Actions\SyncChannel;
use App\Enums\ChannelBookingModel;
use App\Models\Channel;
use App\Models\ChannelExportRequest;
use App\Models\Property;
use Carbon\CarbonInterface;
use Illuminate\Support\Collection;
use Throwable;
/**
* Whether the calendars of the connected portals are good enough to commit to a stay without a human looking.
*
* Two kinds of evidence, both taken from what the synchronisation already records:
* - import: the last successful import of every importing channel is recent (otherwise one import is tried first);
* - export: a channel that can book instantly (booking model portal booking / mixed) has fetched OUR feed after the
* block was created. The feed is built from the database on every request, so a successful fetch of that channel's
* own token after the block existed contains it. This proves delivery, not that the portal has processed it –
* the remaining risk is documented in BOOKING-E2E-IMPLEMENTATION.md.
*
* Network access happens only in {@see refresh()} and never inside a database transaction.
*/
class CalendarClearance
{
public function __construct(private SyncChannel $sync) {}
/**
* @return Collection<int, Channel>
*/
public function staleImports(Property $property): Collection
{
$limit = now()->subMinutes((int) config('fewo.channels.fresh_within_minutes'));
return $property->channels()->active()->get()
->filter(fn (Channel $channel): bool => $channel->importsOccupations())
->filter(fn (Channel $channel): bool => $channel->last_success_at === null || $channel->last_success_at->lessThan($limit))
->values();
}
/**
* Imports the channels whose calendar is not recent (one attempt each); failures stay visible as stale.
*/
public function refresh(Property $property): void
{
foreach ($this->staleImports($property) as $channel) {
try {
$this->sync->handle($channel);
} catch (Throwable) {
// The sync log records the failure; the channel simply stays stale.
}
}
}
/**
* Instant-booking channels that have not fetched our feed since the block exists.
*
* @return Collection<int, Channel>
*/
public function unprovenInstantChannels(Property $property, CarbonInterface $blockedSince): Collection
{
return $property->channels()->active()->get()
->filter(fn (Channel $channel): bool => $this->canBookInstantly($channel))
->reject(fn (Channel $channel): bool => $channel->exportsOccupations() && $this->fetchedFeedSince($channel, $blockedSince))
->values();
}
public function canBookInstantly(Channel $channel): bool
{
return in_array($channel->booking_model, [ChannelBookingModel::PortalBooking, ChannelBookingModel::Mixed], true);
}
/**
* Reasons (German, for the admin) why the calendar state cannot be trusted yet; empty = cleared.
*
* @return list<string>
*/
public function reasons(Property $property, CarbonInterface $blockedSince): array
{
$reasons = [];
foreach ($this->staleImports($property) as $channel) {
$reasons[] = "Kalenderstand von {$channel->name} ist nicht aktuell (letzter erfolgreicher Import: ".($channel->last_success_at?->format('d.m.Y, H:i') ?? 'nie').').';
}
foreach ($this->unprovenInstantChannels($property, $blockedSince) as $channel) {
$reasons[] = $channel->exportsOccupations()
? "{$channel->name} (Sofortbuchung) hat unseren Kalender seit der Sperre noch nicht abgerufen."
: "Der Kalenderexport an {$channel->name} (Sofortbuchung) ist nicht aktiv.";
}
return $reasons;
}
private function fetchedFeedSince(Channel $channel, CarbonInterface $blockedSince): bool
{
return ChannelExportRequest::query()
->where('channel_id', $channel->id)
->where('requested_at', '>=', $blockedSince->copy()->addSecond())
->where('response_status', 200)
->where('export_state', 'live')
->exists();
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace App\Availability;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
/**
* The next bookable stays from tomorrow on, for the "next free dates" in the hero section: free nights
* that the PriceCalculator accepts (minimum stay, offers applied), at least $nights long, not overlapping.
* Cached briefly per apartment because each candidate is a full price calculation (dates as strings: the cache
* does not unserialize objects).
*/
class NextFreeStays
{
public const HORIZON_DAYS = 120;
public const MAX_NIGHTS = 7;
public function __construct(
private AvailabilityChecker $availability,
private PriceCalculator $calculator,
) {}
/**
* @return list<array{arrival: CarbonImmutable, departure: CarbonImmutable, nights: int, total: int, url: string}>
*/
public function for(Property $property, int $count = 3, int $nights = 3, int $guests = 2): array
{
$key = "next-free-stays:{$property->id}:{$count}:{$nights}:{$guests}:".today()->toDateString();
$stays = Cache::remember($key, now()->addMinutes(10), fn (): array => $this->find($property, $count, $nights, min($guests, $property->max_guests)));
return array_map(fn (array $stay): array => [
...$stay,
'arrival' => CarbonImmutable::parse($stay['arrival']),
'departure' => CarbonImmutable::parse($stay['departure']),
], $stays);
}
/**
* @return list<array{arrival: string, departure: string, nights: int, total: int, url: string}>
*/
private function find(Property $property, int $count, int $nights, int $guests): array
{
$from = CarbonImmutable::tomorrow();
$until = $from->addDays(self::HORIZON_DAYS + self::MAX_NIGHTS);
$occupied = $this->availability->occupiedNights($property, $from, $until);
$stays = [];
for ($arrival = $from; count($stays) < $count && $arrival->lessThan($from->addDays(self::HORIZON_DAYS)); $arrival = $arrival->addDay()) {
if (isset($occupied[$arrival->toDateString()])) {
continue;
}
$quote = $this->firstPricedStay($property, $arrival, $nights, $guests, $occupied);
if ($quote === null) {
continue;
}
$stays[] = [
'arrival' => $quote->arrival->toDateString(),
'departure' => $quote->departure->toDateString(),
'nights' => $quote->nights(),
'total' => $quote->total(),
'url' => route('booking.create', ['anreise' => $quote->arrival->toDateString(), 'abreise' => $quote->departure->toDateString(), 'personen' => $guests]),
];
$arrival = $quote->departure->subDay();
}
return $stays;
}
/**
* The shortest stay of at least $nights from $arrival that is free and priceable, if any.
*
* @param array<string, true> $occupied
*/
private function firstPricedStay(Property $property, CarbonImmutable $arrival, int $nights, int $guests, array $occupied): ?PriceQuote
{
for ($length = 1; $length <= self::MAX_NIGHTS; $length++) {
if (isset($occupied[$arrival->addDays($length - 1)->toDateString()])) {
return null;
}
if ($length < $nights) {
continue;
}
try {
return $this->calculator->calculate($property, new StayRequest($arrival, $arrival->addDays($length), $guests));
} catch (QuoteException) {
continue;
}
}
return null;
}
}
+3 -2
View File
@@ -45,7 +45,8 @@ public function records(?int $propertyId = null, ?int $guestId = null, bool $inc
'source' => $booking->bookingChannelLabel(), 'status' => $booking->status->getLabel(),
'status_key' => $booking->status->value, 'color' => $booking->status->getColor(),
'occupies' => in_array($booking->status, BookingStatus::occupying(), true) || $booking->isHoldActive(),
'needs_review' => false, 'review_note' => null, 'reason' => null, 'archived' => false,
'needs_review' => false, 'review_note' => null, 'reason' => null, 'archived' => false, 'archived_booking' => $booking->archived_at !== null,
'channel_id' => $booking->origin_channel_id ?? $booking->import_channel_id,
'representations' => $booking->channel_representations_count,
'mirrored_channels' => $booking->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
'url' => BookingResource::getUrl('view', ['record' => $booking->id]),
@@ -74,7 +75,7 @@ public function records(?int $propertyId = null, ?int $guestId = null, bool $inc
'status' => $block->trashed() ? 'Nicht mehr im Kalenderfeed' : ($block->needs_review ? 'Klärung erforderlich' : 'Im Kalender geführt'),
'status_key' => $block->trashed() ? 'archived' : 'imported', 'color' => $block->needs_review ? 'warning' : $kind->getColor(),
'occupies' => ! $block->trashed(), 'needs_review' => $block->needs_review, 'review_note' => $block->review_note, 'reason' => $block->blockDescription(),
'archived' => $block->trashed(), 'representations' => $block->channel_representations_count,
'archived' => $block->trashed(), 'archived_booking' => false, 'channel_id' => $block->origin_channel_id ?? $block->channel_id, 'representations' => $block->channel_representations_count,
'mirrored_channels' => $block->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]),
'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null,
+1 -1
View File
@@ -21,7 +21,7 @@ public function conflictsFor(BlockedPeriod $block): array
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guestName()}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
$blocks = $property->blockedPeriods()
->occupying()
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Channels\Intake;
use App\Enums\CaseType;
use App\Enums\IntakeOutcome;
use App\Models\Booking;
/**
* What the intake recognised in one incoming portal event, with its reasons in plain words.
*/
final class IntakeDecision
{
/**
* @param list<string> $reasons why the intake decided so
* @param list<string> $missing what the new case will not know yet
*/
public function __construct(
public readonly IntakeOutcome $outcome,
public readonly array $reasons = [],
public readonly ?Booking $booking = null,
public readonly ?CaseType $caseType = null,
public readonly array $missing = [],
public readonly ?string $reference = null,
) {}
public function withBooking(Booking $booking): self
{
return new self($this->outcome, $this->reasons, $booking, $this->caseType ?? $booking->case_type, $this->missing, $this->reference);
}
/**
* @param list<string> $reasons
*/
public function as(IntakeOutcome $outcome, array $reasons): self
{
return new self($outcome, $reasons, $this->booking, $this->caseType, $this->missing, $this->reference);
}
}
+489
View File
@@ -0,0 +1,489 @@
<?php
namespace App\Channels\Intake;
use App\Actions\ReconcileChannelRepresentations;
use App\Actions\TakeOverExternalBooking;
use App\Actions\TakeOverPortalInquiry;
use App\Channels\Mail\ParsedPortalMail;
use App\Enums\BookingStatus;
use App\Enums\BookingTaskKind;
use App\Enums\BookingTaskStatus;
use App\Enums\CaseIntakeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\IntakeKind;
use App\Enums\IntakeOutcome;
use App\Enums\OccupationKind;
use App\Enums\ProcessingMode;
use App\Exceptions\ReservationException;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\BookingTask;
use App\Models\Channel;
use App\Models\IntakeObservation;
use App\Models\PortalEmail;
use App\Pricing\QuoteException;
use App\Process\CaseLog;
use App\Process\ProcessSettings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
use Throwable;
/**
* The one intake for bookings and requests from portals (UMSETZUNGSPLAN_v0.10 §5.5, package 4). Every incoming event –
* an entry of a portal calendar, a booking, request or cancellation e-mail – is judged the same way:
*
* - **Same case first** (no duplicates): an entry already linked to a case; the portal's booking reference; the same
* portal with exactly the same nights; the calendar mirror of an entry that belongs to a case. Different references
* or overlapping but different dates are never merged – they are clarified.
* - **New case only when certain**: a booking e-mail of the portal with dates and reference, or a calendar entry that
* the channel's rules recognise as a reservation booked at this portal (or that the landlord classified so). Blocks,
* mirrors of other portals, own use and unrecognised entries never become cases by themselves.
* - **Reports about known cases** (cancellation e-mail, entry gone from the calendar, other dates) become a task on the
* case and an entry in its history – the case itself is never cancelled, released or changed here (E-019).
*
* What happens then depends on the channel ({@see CaseIntakeMode}): nothing (off), only a record (observe), or the
* cases and tasks are created (create; continue additionally lets the new cases follow the automatic handling).
* Creating a case never sends anything the landlord did not release (package 3).
*/
class PortalIntake
{
public const LINK_NOTE = 'Automatisch dem Vorgang zugeordnet; der Vorgang führt diese Belegung.';
public function __construct(
private TakeOverExternalBooking $takeOver,
private TakeOverPortalInquiry $inquiry,
private ProcessSettings $settings,
) {}
/**
* Judges one portal calendar entry or e-mail block without changing anything.
*/
public function evaluate(BlockedPeriod $block): IntakeDecision
{
$block->loadMissing(['channel', 'property', 'canonicalBlock', 'linkedBooking']);
$channel = $block->channel;
$reference = self::reference($block);
if ($channel === null || ! in_array($block->source, ['channel', 'email'], true)) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Kein importierter Portaleintrag.'], reference: $reference);
}
if ($block->trashed()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Nicht mehr im Kalender des Portals.'], reference: $reference);
}
if ($block->linked_booking_id !== null && $block->linkedBooking !== null) {
return new IntakeDecision(IntakeOutcome::Link, ['Bereits dem Vorgang zugeordnet.'], $block->linkedBooking, reference: $reference);
}
if ($block->is_representation) {
$leaderCase = $block->canonicalBlock?->linkedBooking;
return $leaderCase !== null
? new IntakeDecision(IntakeOutcome::Link, ['Spiegelung einer Belegung, die zu diesem Vorgang gehört.'], $leaderCase, reference: $reference)
: new IntakeDecision(IntakeOutcome::Ignore, ['Spiegelung einer anderen Belegung, keine eigene Buchung.'], reference: $reference);
}
if ($reference !== null && ($case = $this->caseByReference($channel, $reference)) !== null) {
return new IntakeDecision(IntakeOutcome::Link, ['Gleiche Buchungsnummer '.$reference.' wie der Vorgang.'], $case, reference: $reference);
}
if ($block->ends_on->lessThanOrEqualTo(CarbonImmutable::today())) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $reference);
}
if ($block->occupationKind() === OccupationKind::Block) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Als Sperrzeit eingeordnet (z. B. Spiegelung, eigene Nutzung oder Wartung).'], reference: $reference);
}
if ($block->is_private) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Als private Belegung eingeordnet.'], reference: $reference);
}
$origin = $block->origin_channel_id;
if ($origin !== null && $origin !== $channel->id) {
$case = $this->caseWithSameNights($block, $origin);
return $case !== null
? new IntakeDecision(IntakeOutcome::Link, ['Laut Kalender über ein anderes Portal gebucht; dort gibt es den Vorgang mit genau diesen Nächten.'], $case, reference: $reference)
: new IntakeDecision(IntakeOutcome::Clarify, ['Laut Kalender über ein anderes Portal gebucht – der Vorgang entsteht dort, nicht hier.'], reference: $reference);
}
$case = $this->caseWithSameNights($block, $channel->id);
if ($case !== null) {
return filled($case->portal_reference) && $reference !== null && $case->portal_reference !== $reference
? new IntakeDecision(IntakeOutcome::Clarify, ['Gleiche Nächte wie Vorgang '.$case->reference.', aber andere Buchungsnummer ('.$reference.' / '.$case->portal_reference.').'], reference: $reference)
: new IntakeDecision(IntakeOutcome::Link, ['Dasselbe Portal mit genau denselben Nächten wie Vorgang '.$case->reference.'.'], $case, reference: $reference);
}
$overlap = Booking::query()->occupying()->where('property_id', $block->property_id)->overlapping($block->starts_on, $block->ends_on)->first();
if ($overlap !== null) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Überschneidet sich mit Vorgang '.$overlap->reference.' ('.$overlap->arrival->format('d.m.').'–'.$overlap->departure->format('d.m.Y').'), ohne dieselbe Buchung zu sein.'], reference: $reference);
}
$sameChannelOverlap = $channel->blockedPeriods()->occupying()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists();
if ($sameChannelOverlap) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Weitere Einträge desselben Portals überschneiden sich – keine Zusammenführung nach Terminen.'], reference: $reference);
}
$certainty = $this->certainty($block, $reference);
if ($certainty !== null) {
return new IntakeDecision(IntakeOutcome::Clarify, [$certainty], reference: $reference);
}
if ($channel->booking_model === ChannelBookingModel::Inquiry) {
return new IntakeDecision(IntakeOutcome::Clarify, ['Über dieses Portal kommen laut Einstellung nur Anfragen – eine feste Buchung bitte bestätigen.'], reference: $reference);
}
$profile = $this->settings->resolve($block->property, $channel, IntakeKind::Booking);
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
return new IntakeDecision(
IntakeOutcome::Create,
[$block->source === 'email' ? 'Buchungsmail von '.$channel->name.' mit Zeitraum und Buchungsnummer.' : 'Kalendereintrag nach Regel „'.($block->ical_interpretation['rule'] ?? 'persönlich eingeordnet').'“ als Buchung bei '.$channel->name.' erkannt.'],
caseType: $profile->caseType,
missing: array_values(array_filter([
blank($fields['guest_full_name'] ?? null) ? 'Name des Gastes' : 'Name des Gastes (nur als Hinweis aus dem Kalender)',
'E-Mail-Adresse des Gastes',
'Personenzahl',
'Gesamtpreis laut Portal',
$reference === null ? 'Buchungsnummer' : null,
])),
reference: $reference,
);
}
/**
* Judges an entry and acts as the channel allows: records what was recognised and – only when the channel creates
* cases – creates the case, links the entry to its case or marks it for clarification.
*/
public function process(BlockedPeriod $block, string $source): IntakeDecision
{
$channel = $block->channel;
$mode = $channel?->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']);
}
$decision = $this->evaluate($block);
$applied = false;
if ($mode->creates()) {
[$decision, $applied] = match ($decision->outcome) {
IntakeOutcome::Create => $this->create($block, $decision, $mode, $source),
IntakeOutcome::Link => [$decision, $this->link($block, $decision->booking, $decision->reasons[0] ?? '')],
IntakeOutcome::Clarify => [$decision, $this->flag($block, $decision->reasons[0] ?? '')],
default => [$decision, false],
};
}
$this->record($channel, $mode, $source, $decision, $applied, $block, null, $block->starts_on, $block->ends_on);
return $decision;
}
/**
* Takes over an existing portal entry by an explicit run of the landlord or operator (stock adoption), whatever the
* channel's switch says: certain bookings become cases (released by hand, never automatic), entries of known cases
* are linked, everything else is only reported.
*/
public function adopt(BlockedPeriod $block): IntakeDecision
{
$decision = $this->evaluate($block);
$applied = false;
if ($decision->outcome === IntakeOutcome::Create) {
[$decision, $applied] = $this->create($block, $decision, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION);
} elseif ($decision->outcome === IntakeOutcome::Link) {
$applied = $this->link($block, $decision->booking, $decision->reasons[0] ?? '');
}
$this->record($block->channel, CaseIntakeMode::Create, IntakeObservation::SOURCE_ADOPTION, $decision, $applied, $block, null, $block->starts_on, $block->ends_on);
return $decision;
}
/**
* After a calendar sync: new or changed entries of the channel go through the intake; entries of known cases that
* disappeared or show other nights become reports on the case.
*/
public function afterSync(Channel $channel): void
{
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return;
}
$open = $channel->blockedPeriods()->whereIn('source', ['channel', 'email'])->whereNull('linked_booking_id')
->where('is_representation', false)->whereDate('ends_on', '>', CarbonImmutable::today())->orderBy('starts_on')->get();
foreach ($open as $block) {
$this->process($block, IntakeObservation::SOURCE_CALENDAR);
}
$linked = $channel->blockedPeriods()->withTrashed()->with('linkedBooking')->where('source', 'channel')->whereNotNull('linked_booking_id')
->whereHas('linkedBooking', fn ($query) => $query->whereIn('status', BookingStatus::occupying())->whereDate('departure', '>', CarbonImmutable::today()))->get();
foreach ($linked as $block) {
$case = $block->linkedBooking;
if ($block->trashed()) {
$this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, 'Der Eintrag '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').' ist aus dem Kalender von '.$channel->name.' verschwunden. Das kann eine Stornierung sein, ist aber kein Nachweis – bitte im Portal prüfen.', 'gone:'.$block->id, IntakeObservation::SOURCE_CALENDAR, $block);
} elseif (! $block->starts_on->equalTo($case->arrival) || ! $block->ends_on->equalTo($case->departure)) {
$this->report($channel, $mode, $case, IntakeOutcome::ChangeSignal, 'Der Kalender von '.$channel->name.' meldet '.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').', der Vorgang hat '.$case->arrival->format('d.m.').'–'.$case->departure->format('d.m.Y').'. Bitte prüfen, ob die Buchung im Portal geändert wurde.', 'dates:'.$block->id.':'.$block->starts_on->toDateString().':'.$block->ends_on->toDateString(), IntakeObservation::SOURCE_CALENDAR, $block);
}
}
}
/**
* A portal e-mail reporting a cancellation: the case learns about it as a task; nothing is cancelled.
*
* @return Booking|null the case the report belongs to
*/
public function cancellationMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): ?Booking
{
$case = $parsed->reference !== null ? $this->caseByReference($channel, $parsed->reference) : null;
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if ($case === null || ! $case->isBinding()) {
$this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, new IntakeDecision(IntakeOutcome::Clarify, [$parsed->reference === null ? 'Stornierungsmail ohne Buchungsnummer – keinem Vorgang sicher zuzuordnen.' : 'Kein gebuchter Vorgang mit der Buchungsnummer '.$parsed->reference.'.'], reference: $parsed->reference), false, null, $mail, $parsed->startsOn, $parsed->endsOn);
return null;
}
$this->report($channel, $mode, $case, IntakeOutcome::CancellationSignal, $channel->name.' meldet eine Stornierung (E-Mail „'.$mail->subject.'“). Bitte prüfen Sie die Buchung und die nächsten Schritte.', 'mail:'.$mail->message_id, IntakeObservation::SOURCE_MAIL, null, $mail);
return $case;
}
/**
* A request e-mail of a portal: a request case with the dates and the reference (A2), when the channel creates
* cases; otherwise only recorded.
*/
public function inquiryMail(Channel $channel, ParsedPortalMail $parsed, PortalEmail $mail): IntakeDecision
{
$mode = $channel->case_intake ?? CaseIntakeMode::Off;
if (! $mode->records()) {
return new IntakeDecision(IntakeOutcome::Ignore, ['Automatische Übernahme ist für dieses Portal aus.']);
}
$profile = $this->settings->resolve($channel->property, $channel, IntakeKind::Inquiry);
$decision = match (true) {
! $parsed->hasPeriod() => new IntakeDecision(IntakeOutcome::Clarify, ['Anfrage erkannt, aber An- und Abreise nicht sicher lesbar.'], reference: $parsed->reference),
$parsed->reference !== null && ($case = $this->caseByReference($channel, $parsed->reference)) !== null => new IntakeDecision(IntakeOutcome::Link, ['Gleiche Anfragenummer '.$parsed->reference.' wie der Vorgang.'], $case, reference: $parsed->reference),
$parsed->endsOn->lessThanOrEqualTo(CarbonImmutable::today()) => new IntakeDecision(IntakeOutcome::Ignore, ['Liegt in der Vergangenheit.'], reference: $parsed->reference),
default => new IntakeDecision(IntakeOutcome::Inquiry, ['Anfrage-Mail von '.$channel->name.' mit Zeitraum.'], caseType: $profile->caseType, missing: ['Name und E-Mail-Adresse des Gastes', 'Personenzahl'], reference: $parsed->reference),
};
$applied = false;
if ($mode->creates() && $decision->outcome === IntakeOutcome::Inquiry) {
try {
$case = $this->inquiry->handle($channel, $parsed->startsOn, $parsed->endsOn, $parsed->reference, 'Automatisch aus der Anfrage-Mail von '.$channel->name.' übernommen („'.$mail->subject.'“).', $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null);
CaseLog::record($case, 'intake', 'Automatisch aus der Anfrage-Mail von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => IntakeObservation::SOURCE_MAIL, 'message_id' => $mail->message_id]);
$decision = $decision->withBooking($case);
$applied = true;
} catch (ReservationException|QuoteException $exception) {
$decision = $decision->as(IntakeOutcome::Clarify, ['Anfrage nicht automatisch übernommen: '.$exception->getMessage()]);
}
}
$this->record($channel, $mode, IntakeObservation::SOURCE_MAIL, $decision, $applied, null, $mail, $parsed->startsOn, $parsed->endsOn);
return $decision;
}
/**
* The portal's booking reference of an entry: extracted by the calendar rules, or the one of a booking e-mail.
*/
public static function reference(BlockedPeriod $block): ?string
{
$fromRules = $block->ical_interpretation['fields']['booking_reference'] ?? null;
if (filled($fromRules)) {
return trim((string) $fromRules);
}
if ($block->source === 'email' && str_starts_with((string) $block->external_uid, 'email:')) {
$reference = substr((string) $block->external_uid, 6);
// Mails without a reference got a random identifier, which is no booking reference.
return preg_match('/^[0-9a-f]{32}$/', $reference) === 1 ? null : $reference;
}
return null;
}
/**
* The case of a portal booking with this reference: on the case itself or on an entry that belongs to a case.
*/
public function caseByReference(Channel $channel, string $reference): ?Booking
{
$case = Booking::query()->where('portal_reference', $reference)
->where(fn ($query) => $query->where('origin_channel_id', $channel->id)->orWhere('import_channel_id', $channel->id))
->orderBy('id')->first();
if ($case !== null) {
return $case;
}
$linked = $channel->blockedPeriods()->withTrashed()->whereNotNull('linked_booking_id')
->whereIn('external_uid', [$reference, 'email:'.$reference])->value('linked_booking_id');
return $linked !== null ? Booking::query()->find($linked) : null;
}
/**
* The one occupying case of this portal with exactly these nights (more than one: none – that is for a person).
*/
private function caseWithSameNights(BlockedPeriod $block, int $channelId): ?Booking
{
/** @var Collection<int, Booking> $cases */
$cases = Booking::query()->occupying()->where('property_id', $block->property_id)
->whereDate('arrival', $block->starts_on)->whereDate('departure', $block->ends_on)
->where(fn ($query) => $query->where('origin_channel_id', $channelId)->orWhere('import_channel_id', $channelId))
->get();
return $cases->count() === 1 ? $cases->first() : null;
}
/**
* Null when the entry is certainly a booking of its portal, otherwise why not.
*/
private function certainty(BlockedPeriod $block, ?string $reference): ?string
{
if ($block->needs_review && ! in_array($block->review_note, [ReconcileChannelRepresentations::OVERLAP_NOTE], true)) {
return 'Prüfhinweis am Eintrag: '.($block->review_note ?? 'bitte prüfen').'.';
}
if ($block->source === 'email') {
return $reference === null ? 'Buchungsmail ohne Buchungsnummer – ohne Nummer lässt sich ein späterer Kalendereintrag nicht sicher zuordnen.' : null;
}
// Classified by the landlord as a reservation booked at this portal.
if ($block->occupation_kind === OccupationKind::Reservation && $block->reviewed_at !== null && $block->origin_channel_id === $block->channel_id) {
return null;
}
$interpretation = (array) ($block->ical_interpretation ?? []);
if (! ($interpretation['matched'] ?? false)) {
return 'Kein Kalendermerkmal erkannt – eine reine Belegt-Meldung ist kein Nachweis einer Buchung.';
}
if (($interpretation['event_type'] ?? null) !== 'portal_reservation') {
return 'Die Regel „'.($interpretation['rule'] ?? '').'“ ordnet den Eintrag nicht als Buchung ein.';
}
if (($interpretation['representation'] ?? null) !== 'leading_candidate' || $block->origin_channel_id !== $block->channel_id) {
return 'Die Regel erkennt eine Reservierung, aber nicht sicher als Buchung bei diesem Portal.';
}
return null;
}
/**
* @return array{IntakeDecision, bool}
*/
private function create(BlockedPeriod $block, IntakeDecision $decision, CaseIntakeMode $mode, string $source): array
{
$channel = $block->channel;
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
$name = trim((string) ($fields['guest_full_name'] ?? $fields['guest_first_name'] ?? ''));
$origin = match ($source) {
IntakeObservation::SOURCE_MAIL => 'der Buchungsmail',
IntakeObservation::SOURCE_ADOPTION => 'dem Bestand der Portalbelegungen',
default => 'dem Kalender',
};
try {
$case = $this->takeOver->handle($block->property, $channel, CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), [
'portal_reference' => $decision->reference,
'notes' => 'Automatisch aus '.$origin.' von '.$channel->name.' übernommen.'.($name !== '' ? ' Name laut Portal: '.$name.'.' : ''),
'processing_mode' => $mode === CaseIntakeMode::Create ? ProcessingMode::Manual : null,
], $block);
} catch (ReservationException $exception) {
$this->flag($block, 'Nicht automatisch übernommen: '.$exception->getMessage());
return [$decision->as(IntakeOutcome::Clarify, ['Nicht automatisch übernommen: '.$exception->getMessage()]), false];
}
CaseLog::record($case, 'intake', 'Automatisch aus '.$origin.' von '.$channel->name.' angelegt', actor: CaseLog::SYSTEM, data: ['source' => $source, 'blocked_period_id' => $block->id, 'reference' => $decision->reference]);
return [$decision->withBooking($case), true];
}
/**
* Makes the entry a mirror of its case (the case leads availability and export).
*/
private function link(BlockedPeriod $block, ?Booking $case, string $reason): bool
{
if ($case === null || $block->linked_booking_id === $case->id || $block->is_representation) {
return false;
}
$block->forceFill([
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
'linked_booking_id' => $case->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
'occupation_kind' => OccupationKind::Reservation, 'review_note' => self::LINK_NOTE,
])->save();
app(ReconcileChannelRepresentations::class)->handle($block->property);
CaseLog::record($case, 'intake', 'Weitere Quelle zugeordnet: '.($block->source === 'email' ? 'E-Mail' : 'Kalender').' von '.$block->channel?->name.' ('.$block->starts_on->format('d.m.').'–'.$block->ends_on->format('d.m.Y').')', $reason, actor: CaseLog::SYSTEM, data: ['blocked_period_id' => $block->id]);
return true;
}
/**
* Puts an uncertain entry in front of the landlord ("Zu erledigen") with the reason.
*/
private function flag(BlockedPeriod $block, string $reason): bool
{
if ($block->needs_review || $block->reviewed_at !== null) {
return false;
}
$block->forceFill(['needs_review' => true, 'review_note' => mb_substr($reason, 0, 250)])->saveQuietly();
return true;
}
/**
* A report of the portal about a known case: a task and an entry in the history – once per report.
*/
private function report(Channel $channel, CaseIntakeMode $mode, Booking $case, IntakeOutcome $outcome, string $message, string $key, string $source, ?BlockedPeriod $block = null, ?PortalEmail $mail = null): void
{
$fingerprint = hash('sha256', $channel->id.'|signal|'.$key);
$known = $case->events()->where('type', 'portal_signal')->get()->contains(fn ($event): bool => ($event->data['fingerprint'] ?? null) === $fingerprint);
$applied = false;
if ($mode->creates() && ! $known) {
$kind = $outcome === IntakeOutcome::CancellationSignal ? BookingTaskKind::PortalCancellationReported : BookingTaskKind::PortalChangeReported;
$task = BookingTask::query()->firstOrNew(['booking_id' => $case->id, 'kind' => $kind]);
$task->forceFill(['tenant_id' => $case->tenant_id, 'status' => BookingTaskStatus::Open, 'due_on' => today(), 'note' => mb_substr($message, 0, 1000), 'completed_by' => null, 'completed_at' => null])->save();
CaseLog::record($case, 'portal_signal', $message, actor: $channel->name, data: ['fingerprint' => $fingerprint, 'source' => $source]);
$applied = true;
}
$this->record($channel, $mode, $source, new IntakeDecision($outcome, [$message], $case, $case->case_type), $applied, $block, $mail, $block?->starts_on ?? $case->arrival, $block?->ends_on ?? $case->departure, $key);
}
/**
* Records the decision once per event and result (repeated syncs and mails add nothing).
*/
private function record(?Channel $channel, CaseIntakeMode $mode, string $source, IntakeDecision $decision, bool $applied, ?BlockedPeriod $block, ?PortalEmail $mail, mixed $startsOn, mixed $endsOn, ?string $key = null): void
{
if ($channel === null || ! $mode->records()) {
return;
}
$fingerprint = hash('sha256', implode('|', [
$channel->id, $mode->value, $decision->outcome->value, $key ?? '',
$block?->id ?? '', $mail?->message_id ?? '', $decision->booking?->id ?? '',
$startsOn instanceof \DateTimeInterface ? $startsOn->format('Y-m-d') : (string) $startsOn,
$endsOn instanceof \DateTimeInterface ? $endsOn->format('Y-m-d') : (string) $endsOn,
]));
try {
$observation = IntakeObservation::query()->firstOrNew(['fingerprint' => $fingerprint]);
if ($observation->exists) {
return;
}
$observation->fill([
'channel_id' => $channel->id, 'blocked_period_id' => $block?->id, 'portal_email_id' => $mail?->id,
'booking_id' => $decision->booking?->id, 'source' => $source, 'mode' => $mode, 'outcome' => $decision->outcome,
'applied' => $applied, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference,
'starts_on' => $startsOn, 'ends_on' => $endsOn, 'reasons' => $decision->reasons, 'missing' => $decision->missing,
'occurred_at' => now(),
]);
$observation->tenant_id = $channel->tenant_id;
$observation->save();
} catch (Throwable $exception) {
// The record must never stop the intake itself.
report($exception);
}
}
}
@@ -0,0 +1,123 @@
<?php
namespace App\Console\Commands;
use App\Channels\Intake\PortalIntake;
use App\Enums\ChannelTaskStatus;
use App\Enums\IntakeOutcome;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
#[Signature('channels:adopt-occupations
{--channel=* : Nur diese Kanal-IDs}
{--apply : Wirklich übernehmen (ohne: nur Vorschau)}
{--revert= : Eine frühere Übernahme anhand ihres Berichts zurücknehmen}')]
#[Description('Bestehende Portalbelegungen ohne Vorgang prüfen und – nur mit --apply – als Vorgang übernehmen bzw. dem vorhandenen Vorgang zuordnen (Bericht, wiederholbar, rücknehmbar)')]
class AdoptPortalOccupations extends Command
{
private const DIRECTORY = 'intake-adoptions';
/** Attributes of an entry that an adoption changes and a revert restores. */
private const RESTORED = ['is_representation', 'representation_automatic', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'needs_review', 'reviewed_at', 'occupation_kind', 'guest_id', 'review_note'];
public function handle(TenantRunner $runner, PortalIntake $intake): int
{
if (filled($this->option('revert'))) {
return $this->revert((string) $this->option('revert'));
}
$apply = (bool) $this->option('apply');
$report = ['run' => now()->format('Ymd-His'), 'apply' => $apply, 'entries' => [], 'channel_task_ids' => []];
$firstTask = (int) ChannelTask::query()->withoutGlobalScopes()->max('id');
$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();
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();
foreach ($entries as $entry) {
$before = collect(self::RESTORED)->mapWithKeys(fn (string $field): array => [$field => $entry->getRawOriginal($field)])->all();
$decision = $apply ? $intake->adopt($entry) : $intake->evaluate($entry);
$created = $apply && $decision->outcome === IntakeOutcome::Create && $decision->booking !== null;
$report['entries'][] = [
'tenant' => $tenant->id, 'channel' => $channel->name, 'blocked_period_id' => $entry->id,
'period' => $entry->starts_on->format('d.m.Y').'–'.$entry->ends_on->format('d.m.Y'),
'outcome' => $decision->outcome->value, 'case_type' => $decision->caseType?->value, 'reference' => $decision->reference,
'booking_id' => $decision->booking?->id, 'created' => $created, 'reasons' => $decision->reasons, 'before' => $before,
];
}
}
});
if ($apply) {
$report['channel_task_ids'] = ChannelTask::query()->withoutGlobalScopes()->where('id', '>', $firstTask)->pluck('id')->all();
}
$this->table(['Kanal', 'Zeitraum', 'Ergebnis', 'Art', 'Nr.', 'Vorgang', 'Begründung'], array_map(fn (array $entry): array => [
$entry['channel'], $entry['period'], IntakeOutcome::from($entry['outcome'])->getLabel(), strtoupper((string) $entry['case_type']), $entry['reference'] ?? '–',
$entry['booking_id'] ? '#'.$entry['booking_id'].($entry['created'] ? ' (neu)' : '') : '–', implode(' ', $entry['reasons']),
], $report['entries']));
$path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'.json';
for ($number = 2; Storage::disk('local')->exists($path); $number++) {
$path = self::DIRECTORY.'/'.$report['run'].($apply ? '' : '-vorschau').'-'.$number.'.json';
}
Storage::disk('local')->put($path, json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
$counts = collect($report['entries'])->countBy('outcome');
$this->info(($apply ? 'Übernommen' : 'Vorschau – nichts geändert').': '.$counts->map(fn (int $count, string $outcome): string => IntakeOutcome::from($outcome)->getLabel().' '.$count)->implode(', '));
$this->line('Bericht: storage/app/private/'.$path.($apply ? ' (Rücknahme: --revert='.$path.')' : ''));
return self::SUCCESS;
}
/**
* Takes an adoption back: cases created by it are removed again as long as nothing has happened with them (no
* document, no payment), and every entry gets its former state. Cases with activity are reported, not touched.
*/
private function revert(string $path): int
{
if (! Storage::disk('local')->exists($path)) {
$this->error('Bericht nicht gefunden: '.$path);
return self::FAILURE;
}
$report = json_decode((string) Storage::disk('local')->get($path), true);
if (! ($report['apply'] ?? false)) {
$this->info('Das war eine Vorschau – es gibt nichts zurückzunehmen.');
return self::SUCCESS;
}
$kept = [];
foreach ((array) $report['entries'] as $entry) {
$block = BlockedPeriod::query()->withoutGlobalScopes()->withTrashed()->find($entry['blocked_period_id']);
$case = ($entry['created'] ?? false) ? Booking::query()->withoutGlobalScopes()->find($entry['booking_id']) : null;
if ($case !== null && ($case->contract_path !== null || $case->confirmation_sent_at !== null || $case->payments()->withoutGlobalScopes()->exists())) {
$kept[] = $case->reference;
continue;
}
// The entry first gets its former state (it may point to the case), then the case created by the run goes.
if ($block !== null && in_array($entry['outcome'], [IntakeOutcome::Create->value, IntakeOutcome::Link->value], true)) {
$block->forceFill((array) $entry['before'])->saveQuietly();
}
$case?->delete();
}
ChannelTask::query()->withoutGlobalScopes()->whereKey((array) ($report['channel_task_ids'] ?? []))->where('status', ChannelTaskStatus::Open)
->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Bestandsübernahme zurückgenommen.']);
$this->info('Zurückgenommen.'.($kept === [] ? '' : ' Nicht entfernt, weil schon bearbeitet: '.implode(', ', $kept)));
return self::SUCCESS;
}
}
@@ -0,0 +1,186 @@
<?php
namespace App\Console\Commands;
use App\Models\CancellationPolicy;
use App\Models\ContractTemplate;
use App\Models\Property;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('contracts:install-fewo-direkt {--data=* : Wohnungsdaten als name=wert (z. B. wlan_passwort=…), werden nicht im Code gespeichert}')]
#[Description('Legt den Mietvertrag für FeWo-direkt-Direktbuchungen (Text des Vermieters) als Vertragsvorlage an, falls noch nicht vorhanden')]
class InstallFewoDirektContract extends Command
{
public const NAME = 'FeWo-direkt Direktbuchung';
/**
* Execute the console command.
*/
public function handle(TenantRunner $runner): int
{
$data = [];
foreach ((array) $this->option('data') as $pair) {
[$name, $value] = array_pad(explode('=', (string) $pair, 2), 2, null);
if (filled($name) && $value !== null && preg_match('/^[a-z0-9_]+$/', $name) === 1) {
$data[$name] = $value;
}
}
$runner->each(function (Tenant $tenant) use ($data): void {
if (ContractTemplate::query()->where('name', self::NAME)->exists()) {
$this->info("{$tenant->name}: Vorlage „".self::NAME.'“ ist schon vorhanden – nichts geändert.');
} else {
ContractTemplate::query()->create([
'name' => self::NAME,
'version' => 1,
'body' => self::body(),
'annex_title' => 'Ergänzende Vereinbarung zum Mietvertrag für die Wohnung „Am Stadtwald“, Wohnung 3',
'annex_body' => self::annex(),
'texts' => ['cancellation' => self::cancellation()],
'notes' => 'Übernommen aus dem Mietvertrag für FeWo-direkt-Direktbuchungen. Zugangsdaten stehen als Platzhalter {{ wohnung.… }}; Werte unter Wohnung › Vertragsdaten.',
]);
$this->info("{$tenant->name}: Vorlage „".self::NAME.'“ angelegt.');
}
$policy = CancellationPolicy::query()->firstOrCreate(['name' => 'Direktbuchung Standard'], [
'base' => CancellationPolicy::BASE_RENT,
'tiers' => [['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]],
'replacement_fee' => 3500,
'notes' => 'Staffel und Ersatzmieter-Gebühr aus § 13 des FeWo-direkt-Vertrags, berechnet vom Mietpreis. Bitte prüfen.',
]);
ContractTemplate::query()->where('name', self::NAME)->whereNull('cancellation_policy_id')->update(['cancellation_policy_id' => $policy->id]);
if ($data !== []) {
$property = Property::query()->first();
if ($property !== null) {
$property->update(['contract_data' => [...(array) $property->contract_data, ...$data]]);
$this->info("{$tenant->name}: ".count($data).' Vertragsdaten an der Wohnung gesetzt: '.implode(', ', array_keys($data)));
}
}
});
return self::SUCCESS;
}
private static function body(): string
{
return <<<'HTML'
<p>zwischen</p>
<p>{{ mieter }} (Mieter)</p>
<p>und</p>
<p>Frau {{ vermieter }}, {{ vermieter_anschrift }} (Vermieter)</p>
<p>wird folgender Mietvertrag geschlossen:</p>
<h3>§ 1 Mietgegenstand</h3>
<p>Vermietet wird eine Zweizimmer-Ferienwohnung, bestehend aus einem Wohnzimmer mit integrierter Küche, einer Diele mit großem Schrank, einem separaten Schlafzimmer, einem Duschbad mit WC und einer Terrasse im Erdgeschoss des Hauses „Am Stadtwald“, Strandstr. 15, Wohnung Nr. 3 in 18225 Ostseebad Kühlungsborn. Zur Wohnung gehört während der Urlaubsdauer ein eigener Parkplatz (Nr. 3). Dieser Platz befindet sich hinter dem Haus, schräg gegenüber der Hauseingangstür.</p>
<h3>§ 2 Mietdauer, An- und Abreise</h3>
<p>Die Räumlichkeiten werden vermietet an {{ personen }} erwachsene Personen von {{ anreise }} bis {{ abreise }}. Die reservierte Wohnung steht dem Gast ab {{ checkin }} Uhr am Anreisetag und bis {{ checkout }} Uhr am Abreisetag zur Verfügung.</p>
<p>Die Schlüssel für Ihre Ferienwohnung erhalten Sie von der <strong>Firma BALU Dienstleistungen, Ostseeallee 36/37 in 18225 Kühlungsborn.</strong> Die Mitarbeiter und Mitarbeiterinnen sind auch Ihre Ansprechpartner, falls Sie Fragen oder Probleme haben sollten. Die Telefonnummer lautet:</p>
<p><strong>038293-87 72 48.</strong></p>
<p>Bitte rufen Sie dort <u>zwei bis drei Tage vor Ihrer Anreise bis 14:00 Uhr</u> an, um die Schlüsselübergabe abzusprechen.</p>
<h3>§ 3 Kurtaxe</h3>
<p>Die Anmeldung in der Tourist-Information übernimmt ebenfalls die Fa. BALU. Dort werden Ihnen auch Ihre Kurkarten ausgehändigt. Die Kurabgabe beträgt derzeit in der Hauptsaison 3,00 €/Pers. und in der Nebensaison 1,60 €/Pers./Tag. Kinder bis 16 Jahre zahlen keine Kurabgabe. Das Geld dafür zahlen Sie direkt bei Schlüsselübergabe bzw. später, falls Sie außerhalb der Geschäftszeit anreisen.</p>
<h3>§ 4 Miete</h3>
<p>Die Miete inkl. aller Verbrauchskosten in der Wohnung sowie die von Ihrer Betreuungsfirma BALU erhobenen Kosten für Endreinigung und Service für {{ naechte }} Nächte inkl. der Servicegebühr von fewo-direkt beträgt insgesamt <strong>{{ gesamtpreis }}.</strong> Die Servicegebühr Ihres Internetanbieters sowie die Anzahlung wurden bereits bei Buchung von {{ anzahlung }} über Ihre Kreditkarte eingezogen. Zur Zahlung der restlichen Miete wird Ihr Internetanbieter Sie zum vereinbarten Termin auffordern, Ihre Buchung zu bestätigen und den Restbetrag zu zahlen.</p>
<h3>§ 5 Vertragsbedingungen</h3>
<p>Durch Ihre geleistete Anzahlung erklären sich die Mieter mit der Annahme des Vertrages einverstanden und verpflichten sich, Wohnung und Einrichtung pfleglich zu behandeln und eventuelle Schäden oder Bruch zu ersetzen bzw. durch deren Haftpflichtversicherung ersetzen zu lassen.</p>
<h3>§ 6 Bettwäsche und Wäschepakete/Sauna</h3>
<p>Die Firma BALU bietet Bettwäsche und Handtuchpakete zum Gesamtpreis von 23,00 €/Pers. an. Sie können auch Einzelpakete buchen. In dem Fall beträgt der Preis für fertig überzogene Betten 14,00 €/Pers. und für das Handtuchpaket (Dusch- und Handtuch, Duschvorleger) 11,00 €/Pers..</p>
<p>Wenn Sie eigene Wäsche mitbringen, entstehen für Sie keine weiteren Kosten.</p>
<p>Ihre Wünsche teilen Sie im Bedarfsfall bitte rechtzeitig telefonisch der Firma BALU mit.</p>
<p>Ein Geschirrtuch und ein Abwaschtuch werden generell zur Verfügung gestellt und sind im Mietpreis enthalten.</p>
<p>Falls Sie das Schrankbett nutzen wollen, benötigen Sie ein <u>übergroßes Spannbettlaken</u> oder ein <u>einfaches Laken</u> ohne Gummizug (das normale Spannbetttuch ist zu klein). Unter das ausgeklappte Schrankbett stellen Sie bitte zur Stabilität rechts und links die Holzstützen.</p>
<p>Bei geplanten Saunabesuchen vergessen Sie nicht, Saunatücher und zusätzliche Handtücher mit einzupacken. Empfehlenswert ist auch, für die Sauna 1 €-Münzen bereitzuhalten. Sollte der Saunabesuch wegen des Ansteckungsrisikos oder aus anderen Gründen nicht möglich sein, wird von Seiten der Vermieterin keine Haftung übernommen.</p>
<h3>§ 7 Schlüssel und Abfallentsorgung</h3>
<p>Sie erhalten zwei gleiche Schlüssel für die Hauseingangs- und Wohnungstür, Waschküche, den Saunabereich sowie den Abfallcontainer. <strong>Wichtig</strong>: Beide Schlüssel müssen am Abreisetag bei der Firma BALU abgegeben oder in den dort vorhandenen Briefkasten geworfen werden. Die Kellertür ist mit einem Zahlenschloss gesichert. Der Code lautet <strong>{{ wohnung.kellercode }}</strong>.</p>
<h3>§ 8 Schlüsselübergabe durch die Firma BALU nach Dienstschluss</h3>
<p>Bei Anreise außerhalb der Bürozeiten erfolgt die Schlüsselausgabe am Büro der Betreuungsfirma BALU. Ihr persönlicher Schlüsselsafe befindet sich im Foyer links hinter der Eingangstür. Beides ist mit einem Zifferncode zu öffnen. Die Bedienungsanleitung finden Sie direkt über der Tastatur links neben der Eingangstür von außen. Die entsprechenden Codes erfragen Sie bitte telefonisch vor Ort oder per SMS oder WhatsApp bei der Vermieterin.</p>
<h3>§ 9 Hausordnung</h3>
<p>Die Mieter sind verpflichtet, sich an die im Flur aushängende Hausordnung zu halten.</p>
<h3>§ 10 Sorgfaltspflichten</h3>
<p>Die Mieter haben die Räumlichkeiten und die Einrichtungsgegenstände pfleglich zu behandeln. Schuldhaft verursachte Schäden müssen von den Mietern ersetzt werden. Die Mieter sind verpflichtet, bei Bezug der Räumlichkeiten die Einrichtung auf ihre Vollständigkeit und ihre Gebrauchstauglichkeit hin zu überprüfen und eventuelle Beanstandungen <u>umgehend</u> bei Firma BALU oder der Eigentümerin zu melden. Zu spät eingegangene Beanstandungen werden nicht anerkannt und den Mietern angelastet. Während der Mietzeit eintretende Schäden haben die Mieter ebenfalls <u>unverzüglich</u> an die Firma BALU oder die Eigentümerin selbst zu melden. Kommen die Mieter diesen Pflichten nicht nach, steht ihnen eine Mietminderung wegen dieser zu beanstandenden Punkte nicht zu.</p>
<p>Es wird darum gebeten, <strong><u>keinesfalls Desinfektionsmittel oder Raumspray zum Sprühen</u></strong> zu verwenden, da dieses Alkohol enthält und das Mobiliar und insbesondere die Ledergarnitur beschädigen kann.</p>
<p>In der Wohnung darf nicht geraucht werden. Die Mieter werden gebeten, zum Rauchen auf die Terrasse zu gehen. Die Vermieterin kann jedoch nicht garantieren, dass das Rauchverbot auch in jedem Fall eingehalten wird. Eine Mietminderung steht den Mietern bei Nichteinhaltung des Verbots nicht zu.</p>
<h3>§ 11 Internet</h3>
<p>Der Internetanschluss in der Wohnung wird kostenlos zur Verfügung gestellt. Bei Störungen der Leitung oder sonstigen Widrigkeiten und dadurch bedingtem Leistungsausfall kann eine Mietminderung ebenfalls nicht geltend gemacht werden.</p>
<h3>§ 12 Internet-Nutzungsbedingungen</h3>
<p>Bestandteil dieses Vertrages ist die <em>„Ergänzende Vereinbarung zum Mietvertrag für die Wohnung „Am Stadtwald“, Wohnung 3““</em>. Die Vermieterin bittet um Bestätigung per eMail, dass der Inhalt zur Kenntnis genommen und akzeptiert wurde.</p>
<h3>§ 13 Rücktritt</h3>
<p>Die Mieter sind berechtigt, vor Mietbeginn vom Vertrag zurückzutreten. Im Falle eines solchen Rücktritts wird eine Entschädigung geltend gemacht, und zwar wie folgt:</p>
<ul>
<li>Rücktritt bis 60 Tage vor Mietbeginn: 0% des Mietpreises</li>
<li>Rücktritt 59 bis 30 Tage vor Mietbeginn: 50% des Mietpreises</li>
<li>Rücktritt ab 29 Tage vor Mietbeginn bis Mietbeginn: 100% des Mietpreises.</li>
</ul>
<p>Den Mietern wird ausdrücklich der Nachweis gestattet, ein Schaden sei überhaupt nicht entstanden oder wesentlich niedriger als die Pauschale. Die Mieter haben das Recht, Ersatzmieter zu stellen, die die Wohnung in vollem Umfang übernehmen. Dafür kann eine Bearbeitungsgebühr von 35,00 € berechnet werden. Rücktrittsgebühren werden dann nicht erhoben.</p>
<h3>§ 14 Verlassen der Wohnung</h3>
<p>Die Wohnung muss besenrein verlassen werden, da diese Arbeiten nicht in der Endreinigungspauschale enthalten sind. Dazu gehören u. a.</p>
<ul>
<li>die Entsorgung des Abfalls in die bereitstehenden Müllcontainer,</li>
<li>das gespülte Geschirr in den Schrank einräumen und die Tür der geleerten Spülmaschine öffnen,</li>
<li>Möbel und andere Gegenstände an ihren ursprünglichen Standort stellen.</li>
</ul>
<h3>§ 15 Gerichtsstand</h3>
<p>Gerichtsstand bei Streitigkeiten ist Dortmund. Es gilt deutsches Recht.</p>
<h3>§ 16 Schriftform</h3>
<p>Änderungen und Ergänzungen dieses Vertrages bedürfen der Schriftform. Die schriftliche Form kann u. a. auch per E-Mail erfolgen.</p>
<h3>§ 17 Datenschutz</h3>
<p>Ihre personenbezogenen Daten werden nur zum Erstellen der Mietunterlagen und zur Kommunikation mit Ihnen verarbeitet. Eine Übermittlung Ihrer persönlichen Daten an Dritte zu anderen, als den genannten Zwecken, findet nicht statt. Weitere Einzelheiten und die Datenschutzerklärung finden Sie auf meiner Website unter www.fewo-stommer.de unter dem Menüpunkt „Datenschutz“.</p>
<h3>§ 18 Salvatorische Klausel</h3>
<p>Sollten einzelne Bestimmungen dieses Vertrages ganz oder teilweise unwirksam sein oder werden oder sollte sich im Vertrag eine Lücke befinden, so soll hierdurch die Gültigkeit der übrigen Bestimmungen nicht berührt werden. Anstelle der unwirksamen Bestimmung oder zur Ausfüllung der Lücke soll eine angemessene Regelung treten, die, soweit rechtlich möglich, dem am nächsten kommt, was die Vertragsparteien gewollt oder nach dem Sinn und Zweck dieses Vertrages gewollt haben dürften, wenn sie den Punkt bedacht hätten.</p>
<p>Dortmund, den {{ datum }}<br><em>(Die Unterschrift wurde maschinell erstellt und ist gültig)</em></p>
HTML;
}
private static function annex(): string
{
return <<<'HTML'
<p>Der Vermieter stellt dem Mieter den Internetzugang per WLan kostenfrei zur Verfügung.</p>
<p>Die Login-Daten für den WLan-Zugriff dürfen nicht an fremde Personen weitergegeben werden und sind vertraulich zu behandeln.</p>
<p>Folgende Aktivitäten sind generell untersagt:</p>
<ul>
<li>Abrufen von kostenpflichtigen Dienstleistungen,</li>
<li>Nutzung im Zusammenhang mit anstößigem oder strafrechtlich relevantem Inhalt,</li>
<li>übermäßige Belastung durch große Datenmengen.</li>
</ul>
<p>Auch wenn der Mieter im Außenverhältnis für eine kostenpflichtige Nutzung haftet, stellt er den Vermieter vorsorglich von etwaigen Ansprüchen Dritter frei.</p>
<p>Der Vermieter wird die Privatsphäre der Mieter wahren. Dazu gehört auch der Anspruch auf Vertraulichkeit der Nutzung der Online-Dienste.</p>
<p>Der Vermieter verfügt jedoch über die Verkehrs-und Logdaten, welche festhalten, wann welche Verbindungen hergestellt worden sind. Bei begründetem Verdacht auf missbräuchliche Nutzung können diese Daten ausgewertet werden. Diese Daten werden nach drei Monaten gelöscht.</p>
<h3>WLan-Netzwerk</h3>
<p>Zugangsdaten für den Router sind:</p>
<p>Benutzername: {{ wohnung.wlan_benutzer }}</p>
<p>Passwort: {{ wohnung.wlan_passwort }}</p>
<h3>Dunstabzugshaube</h3>
<p>Damit die Dunstabzugshaube die Abluft gut abtransportieren kann, muss zusätzlich der Schalter „Lüfter“ betätigt und die Fenstertür geöffnet (schräg gestellt) werden.</p>
<h3>Spülmaschine</h3>
<p>Bitte beachten Sie das Hinweisschild in der Innenseite der Schranktür über der Spülmaschine. Die Spülmaschine enthält eine Besteckschublade (keinen Besteckkorb).</p>
HTML;
}
private static function cancellation(): string
{
return '<p>Die Mieter sind berechtigt, vor Mietbeginn vom Vertrag zurückzutreten. Im Falle eines solchen Rücktritts wird eine Entschädigung geltend gemacht, und zwar wie folgt:</p><ul><li>Rücktritt bis 60 Tage vor Mietbeginn: 0% des Mietpreises</li><li>Rücktritt 59 bis 30 Tage vor Mietbeginn: 50% des Mietpreises</li><li>Rücktritt ab 29 Tage vor Mietbeginn bis Mietbeginn: 100% des Mietpreises.</li></ul><p>Den Mietern wird ausdrücklich der Nachweis gestattet, ein Schaden sei überhaupt nicht entstanden oder wesentlich niedriger als die Pauschale. Die Mieter haben das Recht, Ersatzmieter zu stellen, die die Wohnung in vollem Umfang übernehmen. Dafür kann eine Bearbeitungsgebühr von 35,00 € berechnet werden. Rücktrittsgebühren werden dann nicht erhoben.</p>';
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Enums\IntakeOutcome;
use App\Models\IntakeObservation;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:intake-report {--days=14 : Zeitraum in Tagen}')]
#[Description('Bericht des Eingangsprotokolls: was über die Portale hereinkam und welche Vorgänge entstanden sind oder entstanden wären')]
class IntakeReport extends Command
{
public function handle(TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant): void {
$observations = IntakeObservation::query()->with(['channel', 'booking'])
->where('occurred_at', '>=', now()->subDays((int) $this->option('days')))->orderBy('occurred_at')->get();
$this->line("<options=bold>{$tenant->name}</>: ".$observations->count().' Einträge');
$this->table(['Wann', 'Portal', 'Quelle', 'Zeitraum', 'Ergebnis', 'Ausgeführt', 'Vorgang', 'Begründung'], $observations->map(fn (IntakeObservation $observation): array => [
$observation->occurred_at->format('d.m. H:i'),
$observation->channel?->name,
$observation->sourceLabel(),
$observation->starts_on ? $observation->starts_on->format('d.m.').'–'.$observation->ends_on?->format('d.m.Y') : '–',
$observation->outcome->getLabel(),
$observation->applied ? 'ja' : 'nur protokolliert',
$observation->booking?->reference ?? '–',
implode(' ', (array) $observation->reasons),
])->all());
$wouldCreate = $observations->filter(fn (IntakeObservation $observation): bool => ! $observation->applied && in_array($observation->outcome, [IntakeOutcome::Create, IntakeOutcome::Inquiry], true))->count();
$this->info("Wären entstanden (Beobachten): {$wouldCreate}");
});
return self::SUCCESS;
}
}
@@ -0,0 +1,59 @@
<?php
namespace App\Console\Commands;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('process:settings-report')]
#[Description('Show every landlord’s process defaults and all deviations of properties and channels (read only)')]
class ProcessSettingsReport extends Command
{
public function handle(TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant): void {
$this->line('');
$this->info($tenant->name);
$defaults = (array) ($tenant->process_defaults ?? []);
foreach (ProcessSetting::cases() as $setting) {
if (! $setting->isLandlordSetting()) {
continue;
}
$value = $setting->normalize($defaults[$setting->value] ?? null);
$this->line(' Standard · '.$setting->question().' '.$setting->describe($value ?? $setting->default()).($value === null ? ' (Grundeinstellung)' : ''));
}
$rows = [];
foreach (Property::query()->orderBy('name')->get() as $property) {
foreach ((array) ($property->process_overrides ?? []) as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting?->normalize($value) !== null) {
$rows[] = ['Wohnung '.$property->name, $setting->question(), $setting->describe($setting->normalize($value))];
}
}
}
foreach (Channel::query()->with('property')->orderBy('name')->get() as $channel) {
foreach ((array) ($channel->process_overrides ?? []) as $intake => $values) {
foreach ((array) $values as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting?->normalize($value) !== null) {
$rows[] = ['Portal '.$channel->name.' ('.$channel->property?->name.', '.(IntakeKind::tryFrom((string) $intake)?->getLabel() ?? $intake).')', $setting->question(), $setting->describe($setting->normalize($value))];
}
}
}
}
$rows === [] ? $this->line(' Keine Abweichungen.') : $this->table(['Wo', 'Einstellung', 'Wert'], $rows);
});
return self::SUCCESS;
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Console\Commands;
use App\Actions\ConfirmBooking;
use App\Enums\BookingStatus;
use App\Models\Booking;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('bookings:resend-confirmations')]
#[Description('Retry booking confirmations whose mail failed (last three days) – once per landlord')]
class ResendBookingConfirmations extends Command
{
/**
* Execute the console command.
*/
public function handle(ConfirmBooking $confirmBooking, TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant) use ($confirmBooking): void {
$sent = 0;
$failed = Booking::query()
->whereIn('status', BookingStatus::occupying())
->whereNotNull('confirmation_failed_at')
->where('confirmation_failed_at', '>=', now()->subDays(3))
->whereNull('confirmation_sent_at')
->get();
foreach ($failed as $booking) {
$sent += $confirmBooking->resend($booking) ? 1 : 0;
}
$this->info("{$tenant->name}: {$sent} von {$failed->count()} Bestätigung(en) nachgesendet.");
});
return self::SUCCESS;
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Console\Commands;
use App\Actions\AutoOffer;
use App\Enums\BookingStatus;
use App\Models\Booking;
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('bookings:auto-offers')]
#[Description('Retry automatic offers of pending requests (e.g. once an instant-booking portal has fetched our calendar) – once per landlord')]
class SendPendingAutoOffers extends Command
{
/**
* Execute the console command.
*/
public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
{
$runner->each(function (Tenant $tenant) use ($autoOffer): void {
$pending = Booking::query()
->where('status', BookingStatus::Reserved)
->where('offer_version', 0)
->where('hold_expires_at', '>', now())
->with(['property', 'guest', 'importChannel', 'originChannel'])
->get()
->filter(fn (Booking $booking): bool => $autoOffer->applies($booking) && $booking->process()->preReservation());
$sent = 0;
foreach ($pending as $booking) {
try {
$sent += $autoOffer->handle($booking) === [] ? 1 : 0;
} catch (Throwable) {
// The request stays pending for the landlord; the next run tries again.
}
}
$this->info("{$tenant->name}: {$sent} von {$pending->count()} Angebot(e) automatisch versendet.");
});
return self::SUCCESS;
}
}
+2
View File
@@ -25,6 +25,8 @@ public function handle(): int
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
if (filled($redirect)) {
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
} elseif (! Settings::isLive()) {
$this->warn('Testbetrieb ohne Testadresse: Es wird keine E-Mail versendet. Testempfänger unter System › Betrieb eintragen.');
}
if ($mailer === 'log') {
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
+136
View File
@@ -0,0 +1,136 @@
<?php
namespace App\Documents;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use App\Support\Money;
/**
* Placeholders of contract documents, written as {{ name }} in the template text. Values are taken from the
* booking and the facts of the property ({{ wohnung.wlan_passwort }}); they are HTML-escaped. A placeholder that
* cannot be filled stays visible as [name?] so that it is never silently missing in a contract.
*/
class ContractPlaceholders
{
/** Placeholders whose value is already safe HTML. */
private const RAW = ['storno_regel'];
private const PATTERN = '/\{\{\s*([a-z][a-z0-9_]*(?:\.[a-z0-9_]+)?)\s*\}\}/i';
/**
* Placeholders with their meaning, for the template editor.
*
* @return array<string, string>
*/
public static function catalog(): array
{
return [
'mieter' => 'Name des Gastes',
'mieter_anschrift' => 'Anschrift des Gastes',
'mieter_email' => 'E-Mail des Gastes',
'anreise' => 'Anreisetag mit Wochentag, z. B. Samstag, 07.11.2026',
'abreise' => 'Abreisetag mit Wochentag',
'anreise_datum' => 'Anreisedatum, z. B. 07.11.2026',
'abreise_datum' => 'Abreisedatum',
'naechte' => 'Anzahl der Nächte',
'personen' => 'Anzahl der Personen',
'gesamtpreis' => 'Gesamtpreis, z. B. 1.234,00 €',
'anzahlung' => 'Anzahlung',
'restzahlung' => 'Restzahlung',
'restzahlung_faellig' => 'Fälligkeit der Restzahlung',
'buchungsnummer' => 'Buchungs-/Angebotsnummer',
'datum' => 'Datum des Vertrags',
'vermieter' => 'Name des Vermieters',
'vermieter_anschrift' => 'Anschrift des Vermieters',
'wohnung' => 'Name der Wohnung',
'wohnung_adresse' => 'Adresse der Wohnung',
'checkin' => 'Anreisezeit (Uhr)',
'checkout' => 'Abreisezeit (Uhr)',
'portal' => 'Name des Portals (leer bei eigener Buchung)',
'storno_regel' => 'Die Stornoregel dieser Vorlage als Aufzählung (Stufen und Prozent)',
'wohnung.<name>' => 'Eigene Wohnungsdaten (Wohnung bearbeiten › Vertragsdaten), z. B. wohnung.wlan_passwort',
];
}
/**
* @param array<string, mixed> $propertyData facts of the property as frozen in the offer
*/
public static function render(string $html, Booking $booking, array $propertyData = []): string
{
$values = self::values($booking, $propertyData);
return (string) preg_replace_callback(self::PATTERN, function (array $match) use ($values): string {
$key = strtolower($match[1]);
if (! array_key_exists($key, $values) || $values[$key] === null) {
return '[<b>'.e($key).'?</b>]';
}
return in_array($key, self::RAW, true) ? (string) $values[$key] : e((string) $values[$key]);
}, $html);
}
/**
* Placeholders in the text that have no value for this booking.
*
* @param array<string, mixed> $propertyData
* @return list<string>
*/
public static function missing(string $html, Booking $booking, array $propertyData = []): array
{
$values = self::values($booking, $propertyData);
preg_match_all(self::PATTERN, $html, $found);
return array_values(array_unique(array_filter(array_map('strtolower', $found[1]), fn (string $key): bool => ! isset($values[$key]))));
}
/**
* @param array<string, mixed> $propertyData
* @return array<string, ?string>
*/
private static function values(Booking $booking, array $propertyData): array
{
$booking->loadMissing(['guest', 'property', 'importChannel', 'originChannel']);
$guest = $booking->guest;
$owner = OfferTerms::owner($booking);
$property = $booking->property;
$address = trim(implode(', ', array_filter([$guest?->street, trim(($guest?->postal_code ?? '').' '.($guest?->city ?? ''))])));
$values = [
'mieter' => $guest?->full_name,
'mieter_anschrift' => $address ?: null,
'mieter_email' => $guest?->email,
'anreise' => $booking->arrival->translatedFormat('l, d.m.Y'),
'abreise' => $booking->departure->translatedFormat('l, d.m.Y'),
'anreise_datum' => $booking->arrival->format('d.m.Y'),
'abreise_datum' => $booking->departure->format('d.m.Y'),
'naechte' => (string) $booking->nights(),
'personen' => $booking->guests !== null ? (string) $booking->guests : null,
'gesamtpreis' => $booking->total !== null ? Money::format($booking->total) : null,
'anzahlung' => $booking->deposit !== null ? Money::format($booking->deposit) : null,
'restzahlung' => $booking->total !== null && $booking->deposit !== null ? Money::format($booking->total - $booking->deposit) : null,
'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'),
'buchungsnummer' => $booking->reference,
'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'),
'vermieter' => $owner['name'] ?? null,
'vermieter_anschrift' => trim(($owner['street'] ?? '').', '.($owner['city'] ?? ''), ', ') ?: null,
'wohnung' => $property->name,
'wohnung_adresse' => $property->address,
'checkin' => $property->check_in_time ? substr((string) $property->check_in_time, 0, 5) : null,
'checkout' => $property->check_out_time ? substr((string) $property->check_out_time, 0, 5) : null,
'portal' => ($booking->importChannel ?? $booking->originChannel)?->name ?? '',
];
$policy = $booking->offer_terms['cancellation_policy'] ?? null;
if (is_array($policy) && ! empty($policy['tiers'])) {
$values['storno_regel'] = '<ul>'.collect(CancellationPolicy::describe($policy))->map(fn (string $line): string => '<li>'.e($line).'</li>')->implode('').'</ul>';
}
foreach ($propertyData as $name => $value) {
$values['wohnung.'.strtolower((string) $name)] = is_scalar($value) ? (string) $value : null;
}
return $values;
}
}
+404
View File
@@ -0,0 +1,404 @@
<?php
namespace App\Documents;
use App\Actions\SendOffer;
use App\Availability\AvailabilityChecker;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\Booking;
use App\Models\CancellationPolicy;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\ProcessProfile;
use App\Process\ProcessSettings;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Throwable;
/**
* Prepares the document a case needs (UMSETZUNGSPLAN_v0.10 §4.5, package 3): applies the landlord's adjustments to a copy
* of the case, takes template and annexes from the process settings, captures the terms the document would freeze and
* lists – in plain words – what is missing, what has to be confirmed and what is only worth knowing. Nothing is saved.
*
* Only objective criteria lead to findings (missing or contradictory data, unreleased texts, terms not shown to be
* agreed); nationality or origin of a guest never do.
*/
class DocumentComposer
{
/** Placeholders that state payments to the landlord. */
private const PAYMENT_PLACEHOLDERS = ['anzahlung', 'restzahlung', 'restzahlung_faellig'];
public function __construct(
private SendOffer $offer,
private AvailabilityChecker $availability,
private ProcessSettings $settings,
) {}
/**
* @param array<string, mixed> $changes adjustments of the landlord (offer: dates, guests, promo code, price adjustment
* in cents, validity, message, guest data; all kinds: contract_template_id, annex_ids)
*/
public function compose(Booking $booking, ?DocumentKind $kind = null, array $changes = []): DocumentComposition
{
$booking->loadMissing(['guest', 'property', 'originChannel', 'importChannel']);
$kind ??= DocumentKind::forCase($booking) ?? DocumentKind::Internal;
$findings = [];
$draft = clone $booking;
$draft->setRelation('guest', $booking->guest !== null ? (clone $booking->guest)->fill(self::guestChanges($changes)) : null);
if ($kind === DocumentKind::Offer) {
$findings = [...$findings, ...$this->prepareOffer($booking, $draft, $changes)];
}
$frozen = $kind !== DocumentKind::Offer && ($booking->contract_path !== null || ($booking->offer_version > 0 && is_array($booking->offer_terms)));
$explicitTemplate = ! $frozen && filled($changes['contract_template_id'] ?? null);
$template = match (true) {
$frozen => isset($booking->offer_terms['template']['id']) ? ContractTemplate::query()->find($booking->offer_terms['template']['id']) : null,
default => OfferTerms::templateFor($booking, $explicitTemplate ? $changes['contract_template_id'] : null),
};
$terms = match (true) {
! $kind->isForGuests() => null,
$frozen => $booking->offer_terms,
default => OfferTerms::capture($template, $draft, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
};
$draft->offer_terms = $terms;
$findings = [...$findings, ...$this->commonFindings($booking, $draft, $kind, $template, $frozen)];
if ($kind === DocumentKind::ExternalRecord) {
$findings = [...$findings, ...$this->externalFindings($booking, $template, $terms, $frozen)];
}
if ($kind === DocumentKind::Confirmation) {
$findings = [...$findings, ...$this->confirmationFindings($booking)];
}
return new DocumentComposition(
kind: $kind,
draft: $draft,
intakeLabel: explode(' · ', CaseActivities::situation($booking))[0],
priceLines: array_values(array_map(fn (array $line): array => ['label' => (string) $line['label'], 'amount' => (int) $line['amount']], (array) ($draft->quote['lines'] ?? []))),
priceSource: $this->priceSource($booking, $draft, $kind),
services: $this->services($draft),
cancellation: $this->cancellation($terms, $kind),
template: $template,
templateSource: $this->templateSource($booking, $frozen, $explicitTemplate),
annexes: array_values(array_map(fn (array $annex): array => ['id' => (int) $annex['id'], 'label' => $annex['name'].' (Version '.$annex['version'].')'], (array) ($terms['annexes'] ?? []))),
terms: $terms,
termsFrozen: $frozen,
findings: $findings,
);
}
/**
* Applies the offer adjustments to the copy and calculates its price exactly as {@see SendOffer} will.
*
* @param array<string, mixed> $changes
* @return list<DocumentFinding>
*/
private function prepareOffer(Booking $booking, Booking $draft, array $changes): array
{
$findings = [];
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
$findings[] = DocumentFinding::blocker('Für diesen Vorgang ist kein Angebot mehr möglich ('.$booking->status->getLabel().').');
}
try {
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
$guests = (int) ($changes['guests'] ?? $booking->guests);
$promo = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$label = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->offer->quoteFor($booking, new StayRequest($arrival, $departure, max(1, $guests), $booking->extras ?? [], $promo), $adjustment, $label);
$draft->forceFill([
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $quote->guests,
'promo_code' => $quote->promoCodeApplied ? $promo : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
]);
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
$findings[] = DocumentFinding::blocker('Der Zeitraum ist nicht mehr frei.');
}
} catch (QuoteException $exception) {
$findings[] = DocumentFinding::blocker('Preis: '.$exception->getMessage());
} catch (Throwable) {
$findings[] = DocumentFinding::blocker('Bitte Anreise, Abreise und Personen angeben.');
}
$draft->forceFill([
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->process()->holdHours()),
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? $booking->offer_message,
]);
if (! $booking->process()->preReservation()) {
$findings[] = DocumentFinding::confirm('Nach Ihrer Einstellung reservieren Anfragen den Zeitraum nicht. Ein Angebot mit Annahmelink reserviert ihn trotzdem bis '.$draft->hold_expires_at->format('d.m.Y, H:i').' Uhr, und der Gast kann bis dahin verbindlich annehmen. Eine Auskunft ohne Reservierung gibt es erst in einem späteren Ausbauschritt.', DocumentFinding::HOLD_ZERO);
}
if ($booking->offer_version > 0) {
$findings[] = DocumentFinding::info('Ersetzt Angebot Version '.$booking->offer_version.'; dessen Link wird ungültig.');
}
return $findings;
}
/**
* @return list<DocumentFinding>
*/
private function commonFindings(Booking $booking, Booking $draft, DocumentKind $kind, ?ContractTemplate $template, bool $frozen): array
{
if (! $kind->isForGuests()) {
return [DocumentFinding::info('Für diesen Vorgang geht kein Dokument an Gäste.')];
}
$findings = [];
if (! $kind->isAvailable()) {
$findings[] = DocumentFinding::blocker('„'.$kind->getLabel().'“ kann erst mit einem späteren Ausbauschritt versendet werden; die Arbeitsfassung ist vorbereitet.');
}
if ($draft->guest === null) {
$findings[] = DocumentFinding::blocker('Name und Kontaktdaten des Gastes fehlen.');
} elseif (blank($draft->guest->email)) {
$findings[] = DocumentFinding::blocker('Die E-Mail-Adresse des Gastes fehlt.');
}
if ($kind !== DocumentKind::Offer && $booking->total === null) {
$findings[] = DocumentFinding::blocker($booking->intake === IntakeKind::Booking ? 'Der Gesamtpreis (laut Portal) fehlt.' : 'Der Preis fehlt.');
}
if ($booking->confirmation_sent_at !== null && $kind !== DocumentKind::Offer) {
$findings[] = DocumentFinding::info('Bereits gesendet am '.$booking->confirmation_sent_at->format('d.m.Y, H:i').' Uhr. Erneutes Senden schickt dieselben Unterlagen.');
}
if ($frozen) {
return $findings;
}
if ($kind->isAvailable() && ! DocumentReleases::isReleased($kind)) {
$findings[] = DocumentFinding::confirm('Die Texte für „'.$kind->getLabel().'“ sind eine Arbeitsfassung und noch nicht freigegeben (So arbeite ich › Dokumente).');
}
if ($template !== null && ! $template->isReleased()) {
$findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist noch nicht für Gäste freigegeben (Vorlagen › Freigabe).');
}
$missing = $this->missingPlaceholders($draft);
if ($missing !== []) {
$findings[] = DocumentFinding::confirm('Im Vertragstext fehlen Angaben, sie erscheinen als [name?]: '.implode(', ', $missing).'.');
}
return $findings;
}
/**
* Bookings already binding on a portal: no acceptance link, the portal price counts, and the template must not add
* obligations the guest did not accept there (E-004).
*
* @param array<string, mixed>|null $terms
* @return list<DocumentFinding>
*/
private function externalFindings(Booking $booking, ?ContractTemplate $template, ?array $terms, bool $frozen): array
{
$channel = $booking->processChannel()?->name ?? 'dem Portal';
$findings = [DocumentFinding::info('Kein Annahmelink: Die Buchung ist bei '.$channel.' bereits verbindlich zustande gekommen.')];
if ($frozen) {
return $findings;
}
if ($template === null) {
$findings[] = DocumentFinding::confirm('Für Buchungen über '.$channel.' ist keine eigene Vorlage hinterlegt. Die Unterlagen enthielten Ihre Mietbedingungen der Webseite – ihnen hat der Gast bei '.$channel.' nicht zugestimmt.');
} elseif (! $template->confirmsPortalTerms()) {
$findings[] = DocumentFinding::confirm('Die Vorlage „'.$template->label().'“ ist nicht als Wiedergabe der Bedingungen von '.$channel.' bestätigt. Zusätzliche Pflichten gelten nur, wenn der Gast ihnen dort zugestimmt hat.');
$fees = $this->fees($terms);
if ($fees !== []) {
$findings[] = DocumentFinding::confirm('Gebühren in der Vorlage, die bei '.$channel.' nicht nachweislich vereinbart sind: '.implode('; ', $fees).'.');
}
}
if ($booking->process()->payments() === Responsibility::Portal && $this->mentionsPaymentsToUs($terms)) {
$findings[] = DocumentFinding::confirm('Die Vorlage nennt Zahlungen an Sie (Anzahlung/Restzahlung), laut Einstellung zahlt der Gast über '.$channel.'.');
}
return $findings;
}
/**
* @return list<DocumentFinding>
*/
private function confirmationFindings(Booking $booking): array
{
return $booking->accepted_at !== null
? [DocumentFinding::info('Bedingungen wie im angenommenen Angebot vom '.$booking->accepted_at->format('d.m.Y').' (unverändert).')]
: [];
}
private function priceSource(Booking $booking, Booking $draft, DocumentKind $kind): string
{
return match (true) {
$draft->total === null => 'noch nicht bekannt',
($draft->quote['source'] ?? null) === 'portal' => 'laut '.($booking->processChannel()?->name ?? 'Portal').' übernommen, nicht neu berechnet',
$kind === DocumentKind::Offer => 'aus Ihren Preisen berechnet',
$booking->accepted_at !== null => 'wie im angenommenen Angebot',
default => 'aus Ihren Preisen berechnet',
};
}
private function templateSource(Booking $booking, bool $frozen, bool $explicit): string
{
if ($frozen) {
return $booking->offer_version > 0 ? 'im angenommenen Angebot festgehalten' : 'mit den Unterlagen festgehalten';
}
if ($explicit) {
return 'für diesen Vorgang gewählt';
}
$source = $this->settings->forBooking($booking)->source(ProcessSetting::ContractTemplate);
return match ($source) {
ProcessProfile::CHANNEL => 'eingestellt für '.$booking->processChannel()?->name.' ('.($booking->intake?->getLabel() ?? '').')',
ProcessProfile::PROPERTY => 'eingestellt für die Wohnung '.$booking->property->name,
ProcessProfile::TENANT => 'Ihre Standardeinstellung',
default => 'keine Vorlage eingestellt',
};
}
/**
* @return list<string>
*/
private function services(Booking $draft): array
{
$extras = array_filter((array) ($draft->extras ?? []), fn ($quantity): bool => (int) $quantity > 0);
if ($extras === []) {
return [];
}
return Extra::query()->whereIn('id', array_keys($extras))->orderBy('name')->get()
->map(fn (Extra $extra): string => $extra->name.((int) $extras[$extra->id] > 1 ? ' × '.$extras[$extra->id] : ''))
->values()->all();
}
/**
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function cancellation(?array $terms, DocumentKind $kind): array
{
$lines = [];
if ($kind === DocumentKind::ExternalRecord) {
$lines[] = 'Maßgeblich ist die bei der Buchung über das Portal vereinbarte Regel.';
}
$policy = $terms['cancellation_policy'] ?? null;
if (is_array($policy) && ! empty($policy['tiers'])) {
return [...$lines, ...CancellationPolicy::describe($policy)];
}
if (filled($terms['texts']['stay.cancellation'] ?? null)) {
return [...$lines, 'Laut Text „Rücktritt / Stornierung“ der Vorlage bzw. Webseite (keine Staffel hinterlegt).'];
}
return $terms === null ? $lines : [...$lines, 'Keine Stornoregel hinterlegt.'];
}
/**
* Placeholders of the contract text that have no value for this case.
*
* @return list<string>
*/
private function missingPlaceholders(Booking $draft): array
{
$terms = (array) ($draft->offer_terms ?? []);
$data = (array) ($terms['property_data'] ?? []);
$texts = array_filter([
$terms['document']['body'] ?? null,
$terms['document']['annex_body'] ?? null,
...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])),
]);
return array_values(array_unique(array_merge(...array_map(fn (string $html): array => ContractPlaceholders::missing($html, $draft, $data), $texts ?: ['']))));
}
/**
* Fees a template states: the replacement fee of its cancellation rule and amounts written in its texts.
*
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function fees(?array $terms): array
{
$fees = [];
$policy = $terms['cancellation_policy'] ?? null;
if (is_array($policy) && ($policy['replacement_fee'] ?? null) !== null) {
$fees[] = 'Ersatzmieter-Gebühr '.Money::format((int) $policy['replacement_fee']);
}
if (is_array($policy) && ! empty($policy['tiers'])) {
$fees[] = 'Stornokosten nach Staffel ('.$policy['name'].')';
}
$text = strip_tags(implode(' ', $this->templateTexts($terms)));
preg_match_all('/\d{1,3}(?:\.\d{3})*(?:,\d{1,2})?\s?(?:€|EUR\b|Euro\b)/u', html_entity_decode($text), $amounts);
foreach (array_unique($amounts[0]) as $amount) {
$fees[] = trim($amount).' (im Text)';
}
return $fees;
}
/**
* @param array<string, mixed>|null $terms
*/
private function mentionsPaymentsToUs(?array $terms): bool
{
$text = implode(' ', $this->templateTexts($terms));
foreach (self::PAYMENT_PLACEHOLDERS as $placeholder) {
if (preg_match('/\{\{\s*'.$placeholder.'\s*\}\}/i', $text) === 1) {
return true;
}
}
return false;
}
/**
* The texts a template contributes (not the website texts it falls back to).
*
* @param array<string, mixed>|null $terms
* @return list<string>
*/
private function templateTexts(?array $terms): array
{
if ($terms === null || ! isset($terms['template'])) {
return [];
}
$template = ContractTemplate::query()->find($terms['template']['id']);
return array_values(array_filter([
$terms['document']['body'] ?? null,
$terms['document']['annex_body'] ?? null,
...array_values($template?->overrides() ?? []),
...array_map(fn (array $annex): ?string => $annex['body'] ?? null, (array) ($terms['annexes'] ?? [])),
]));
}
/**
* @param array<string, mixed> $changes
* @return array<string, ?string>
*/
private static function guestChanges(array $changes): array
{
$guest = (array) ($changes['guest'] ?? []);
return array_map(fn ($value): ?string => filled($value) ? trim((string) $value) : null, array_filter(Arr::only($guest, ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']), 'filled'));
}
}
+129
View File
@@ -0,0 +1,129 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Booking;
use App\Models\ContractTemplate;
/**
* Everything a document of a case consists of before it is sent (UMSETZUNGSPLAN_v0.10 §4.5): recipient, stay, how the
* case came in, price with its origin, services, cancellation rule, template and annexes, and what has to be checked.
* The same composition is shown to the landlord, decides whether the automatic run may send, and is what is sent.
*/
final class DocumentComposition
{
/**
* @param Booking $draft the case as the document will show it (never saved)
* @param list<array{label: string, amount: int}> $priceLines
* @param list<string> $services
* @param list<string> $cancellation
* @param list<array{id: int, label: string}> $annexes
* @param array<string, mixed>|null $terms the terms the document freezes (null: the website texts apply live)
* @param list<DocumentFinding> $findings
*/
public function __construct(
public readonly DocumentKind $kind,
public readonly Booking $draft,
public readonly string $intakeLabel,
public readonly array $priceLines,
public readonly string $priceSource,
public readonly array $services,
public readonly array $cancellation,
public readonly ?ContractTemplate $template,
public readonly string $templateSource,
public readonly array $annexes,
public readonly ?array $terms,
public readonly bool $termsFrozen,
public readonly array $findings,
) {}
public function recipientName(): ?string
{
return $this->draft->guest?->full_name;
}
public function recipientEmail(): ?string
{
return filled($this->draft->guest?->email) ? $this->draft->guest->email : null;
}
/**
* @return list<string>
*/
public function blockers(): array
{
return $this->messages(DocumentFinding::BLOCKER);
}
/**
* @param list<string> $except codes of findings left out
* @return list<string>
*/
public function toConfirm(array $except = []): array
{
return $this->messages(DocumentFinding::CONFIRM, $except);
}
/**
* @return list<string>
*/
public function information(): array
{
return $this->messages(DocumentFinding::INFO);
}
/**
* The automatic run sends only a document without blockers and without anything the landlord has to confirm.
*/
public function canSendAutomatically(): bool
{
return $this->blockers() === [] && $this->toConfirm() === [];
}
/**
* By hand: no blockers, and every point to confirm was confirmed.
*/
public function canSendByHand(bool $acknowledged): bool
{
return $this->blockers() === [] && ($this->toConfirm() === [] || $acknowledged);
}
/**
* The template as the landlord reads it.
*/
public function templateLabel(): string
{
if ($this->terms !== null && isset($this->terms['template']['name'])) {
return $this->terms['template']['name'].' (Version '.$this->terms['template']['version'].')';
}
return $this->template?->label() ?? 'Texte der Webseite';
}
/**
* What is stored about the document in the case history.
*
* @return array<string, mixed>
*/
public function record(): array
{
return [
'kind' => $this->kind->value,
'template' => $this->terms['template'] ?? null,
'annexes' => array_map(fn (array $annex): string => $annex['label'], $this->annexes),
'recipient' => $this->recipientEmail(),
'total' => $this->draft->total,
'price_source' => $this->priceSource,
];
}
/**
* @param list<string> $except
* @return list<string>
*/
private function messages(string $severity, array $except = []): array
{
return array_values(array_map(fn (DocumentFinding $finding): string => $finding->message, array_filter($this->findings, fn (DocumentFinding $finding): bool => $finding->severity === $severity && ! in_array($finding->code, $except, true))));
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Documents;
/**
* One finding of a document composition. A blocker stops the document (data missing or contradictory); a point to
* confirm stops the automatic run and needs the landlord's explicit confirmation before sending by hand; information
* only explains.
*/
final class DocumentFinding
{
public const BLOCKER = 'blocker';
public const CONFIRM = 'confirm';
public const INFO = 'info';
/** Code of the finding "the settings reserve nothing for requests" (Hold = 0, package 7). */
public const HOLD_ZERO = 'hold_zero';
public function __construct(
public readonly string $severity,
public readonly string $message,
public readonly ?string $code = null,
) {}
public static function blocker(string $message): self
{
return new self(self::BLOCKER, $message);
}
public static function confirm(string $message, ?string $code = null): self
{
return new self(self::CONFIRM, $message, $code);
}
public static function info(string $message): self
{
return new self(self::INFO, $message);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Tenant;
use App\Support\Settings;
/**
* Which document kinds the landlord has released for guests (tenants.document_releases). A kind that is not released is
* a working draft: it is never sent automatically, and by hand only after an explicit confirmation in the case.
*/
class DocumentReleases
{
public static function isReleased(DocumentKind $kind, ?Tenant $tenant = null): bool
{
$entry = self::entries($tenant)[$kind->value] ?? null;
return is_array($entry) ? (bool) ($entry['released'] ?? false) : $kind->releasedByDefault();
}
/**
* @return array{released: bool, by: ?string, at: ?string}|null the landlord's decision, null when none was made
*/
public static function decision(DocumentKind $kind, ?Tenant $tenant = null): ?array
{
$entry = self::entries($tenant)[$kind->value] ?? null;
return is_array($entry) ? ['released' => (bool) ($entry['released'] ?? false), 'by' => $entry['by'] ?? null, 'at' => $entry['at'] ?? null] : null;
}
/**
* Stores the decision for one kind; an unchanged decision keeps its date and author.
*/
public static function set(DocumentKind $kind, bool $released, string $actor, ?Tenant $tenant = null): void
{
$tenant ??= Settings::tenant();
if ($tenant === null || self::isReleased($kind, $tenant) === $released && self::decision($kind, $tenant) !== null) {
return;
}
$entries = self::entries($tenant);
$entries[$kind->value] = ['released' => $released, 'by' => $actor, 'at' => now()->toIso8601String()];
$tenant->update(['document_releases' => $entries]);
}
/**
* @return array<string, mixed>
*/
private static function entries(?Tenant $tenant): array
{
return (array) (($tenant ?? Settings::tenant())?->document_releases ?? []);
}
}
+171
View File
@@ -0,0 +1,171 @@
<?php
namespace App\Documents;
use App\Models\Booking;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Process\ProcessSettings;
use App\Support\Content;
use Filament\Forms\Components\RichEditor\RichContentRenderer;
use Illuminate\Support\HtmlString;
/**
* The terms of one offer version, frozen when the offer is made (bookings.offer_terms): contract texts,
* payment period and landlord/bank data. Offer page, PDFs, acceptance and confirmation read from this snapshot,
* so later changes of the website texts never alter an offer the guest already received.
* Bookings without a snapshot (created before it existed) fall back to the live texts.
*/
class OfferTerms
{
/** Website text keys that form part of the contract. */
public const TEXT_KEYS = [
'contract.intro',
'contract.terms',
'contract.closing',
'stay.cancellation',
'stay.house_rules',
'offer.contract_note',
'offer.accept_note',
'offer.accept_button',
];
/**
* @return array{captured_at: string, template: ?array{id: int, name: string, version: int}, texts: array<string, ?string>, deposit_due_days: int, owner: array<string, mixed>, bank: array<string, mixed>}
*/
public static function capture(?ContractTemplate $template = null, ?Booking $booking = null, ?array $annexIds = null): array
{
$overrides = $template?->overrides() ?? [];
$annexes = $annexIds !== null
? ContractAnnex::query()->whereIn('id', $annexIds)->orderBy('name')->get()
: ($template !== null && $booking !== null ? $template->annexesFor($booking) : collect());
return [
'captured_at' => now()->toIso8601String(),
'template' => $template ? ['id' => $template->id, 'name' => $template->name, 'version' => $template->version] : null,
'document' => $template?->hasDocument() ? ['body' => $template->body, 'annex_title' => $template->annex_title, 'annex_body' => $template->annex_body] : null,
'annex_ids' => $annexes->pluck('id')->all(),
'annexes' => $annexes->map(fn (ContractAnnex $annex): array => ['id' => $annex->id, 'name' => $annex->name, 'version' => $annex->version, 'title' => $annex->title, 'body' => $annex->body])->values()->all(),
'cancellation_policy' => $template?->cancellationPolicy?->snapshot(),
'property_data' => (array) ($booking?->property?->contract_data ?? []),
'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => $overrides[$key] ?? Content::get($key)])->all(),
'deposit_due_days' => (int) config('fewo.deposit_due_days'),
'owner' => (array) config('fewo.owner'),
'bank' => (array) config('fewo.bank'),
];
}
/**
* The contract template for a case: chosen explicitly, else the one of its process settings – the channel's
* template for the case's intake kind (request or binding booking), else the property's, else the landlord's.
*/
public static function templateFor(Booking $booking, int|string|null $explicitId = null): ?ContractTemplate
{
$id = filled($explicitId) ? (int) $explicitId : app(ProcessSettings::class)->forBooking($booking)->contractTemplateId();
return $id ? ContractTemplate::query()->find($id) : null;
}
/**
* The contract as a complete document (placeholders filled), or null when the offer uses the text blocks.
*
* @return array{body: string, annex_title: ?string, annex: ?string}|null
*/
public static function document(Booking $booking): ?array
{
$document = $booking->offer_terms['document'] ?? null;
if (! is_array($document) || blank($document['body'] ?? null)) {
return null;
}
$data = (array) ($booking->offer_terms['property_data'] ?? []);
$render = fn (?string $html): ?string => filled($html) ? (string) RichContentRenderer::make(ContractPlaceholders::render($html, $booking, $data))->toHtml() : null;
return ['body' => (string) $render($document['body']), 'annex_title' => $document['annex_title'] ?? null, 'annex' => $render($document['annex_body'] ?? null)];
}
/**
* The annexes frozen in the offer, with placeholders filled.
*
* @return list<array{title: string, name: string, version: int, html: string}>
*/
public static function annexes(Booking $booking): array
{
$data = (array) ($booking->offer_terms['property_data'] ?? []);
return collect((array) ($booking->offer_terms['annexes'] ?? []))->map(fn (array $annex): array => [
'title' => (string) $annex['title'],
'name' => (string) $annex['name'],
'version' => (int) $annex['version'],
'html' => (string) RichContentRenderer::make(ContractPlaceholders::render((string) $annex['body'], $booking, $data))->toHtml(),
])->values()->all();
}
public static function text(Booking $booking, string $key): ?string
{
$texts = $booking->offer_terms['texts'] ?? null;
return is_array($texts) ? ($texts[$key] ?? null) : Content::get($key);
}
public static function html(Booking $booking, string $key): HtmlString
{
$value = self::text($booking, $key);
return new HtmlString(filled($value) ? RichContentRenderer::make($value)->toHtml() : '');
}
public static function depositDueDays(Booking $booking): int
{
return (int) ($booking->offer_terms['deposit_due_days'] ?? config('fewo.deposit_due_days'));
}
/**
* @return array<string, mixed>
*/
public static function owner(Booking $booking): array
{
return $booking->offer_terms['owner'] ?? (array) config('fewo.owner');
}
/**
* @return array<string, mixed>
*/
public static function bank(Booking $booking): array
{
return $booking->offer_terms['bank'] ?? (array) config('fewo.bank');
}
/**
* Fingerprint of everything the guest agrees to in this offer version. The validity (hold_expires_at) is
* not part of it – the landlord may extend it – but is checked separately.
*/
public static function hash(Booking $booking): string
{
return hash('sha256', json_encode(self::canonical([
'version' => $booking->offer_version,
'arrival' => $booking->arrival->toDateString(),
'departure' => $booking->departure->toDateString(),
'guests' => $booking->guests,
'quote' => $booking->quote,
'total' => $booking->total,
'deposit' => $booking->deposit,
'balance_due_on' => $booking->balance_due_on->toDateString(),
'terms' => $booking->offer_terms,
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
}
private static function canonical(mixed $value): mixed
{
if (! is_array($value)) {
return $value;
}
$value = array_map(self::canonical(...), $value);
if (! array_is_list($value)) {
ksort($value);
}
return $value;
}
}
+46 -15
View File
@@ -2,40 +2,71 @@
namespace App\Documents;
use App\Enums\DocumentKind;
use App\Models\Booking;
use App\Models\Site;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
/**
* The rental contract as PDF. As a draft it is part of the offer (offer_path, one file per offer version);
* the final contract is generated at confirmation (contract_path). Both are stored, so later changes of
* texts or prices do not alter a document the guest already received.
* The PDF of a case's document. As a draft it is part of the offer (offer_path, one file per offer version); the
* document of record – rental contract, booking documentation of a portal booking or stay confirmation, depending on
* the case – is generated once when it is sent (contract_path). Both are stored, so later changes of texts or prices do
* not alter a document the guest already received.
*/
class RentalContract
{
private const DISK = 'local';
public function generate(Booking $booking, bool $draft = false): string
public function generate(Booking $booking, bool $draft = false, ?DocumentKind $kind = null): string
{
$booking->loadMissing(['guest', 'property']);
$kind = $draft ? DocumentKind::Offer : ($kind ?? DocumentKind::forCase($booking) ?? DocumentKind::Confirmation);
$filename = $draft
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
: "contracts/Mietvertrag-{$booking->reference}.pdf";
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename);
? "Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
: "{$kind->fileName()}-{$booking->reference}.pdf";
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/{$filename}";
// The document of record is never rewritten once stored (confirmation resends reuse it).
if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) {
return $booking->contract_path;
}
$pdf = $this->render($booking, $kind, $draft);
Storage::disk(self::DISK)->put($path, $pdf);
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]);
return $path;
}
/**
* The PDF bytes of a document, without storing anything (also used for previews of a composition).
*/
public function render(Booking $booking, DocumentKind $kind, bool $draft = false): string
{
[$view, $data] = $this->view($booking, $kind, $draft);
return Pdf::loadView($view, $data)->setPaper('a4')->output();
}
/**
* The view and its data that make up the document.
*
* @return array{0: string, 1: array<string, mixed>}
*/
public function view(Booking $booking, DocumentKind $kind, bool $draft = false): array
{
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
// fetching anything over the network. Each website has its own (A14).
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
$document = $kind === DocumentKind::StayConfirmation ? null : OfferTerms::document($booking);
$view = match (true) {
$kind === DocumentKind::StayConfirmation => 'pdf.stay-confirmation',
$document !== null => 'pdf.contract-document',
default => 'pdf.contract',
};
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', [
'booking' => $booking,
'draft' => $draft,
'logo' => $logo,
])->setPaper('a4')->output());
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
return $path;
return [$view, ['booking' => $booking, 'draft' => $draft, 'logo' => $logo, 'document' => $document, 'kind' => $kind]];
}
public function absolutePath(Booking $booking, bool $draft = false): ?string
+65
View File
@@ -0,0 +1,65 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* Where an activity of a case stands (docs/Prozessarchitektur/Querschnitt/Gates_und_Nachweise.md: done by us, done
* externally, not applicable, open, contradictory) – plus "waiting" for somebody else and "later" for what is not due.
*/
enum ActivityState: string implements HasColor, HasLabel
{
case Done = 'done';
case External = 'external';
case Open = 'open';
case Problem = 'problem';
case Waiting = 'waiting';
case Later = 'later';
case NotApplicable = 'not_applicable';
public function getLabel(): string
{
return match ($this) {
self::Done => 'erledigt',
self::External => 'übernimmt das Portal',
self::Open => 'zu tun',
self::Problem => 'Problem',
self::Waiting => 'wartet',
self::Later => 'später',
self::NotApplicable => 'entfällt',
};
}
public function getColor(): string
{
return match ($this) {
self::Done, self::External => 'success',
self::Open => 'warning',
self::Problem => 'danger',
self::Waiting => 'info',
self::Later, self::NotApplicable => 'gray',
};
}
public function icon(): string
{
return match ($this) {
self::Done, self::External => '✓',
self::Open => '●',
self::Problem => '!',
self::Waiting => '…',
self::Later => '○',
self::NotApplicable => '–',
};
}
/**
* Whether the landlord has to act.
*/
public function needsAction(): bool
{
return $this === self::Open || $this === self::Problem;
}
}
+6 -13
View File
@@ -2,16 +2,12 @@
namespace App\Enums;
use App\Filament\Pages\Dashboard;
use App\Filament\Pages\OccupancyCalendar;
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\ChannelTasks\ChannelTaskResource;
use App\Filament\Resources\Guests\GuestResource;
use App\Filament\Resources\Photos\PhotoResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Filament\Resources\Reviews\ReviewResource;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
@@ -24,21 +20,18 @@ enum AdminMode: string implements HasDescription, HasLabel
case Expert = 'expert';
/**
* Menu entries of the simple mode: day-to-day work with requests, bookings, contracts and the calendar.
* Menu entries of the simple mode: the start page with everything to do, calendar, cases, guests, blocked periods
* and prices. Tasks, portal tasks and the mailbox are part of the start page's work list.
*
* @var list<class-string>
*/
public const SIMPLE_NAVIGATION = [
Dashboard::class,
OccupancyCalendar::class,
BookingResource::class,
PortalOccupationResource::class,
GuestResource::class,
BlockedPeriodResource::class,
PricesAndOffers::class,
GuestResource::class,
ChannelTaskResource::class,
ChannelResource::class,
ReviewResource::class,
PhotoResource::class,
];
public function getLabel(): string
@@ -52,7 +45,7 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
self::Simple => 'Das Tägliche: Start mit allem, was zu tun ist, Kalender, Vorgänge, Gäste, Sperrzeiten, Preise',
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
};
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Enums;
use App\Mail\PaymentReminder;
use Filament\Support\Contracts\HasLabel;
/**
* What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is
* sent to the guest until the landlord has checked the payment and chooses to send the mail.
*/
enum BookingTaskKind: string implements HasLabel
{
case DepositReminder = 'deposit_reminder';
case BalanceRequest = 'balance_request';
case BalanceReminder = 'balance_reminder';
case CancellationRequest = 'cancellation_request';
case CancellationFee = 'cancellation_fee';
case PortalCancellation = 'portal_cancellation';
case PortalCancellationReported = 'portal_cancel_reported';
case PortalChangeReported = 'portal_change_reported';
public function getLabel(): string
{
return match ($this) {
self::DepositReminder => 'Anzahlung überfällig – anmahnen',
self::BalanceRequest => 'Restzahlung bald fällig – anfordern',
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
self::CancellationRequest => 'Stornierungswunsch des Gastes',
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
self::PortalCancellation => 'Stornierung im Portal veranlassen bzw. prüfen',
self::PortalCancellationReported => 'Das Portal meldet eine Stornierung – bitte prüfen',
self::PortalChangeReported => 'Das Portal meldet eine Änderung – bitte prüfen',
};
}
public function isPayment(): bool
{
return ! in_array($this, [self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported], true);
}
/**
* The mail kind (App\Mail\PaymentReminder) and the booking column that records its dispatch.
*
* @return array{0: string, 1: string}|null
*/
public function reminder(): ?array
{
return match ($this) {
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
self::CancellationRequest, self::CancellationFee, self::PortalCancellation, self::PortalCancellationReported, self::PortalChangeReported => null,
};
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum BookingTaskStatus: string implements HasColor, HasLabel
{
case Open = 'open';
case Done = 'done';
case Dismissed = 'dismissed';
public function getLabel(): string
{
return match ($this) {
self::Open => 'Offen',
self::Done => 'Erledigt',
self::Dismissed => 'Verworfen',
};
}
public function getColor(): string
{
return match ($this) {
self::Open => 'warning',
self::Done => 'success',
self::Dismissed => 'gray',
};
}
}
+29
View File
@@ -0,0 +1,29 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* What the cancellation link in the booking confirmation does.
*/
enum CancellationMode: string implements HasLabel
{
/** The guest sends a request; the landlord decides and settles costs. */
case Request = 'request';
/** The booking is cancelled at once and the dates are released. */
case Instant = 'instant';
/** Cancelled at once while the stay is still far enough away (free cancellation), otherwise a request. */
case InstantWhenFree = 'instant_when_free';
public function getLabel(): string
{
return match ($this) {
self::Request => 'Nur Stornierungswunsch – ich entscheide',
self::Instant => 'Sofort stornieren (Ein-Klick)',
self::InstantWhenFree => 'Sofort stornieren bis zur Frist der kostenfreien Stornierung, danach Wunsch',
};
}
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* Whether bookings and requests recognised on a channel become cases by themselves (UMSETZUNGSPLAN_v0.10 §5.5). Every
* channel starts switched off; observing only records what would happen. Creating cases never sends anything that the
* landlord has not released (documents need their release, package 3); only the last mode lets the new cases follow
* the automatic handling of the settings.
*/
enum CaseIntakeMode: string implements HasDescription, HasLabel
{
case Off = 'off';
case Observe = 'observe';
case Create = 'create';
case Continue = 'continue';
public function getLabel(): string
{
return match ($this) {
self::Off => 'Aus – Sie übernehmen Buchungen selbst',
self::Observe => 'Beobachten – nur protokollieren, was entstehen würde',
self::Create => 'Vorgänge anlegen – die nächsten Schritte geben Sie frei',
self::Continue => 'Vorgänge anlegen und nach Ihren Einstellungen weiterbearbeiten',
};
}
public function getDescription(): string
{
return match ($this) {
self::Off => 'Erkannte Buchungen erscheinen als Klärungsfall; nichts entsteht automatisch.',
self::Observe => 'Es entsteht nichts. Das Eingangsprotokoll zeigt, welche Vorgänge entstanden wären und warum.',
self::Create => 'Sicher erkannte Buchungen werden zum Vorgang; Sie geben jeden weiteren Schritt frei.',
self::Continue => 'Wie „anlegen“; danach laufen die Vorgänge automatisch oder mit Freigabe – wie unter „So arbeite ich“ eingestellt.',
};
}
public function records(): bool
{
return $this !== self::Off;
}
public function creates(): bool
{
return in_array($this, [self::Create, self::Continue], true);
}
}
+60
View File
@@ -0,0 +1,60 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* The business constellation of a case (docs/Prozessarchitektur/01_Buchungsarchetypen.md). It follows from the way
* the case came in and who handles what – not from the channel's name alone.
*/
enum CaseType: string implements HasDescription, HasLabel
{
/** Own website or own direct way (phone, e-mail): request, own offer, acceptance. */
case A1 = 'a1';
/** Non-binding request passed on by an intermediary; own offer like A1. */
case A2 = 'a2';
/** Binding external booking, everything else is handled by the landlord. */
case A3 = 'a3';
/** Binding external booking with split handling (e.g. the portal collects the payments). */
case A4 = 'a4';
/** Binding external booking the portal handles almost completely. */
case A5 = 'a5';
/** Own use, private stay, maintenance or another block. */
case A6 = 'a6';
public function getLabel(): string
{
return match ($this) {
self::A1 => 'Eigene Anfrage',
self::A2 => 'Anfrage über ein Portal',
self::A3 => 'Portalbuchung, Abwicklung bei uns',
self::A4 => 'Portalbuchung, Zahlung über das Portal',
self::A5 => 'Portalbuchung, Abwicklung durch das Portal',
self::A6 => 'Eigene Nutzung / Sperre',
};
}
public function getDescription(): string
{
return match ($this) {
self::A1 => 'Anfrage → Angebot → Annahme durch den Gast',
self::A2 => 'Anfrage aus einem Portal, Angebot und Vertrag von uns',
self::A3 => 'Beim Portal schon verbindlich; Unterlagen, Zahlung und Gastkontakt übernehmen wir',
self::A4 => 'Beim Portal schon verbindlich; Unterlagen von uns, das Geld zieht das Portal ein',
self::A5 => 'Beim Portal schon verbindlich; das Portal erledigt Vertrag und Zahlung',
self::A6 => 'Eigenbelegung, private Überlassung, Wartung oder sonstige Sperre',
};
}
public function isExternallyBinding(): bool
{
return in_array($this, [self::A3, self::A4, self::A5], true);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* How far a block (or release) on a portal is proven (E-018). The three steps are different statements: entering the
* block does not show that the portal took it over, and a calendar feed we provide proves nothing about the portal.
*/
enum ChannelTaskProof: string implements HasColor, HasLabel
{
/** The change was made or started (by hand or by an automation). */
case Initiated = 'initiated';
/** The block was seen in the portal's own calendar. */
case Observed = 'observed';
/** The portal confirmed it (e.g. its own confirmation or a test booking was refused). */
case Confirmed = 'confirmed';
public function getLabel(): string
{
return match ($this) {
self::Initiated => 'veranlasst',
self::Observed => 'im Portal gesehen',
self::Confirmed => 'Wirksamkeit bestätigt',
};
}
public function getColor(): string
{
return match ($this) {
self::Initiated => 'warning',
self::Observed => 'info',
self::Confirmed => 'success',
};
}
/**
* The choice the landlord reads when completing a task.
*/
public function question(bool $block = true): string
{
$what = $block ? 'gesperrt' : 'freigegeben';
return match ($this) {
self::Initiated => "Ich habe den Zeitraum im Portal {$what}.",
self::Observed => "… und im Kalender des Portals gesehen, dass er {$what} ist.",
self::Confirmed => 'Das Portal hat es bestätigt (z. B. Bestätigung oder Testanfrage abgelehnt).',
};
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* The parts of the daily/weekly summary a landlord can choose (System › Betrieb › Benachrichtigungen).
*/
enum DigestSection: string implements HasDescription, HasLabel
{
case Inbox = 'inbox';
case Requests = 'requests';
case News = 'news';
case Stays = 'stays';
case Payments = 'payments';
case Portals = 'portals';
case Reviews = 'reviews';
public function getLabel(): string
{
return match ($this) {
self::Inbox => 'Postfach',
self::Requests => 'Offene Anfragen und Angebote',
self::News => 'Neu seit der letzten Übersicht',
self::Stays => 'An- und Abreisen',
self::Payments => 'Zahlungsaufgaben und Gästewünsche',
self::Portals => 'Portale: Aufgaben und Klärungsfälle',
self::Reviews => 'Bewertungen zur Freigabe',
};
}
public function getDescription(): string
{
return match ($this) {
self::Inbox => 'Ungelesene Meldungen, z. B. mögliche Doppelbuchungen',
self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist',
self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen',
self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage',
self::Payments => 'Offene Aufgaben: fällige Zahlungen (nur wo Sie selbst mahnen) und Stornierungswünsche',
self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler',
self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind',
};
}
/**
* @param list<string>|null $values stored choice; null = everything
* @return list<self>
*/
public static function chosen(?array $values): array
{
return $values === null ? self::cases() : array_values(array_filter(self::cases(), fn (self $section): bool => in_array($section->value, $values, true)));
}
}
+121
View File
@@ -0,0 +1,121 @@
<?php
namespace App\Enums;
use App\Models\Booking;
use Filament\Support\Contracts\HasLabel;
/**
* The kinds of documents a case can produce (UMSETZUNGSPLAN_v0.10 §5.4). Which one a case needs follows from its case
* type, never from a choice of the landlord: a request gets a binding offer, a booking we made ourselves gets the
* confirmation with the rental contract, a booking that is already binding on a portal gets the booking documentation
* without an acceptance link (E-004). Information "unter Vorbehalt" (package 7) and the stay confirmation of A6
* (package 6) are prepared as working drafts but cannot be sent yet.
*/
enum DocumentKind: string implements HasLabel
{
case Offer = 'offer';
case Information = 'information';
case Confirmation = 'confirmation';
case ExternalRecord = 'external_record';
case StayConfirmation = 'stay_confirmation';
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Offer => 'Angebot mit Annahmelink',
self::Information => 'Auskunft unter Vorbehalt',
self::Confirmation => 'Buchungsbestätigung mit Mietvertrag',
self::ExternalRecord => 'Buchungsunterlagen (beim Portal gebucht)',
self::StayConfirmation => 'Aufenthaltsbestätigung (privat)',
self::Internal => 'Nur intern, kein Dokument an Gäste',
};
}
/**
* What the landlord reads about this kind on the settings page.
*/
public function description(): string
{
return match ($this) {
self::Offer => 'Für Anfragen: Preis, Vertragsentwurf und ein Link, mit dem der Gast verbindlich annimmt.',
self::Information => 'Für Anfragen ohne Reservierung: Preis und Verfügbarkeit ohne Zusage; der Gast kann die Buchung anfragen. Folgt mit Paket 7.',
self::Confirmation => 'Nach der Annahme eines Angebots oder einer direkt vereinbarten Buchung: Bestätigung mit dem Mietvertrag.',
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. Folgt mit Paket 6.',
self::Internal => 'Eigennutzung und Wartung: kein Dokument an Gäste.',
};
}
/**
* The document a case needs at its current stage, or null when nobody needs one from us (e.g. the portal sends it).
*/
public static function forCase(Booking $booking): ?self
{
$profile = $booking->process();
return match (true) {
$booking->intake === IntakeKind::Internal => $booking->guest_id !== null ? self::StayConfirmation : self::Internal,
$booking->caseType()->isExternallyBinding() => $profile->documents() === Responsibility::Portal ? null : self::ExternalRecord,
$booking->isBinding() => $profile->documents() === Responsibility::Portal ? null : self::Confirmation,
default => self::Offer,
};
}
/**
* Whether the guest makes the contract by accepting this document (only the offer carries an acceptance link).
*/
public function hasAcceptanceLink(): bool
{
return $this === self::Offer;
}
/**
* Whether a rental contract is part of this document.
*/
public function containsContract(): bool
{
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true);
}
/**
* Whether this kind can be sent with the current packages (the others exist as working drafts only).
*/
public function isAvailable(): bool
{
return in_array($this, [self::Offer, self::Confirmation, self::ExternalRecord], true);
}
/**
* Whether the texts of this kind count as released while the landlord has not decided otherwise: the offer and the
* confirmation are the documents in use since the start; every new kind starts as a working draft.
*/
public function releasedByDefault(): bool
{
return in_array($this, [self::Offer, self::Confirmation], true);
}
/**
* Whether this kind goes to guests at all.
*/
public function isForGuests(): bool
{
return $this !== self::Internal;
}
/**
* File name prefix of the stored PDF.
*/
public function fileName(): string
{
return match ($this) {
self::Offer => 'Angebot',
self::Information => 'Auskunft',
self::Confirmation => 'Mietvertrag',
self::ExternalRecord => 'Buchungsunterlagen',
self::StayConfirmation => 'Aufenthaltsbestaetigung',
self::Internal => 'Intern',
};
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* What an inbox message is about.
*/
enum InboxMessageKind: string implements HasColor, HasLabel
{
case ChannelConflict = 'channel_conflict';
case ConfirmationFailed = 'confirmation_failed';
case OfferMailFailed = 'offer_mail_failed';
case OfferRejected = 'offer_rejected';
case SyncFailed = 'sync_failed';
public function getLabel(): string
{
return match ($this) {
self::ChannelConflict => 'Mögliche Doppelbuchung',
self::ConfirmationFailed => 'Buchungsbestätigung nicht zugestellt',
self::OfferMailFailed => 'Angebot nicht zugestellt',
self::OfferRejected => 'Annahme abgewiesen',
self::SyncFailed => 'Kalenderabgleich gestört',
};
}
public function getColor(): string
{
return match ($this) {
self::ChannelConflict, self::SyncFailed => 'danger',
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
};
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How a case arrived – the "Eingangsart". Settings of a channel may differ per intake kind, because one portal can
* deliver both mere requests and bookings that are already binding.
*/
enum IntakeKind: string implements HasLabel
{
/** A request that is not binding yet (own website, phone, a portal passing on a request). */
case Inquiry = 'inquiry';
/** A booking that is already binding when it reaches us (made on a portal). */
case Booking = 'booking';
/** An internal occasion: own use, private stay, maintenance, block. */
case Internal = 'internal';
public function getLabel(): string
{
return match ($this) {
self::Inquiry => 'Anfrage',
self::Booking => 'Verbindliche Buchung',
self::Internal => 'Eigene Nutzung / Sperre',
};
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* What the intake made of one incoming event (portal calendar entry or portal e-mail).
*/
enum IntakeOutcome: string implements HasColor, HasLabel
{
/** A booking binding on the portal, recognised with confidence: a new case (A3–A5). */
case Create = 'create';
/** A non-binding request through the portal: a new request case (A2). */
case Inquiry = 'inquiry';
/** The same booking as an existing case (reference, same portal and dates, or its calendar mirror). */
case Link = 'link';
/** Not certain enough: the landlord clarifies. */
case Clarify = 'clarify';
/** No booking of this portal (block, mirror of another portal, own use, already clarified). */
case Ignore = 'ignore';
/** The portal reports a cancellation of a known case. */
case CancellationSignal = 'cancellation';
/** The portal reports other dates for a known case, or its calendar entry disappeared. */
case ChangeSignal = 'change';
public function getLabel(): string
{
return match ($this) {
self::Create => 'Neuer Vorgang (Buchung)',
self::Inquiry => 'Neuer Vorgang (Anfrage)',
self::Link => 'Gehört zu vorhandenem Vorgang',
self::Clarify => 'Klärung nötig',
self::Ignore => 'Keine Buchung',
self::CancellationSignal => 'Portal meldet Stornierung',
self::ChangeSignal => 'Portal meldet Änderung',
};
}
public function getColor(): string
{
return match ($this) {
self::Create, self::Inquiry => 'success',
self::Link, self::Ignore => 'gray',
self::Clarify => 'warning',
self::CancellationSignal, self::ChangeSignal => 'danger',
};
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* How requests for a property are turned into offers.
*/
enum OfferMode: string implements HasLabel
{
/** The landlord reviews every request and sends the offer. */
case Manual = 'manual';
/** The offer is sent automatically when all release rules are met; otherwise the request waits for the landlord. */
case Automatic = 'automatic';
public function getLabel(): string
{
return match ($this) {
self::Manual => 'Manuell – ich prüfe jede Anfrage und sende das Angebot',
self::Automatic => 'Automatisch – Angebot sofort, wenn alle Prüfungen bestanden sind',
};
}
}
+107
View File
@@ -0,0 +1,107 @@
<?php
namespace App\Enums;
/**
* The settings that shape how a case is handled. Each one has a built-in default; the landlord sets his own default,
* a property (expert area) and a channel per intake kind may deviate. A value that is not set inherits – a deliberately
* set 0, "no" or "manual" is a value of its own.
*/
enum ProcessSetting: string
{
case Processing = 'processing';
case PreReservation = 'pre_reservation';
case HoldHours = 'hold_hours';
case Documents = 'documents';
case Payments = 'payments';
case GuestMessages = 'guest_messages';
case ArrivalInfoDaysBefore = 'arrival_info_days_before';
case ContractTemplate = 'contract_template_id';
/**
* Built-in default (the behaviour before any landlord setting existed).
*/
public function default(): string|int|bool|null
{
return match ($this) {
self::Processing => ProcessingMode::Manual->value,
self::PreReservation => true,
self::HoldHours => 48,
self::Documents, self::Payments, self::GuestMessages => Responsibility::Landlord->value,
self::ArrivalInfoDaysBefore => 3,
self::ContractTemplate => null,
};
}
/**
* The question shown to the landlord, in plain words.
*/
public function question(): string
{
return match ($this) {
self::Processing => 'Wie sollen neue Vorgänge bearbeitet werden?',
self::PreReservation => 'Soll eine Anfrage den Zeitraum im Kalender reservieren?',
self::HoldHours => 'Wie lange gilt ein Angebot (und bleibt der Zeitraum reserviert)?',
self::Documents => 'Wer schickt dem Gast Vertrag bzw. Buchungsunterlagen?',
self::Payments => 'Wer kümmert sich um die Zahlungen des Gastes?',
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?',
};
}
/**
* Intake kinds for which a channel may deviate (empty: landlord and property level only).
*
* @return list<IntakeKind>
*/
public function channelIntakes(): array
{
return match ($this) {
self::Processing, self::Payments, self::GuestMessages, self::ContractTemplate => [IntakeKind::Inquiry, IntakeKind::Booking],
self::PreReservation, self::HoldHours => [IntakeKind::Inquiry],
self::Documents => [IntakeKind::Booking],
self::ArrivalInfoDaysBefore => [],
};
}
/**
* Whether the landlord sets this on his general settings page (the template is chosen per property or channel).
*/
public function isLandlordSetting(): bool
{
return $this !== self::ContractTemplate;
}
/**
* Normalises a stored or submitted value; null means "not set".
*/
public function normalize(mixed $value): string|int|bool|null
{
if ($value === null || $value === '') {
return 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::HoldHours, self::ArrivalInfoDaysBefore, self::ContractTemplate => is_numeric($value) ? (int) $value : null,
};
}
/**
* The value in plain words, for showing where a value comes from.
*/
public function describe(string|int|bool|null $value): string
{
return match ($this) {
self::Processing => ProcessingMode::tryFrom((string) $value)?->getLabel() ?? '–',
self::Documents, self::Payments, self::GuestMessages => Responsibility::tryFrom((string) $value)?->getLabel() ?? '–',
self::PreReservation => $value ? 'ja' : 'nein',
self::HoldHours => $value.' Stunden',
self::ArrivalInfoDaysBefore => $value.' Tage vor Anreise',
self::ContractTemplate => $value === null ? 'Texte der Webseite' : 'Vorlage Nr. '.$value,
};
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Whether the system carries a case on by itself as far as the data allows, or prepares each step and waits for
* the landlord's release.
*/
enum ProcessingMode: string implements HasLabel
{
case Automatic = 'automatic';
case Manual = 'manual';
public function getLabel(): string
{
return match ($this) {
self::Automatic => 'Automatisch weiterbearbeiten',
self::Manual => 'Jeden Schritt selbst freigeben',
};
}
public static function fromOfferMode(OfferMode $mode): self
{
return $mode === OfferMode::Automatic ? self::Automatic : self::Manual;
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* Who takes care of a part of the handling: the landlord (with this system) or the portal.
*/
enum Responsibility: string implements HasLabel
{
case Landlord = 'landlord';
case Portal = 'portal';
public function getLabel(): string
{
return match ($this) {
self::Landlord => 'Wir',
self::Portal => 'Das Portal',
};
}
}
+10
View File
@@ -24,6 +24,16 @@ public static function offerOutdated(): self
return new self('Zu dieser Anfrage gibt es inzwischen ein aktualisiertes Angebot. Bitte verwenden Sie den Link aus unserer neuesten E-Mail.');
}
public static function offerChanged(): self
{
return new self('Dieses Angebot kann nicht angenommen werden, weil sich seine Angaben geändert haben. Bitte melden Sie sich bei uns – gern erstellen wir Ihnen ein neues Angebot.');
}
public static function calendarUnverified(): self
{
return new self('Wir können die Verfügbarkeit gerade nicht sicher bestätigen, daher wurde Ihre Annahme noch nicht gespeichert. Bitte versuchen Sie es in einigen Minuten noch einmal oder rufen Sie uns an – wir kümmern uns darum.');
}
public static function invalidTransition(string $statusLabel, string $action): self
{
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
@@ -0,0 +1,110 @@
<?php
namespace App\Filament\Forms;
use App\Documents\DocumentComposer;
use App\Documents\DocumentComposition;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
use App\Mail\BookingConfirmed;
use App\Mail\BookingDocumentation;
use App\Mail\OfferMade;
use App\Models\Booking;
use App\Models\User;
use Closure;
use Filament\Forms\Components\Checkbox;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\View;
use Throwable;
/**
* The composition of a document inside an action modal: the same picture for offer, confirmation and booking
* documentation, recalculated whenever the landlord adjusts something, plus the explicit confirmation that is
* required when there is something to check.
*/
class DocumentCompositionFields
{
/** @var array<string, DocumentComposition> */
private static array $compositions = [];
/**
* @param Closure(Get): array<string, mixed> $changes the adjustments currently in the form
* @return list<View|Checkbox>
*/
public static function make(Booking $booking, DocumentKind $kind, Closure $changes, ?Closure $visible = null): array
{
$compose = fn (Get $get): DocumentComposition => self::compose($booking, $kind, $changes($get));
return [
View::make('filament.document-composition')
->viewData(fn (Get $get): array => self::viewData($compose($get), $changes($get))),
Checkbox::make('acknowledged')
->label('Ich habe die Hinweise geprüft und möchte das Dokument so senden.')
->visible(fn (Get $get): bool => ($visible === null || $visible($get)) && $compose($get)->toConfirm() !== [])
->accepted(),
];
}
/**
* One composition per form state and request (the view and the confirmation box both need it).
*
* @param array<string, mixed> $changes
*/
public static function compose(Booking $booking, DocumentKind $kind, array $changes): DocumentComposition
{
$key = $booking->id.':'.$kind->value.':'.md5(serialize($changes)).':'.$booking->updated_at?->getTimestamp();
return self::$compositions[$key] ??= app(DocumentComposer::class)->compose($booking, $kind, $changes);
}
/**
* @param array<string, mixed> $changes
* @return array<string, mixed>
*/
private static function viewData(DocumentComposition $composition, array $changes): array
{
$user = auth()->user();
return [
'composition' => $composition,
'expert' => $user instanceof User && $user->adminMode() === AdminMode::Expert,
'mailPreview' => self::mailPreview($composition),
'documentPreview' => self::documentPreview($composition),
'pdfUrl' => route('filament.admin.document-preview', ['booking' => $composition->draft->getRouteKey(), 'kind' => $composition->kind->value, 'changes' => base64_encode(json_encode($changes) ?: '[]')]),
];
}
private static function mailPreview(DocumentComposition $composition): string
{
$draft = $composition->draft;
if ($draft->guest === null) {
return '<p style="font-family:sans-serif">Keine Vorschau: Der Gast ist noch nicht bekannt.</p>';
}
try {
return match ($composition->kind) {
DocumentKind::Offer => (new OfferMade($draft, '#'))->render(),
DocumentKind::ExternalRecord => (new BookingDocumentation($draft))->render(),
default => (new BookingConfirmed($draft))->render(),
};
} catch (Throwable $exception) {
report($exception);
return '<p style="font-family:sans-serif">Die Vorschau der E-Mail ist gerade nicht möglich.</p>';
}
}
private static function documentPreview(DocumentComposition $composition): string
{
try {
[$view, $data] = app(RentalContract::class)->view($composition->draft, $composition->kind, draft: $composition->kind === DocumentKind::Offer);
return view($view, $data)->render();
} catch (Throwable $exception) {
report($exception);
return '<p style="font-family:sans-serif">Die Vorschau des Dokuments ist gerade nicht möglich.</p>';
}
}
}
@@ -0,0 +1,77 @@
<?php
namespace App\Filament\Forms;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\ContractTemplate;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
/**
* Form fields of the process settings, asked as plain questions. On a deviation level (property, channel) an empty
* field means "as the level above" and the placeholder says which value that is; on the landlord level an empty field
* means the built-in default.
*/
class ProcessSettingFields
{
/**
* @param list<ProcessSetting> $settings
* @param callable(ProcessSetting): string $inherited plain-words value used when the field stays empty
* @return list<Field>
*/
public static function make(string $prefix, array $settings, callable $inherited): array
{
return array_map(fn (ProcessSetting $setting): Field => self::field($prefix.$setting->value, $setting, $inherited($setting)), $settings);
}
public static function field(string $name, ProcessSetting $setting, string $inheritedLabel): Field
{
$placeholder = 'wie Standard: '.$inheritedLabel;
return (match ($setting) {
ProcessSetting::Processing => Select::make($name)->options(ProcessingMode::class)->placeholder($placeholder)
->helperText('Automatisch: Das System sendet Angebote bzw. Unterlagen selbst, sobald alle Angaben da sind. Sonst bereitet es alles vor und Sie geben frei.'),
ProcessSetting::PreReservation => Select::make($name)->options(['1' => 'Ja – der Zeitraum ist bis zum Ablauf des Angebots reserviert', '0' => 'Nein – eine Anfrage reserviert nichts'])->placeholder($placeholder),
ProcessSetting::HoldHours => TextInput::make($name)->integer()->minValue(1)->maxValue(720)->suffix('Stunden')->placeholder($placeholder),
ProcessSetting::Documents, ProcessSetting::Payments, ProcessSetting::GuestMessages => Select::make($name)->options(Responsibility::class)->placeholder($placeholder),
ProcessSetting::ArrivalInfoDaysBefore => TextInput::make($name)->integer()->minValue(1)->maxValue(14)->suffix('Tage vor Anreise')->placeholder($placeholder),
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),
})->label($setting->question());
}
/**
* Normalised values of submitted fields; empty fields are dropped (not set = inherit).
*
* @param array<string, mixed> $data
* @param list<ProcessSetting> $settings
* @return array<string, string|int|bool>
*/
public static function values(array $data, array $settings): array
{
$values = [];
foreach ($settings as $setting) {
$value = $setting->normalize($data[$setting->value] ?? null);
if ($value !== null) {
$values[$setting->value] = $value;
}
}
return $values;
}
/**
* Stored values as form state (booleans as the select keys).
*
* @param array<string, mixed> $values
* @return array<string, mixed>
*/
public static function state(array $values): array
{
return array_map(fn (mixed $value): mixed => is_bool($value) ? ($value ? '1' : '0') : $value, $values);
}
}
+22
View File
@@ -0,0 +1,22 @@
<?php
namespace App\Filament\Pages;
use App\Filament\Concerns\FollowsAdminMode;
use BackedEnum;
use Filament\Pages\Dashboard as BaseDashboard;
use Filament\Support\Icons\Heroicon;
/**
* The start page: first "Zu erledigen", then the coming stays and key figures.
*/
class Dashboard extends BaseDashboard
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHome;
protected static ?string $navigationLabel = 'Start';
protected static ?string $title = 'Start';
}
+178
View File
@@ -0,0 +1,178 @@
<?php
namespace App\Filament\Pages;
use App\Documents\DocumentReleases;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\ProcessSettingFields;
use App\Models\Channel;
use App\Models\Property;
use App\Models\Tenant;
use App\Support\Settings;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Forms\Components\Toggle;
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\Schema;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* "So arbeite ich": the landlord's own defaults for handling cases. A portal (Kanäle › Portal) and – in the expert
* area – a property may deviate; everything not set there follows these defaults.
*/
class HandlingSettings extends Page
{
use FollowsAdminMode;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsVertical;
protected static string|UnitEnum|null $navigationGroup = 'System';
protected static ?string $navigationLabel = 'So arbeite ich';
protected static ?string $title = 'So arbeite ich';
protected static ?string $slug = 'abwicklung';
protected static ?int $navigationSort = 2;
/** @var array<string, mixed> */
public array $data = [];
public static function canAccess(): bool
{
return (bool) auth()->user()?->hasRole(UserRole::Admin);
}
/**
* @return list<ProcessSetting>
*/
public static function settings(): array
{
return array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => $setting->isLandlordSetting()));
}
public function mount(): void
{
$this->form->fill([
...ProcessSettingFields::state((array) ($this->tenant()->process_defaults ?? [])),
'document_releases' => collect(self::releasableKinds())->mapWithKeys(fn (DocumentKind $kind): array => [$kind->value => DocumentReleases::isReleased($kind, $this->tenant())])->all(),
]);
}
public function form(Schema $schema): Schema
{
return $schema
->statePath('data')
->components([
Section::make('Ihre Standardeinstellungen')
->description('Gilt für alle Wohnungen und Portale, solange dort nichts anderes eingestellt ist. Neue Einstellungen gelten für neue Vorgänge; laufende Vorgänge behalten ihre Regeln.')
->columns(2)
->schema(ProcessSettingFields::make('', self::settings(), fn (ProcessSetting $setting): string => 'Grundeinstellung ('.$setting->describe($setting->default()).')')),
Section::make('Dokumente')
->description('Welche Dokumente an Gäste gehen dürfen. Eine Arbeitsfassung wird nie automatisch versendet, von Hand nur nach ausdrücklicher Bestätigung im Vorgang. Vorlagen selbst geben Sie unter Vorlagen frei.')
->schema([
...array_map(fn (DocumentKind $kind): Toggle => Toggle::make('document_releases.'.$kind->value)
->label($kind->getLabel().' – freigegeben')
->helperText(fn (): string => $kind->description().self::decisionNote($kind)), self::releasableKinds()),
Text::make(fn (): HtmlString => new HtmlString('<ul style="list-style:disc;padding-left:1.25rem">'.collect(DocumentKind::cases())
->reject(fn (DocumentKind $kind): bool => in_array($kind, self::releasableKinds(), true) || ! $kind->isForGuests())
->map(fn (DocumentKind $kind): string => '<li><strong>'.e($kind->getLabel()).'</strong>: '.e($kind->description()).' '.e($kind->isAvailable() ? '(in Verwendung; Texte unter Webseite › Texte bzw. Vorlagen)' : '(Arbeitsfassung vorbereitet, noch nicht nutzbar)').'</li>')
->implode('').'</ul>')),
]),
Section::make('Abweichungen')
->description('Wo Portale oder Wohnungen anders arbeiten. Ändern unter Portale bzw. Wohnungen (Expertenansicht).')
->collapsed()
->schema([Text::make(fn (): HtmlString => $this->deviations())]),
]);
}
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')])]),
]);
}
public function save(): void
{
$state = $this->form->getState();
$this->tenant()->update(['process_defaults' => ProcessSettingFields::values($state, self::settings())]);
foreach (self::releasableKinds() as $kind) {
DocumentReleases::set($kind, (bool) ($state['document_releases'][$kind->value] ?? false), (string) auth()->user()?->name, $this->tenant());
}
Notification::make()->title('Gespeichert')->body('Gilt für neue Vorgänge.')->success()->send();
}
/**
* Document kinds whose texts the landlord releases here: the new kinds that can already be sent. Offer and
* confirmation are in use since the start; the others are drafts of later packages.
*
* @return list<DocumentKind>
*/
public static function releasableKinds(): array
{
return array_values(array_filter(DocumentKind::cases(), fn (DocumentKind $kind): bool => $kind->isAvailable() && ! $kind->releasedByDefault()));
}
private static function decisionNote(DocumentKind $kind): string
{
$decision = DocumentReleases::decision($kind);
return $decision === null || $decision['at'] === null ? ' Bisher: Arbeitsfassung.' : ' Zuletzt geändert am '.CarbonImmutable::parse($decision['at'])->format('d.m.Y').' von '.$decision['by'].'.';
}
/**
* Every deviation of a property or a channel, in plain words.
*/
private function deviations(): HtmlString
{
$lines = [];
foreach (Property::query()->orderBy('name')->get() as $property) {
foreach ((array) ($property->process_overrides ?? []) as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting !== null && $setting->normalize($value) !== null) {
$lines[] = e($property->name).': '.e($setting->question()).' → <strong>'.e($setting->describe($setting->normalize($value))).'</strong>';
}
}
}
foreach (Channel::query()->with('property')->orderBy('name')->get() as $channel) {
foreach ((array) ($channel->process_overrides ?? []) as $intake => $values) {
foreach ((array) $values as $key => $value) {
$setting = ProcessSetting::tryFrom((string) $key);
if ($setting !== null && $setting->normalize($value) !== null) {
$lines[] = e($channel->name.' ('.$channel->property?->name.', '.(IntakeKind::tryFrom((string) $intake)?->getLabel() ?? $intake).')').': '.e($setting->question()).' → <strong>'.e($setting->describe($setting->normalize($value))).'</strong>';
}
}
}
}
return new HtmlString($lines === [] ? 'Keine – überall gelten Ihre Standardeinstellungen.' : '<ul class="list-disc ps-5 space-y-1"><li>'.implode('</li><li>', $lines).'</li></ul>');
}
private function tenant(): Tenant
{
$tenant = Settings::tenant();
abort_if($tenant === null, 404);
return $tenant;
}
}
+1 -1
View File
@@ -25,7 +25,7 @@ class OccupancyCalendar extends Page
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $title = 'Belegungsplan';
+84 -1
View File
@@ -2,6 +2,8 @@
namespace App\Filament\Pages;
use App\Actions\SendDigests;
use App\Enums\DigestSection;
use App\Enums\TenantServiceKey;
use App\Enums\UserRole;
use App\Filament\Concerns\FollowsAdminMode;
@@ -11,10 +13,12 @@
use App\Tenancy\TenantFeatures;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\CheckboxList;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TagsInput;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Pages\Page;
use Filament\Schemas\Components\Actions;
@@ -30,7 +34,7 @@
/**
* Operating data of the landlord: operating mode (test mode sends every e-mail to one test recipient only;
* live delivers to the real recipients), the addresses of the internal communication, the landlord's own
* address and bank details, and the periods. Administrators only.
* address and bank details, reminders and summaries, and the periods. Administrators only.
*/
class Operations extends Page
{
@@ -53,6 +57,11 @@ class Operations extends Page
'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)',
];
/** Choices for repeating open findings (days => label). */
public const REMINDER_INTERVALS = [0 => 'Nur einmal', 1 => 'Täglich', 2 => 'Alle 2 Tage', 3 => 'Alle 3 Tage', 7 => 'Wöchentlich'];
public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
protected static string|UnitEnum|null $navigationGroup = 'System';
@@ -99,6 +108,13 @@ public function mount(): void
'mailbox_password' => $tenant->mailbox_password,
'mailbox_encryption' => $tenant->mailbox_encryption,
'mailbox_folder' => $tenant->mailbox_folder,
'reminder_interval_days' => $tenant->reminder_interval_days,
'digest_daily' => $tenant->digest_daily,
'digest_weekly' => $tenant->digest_weekly,
'digest_weekday' => $tenant->digest_weekday,
'digest_hour' => $tenant->digest_hour,
'digest_sections' => array_map(fn (DigestSection $section): string => $section->value, DigestSection::chosen($tenant->digest_sections)),
'digest_when_empty' => $tenant->digest_when_empty,
...$this->periodValues($tenant),
]);
}
@@ -181,6 +197,43 @@ public function form(Schema $schema): Schema
->maxLength(255)
->columnSpanFull(),
]),
Section::make('Benachrichtigungen')
->description('Wie oft offene Meldungen wiederholt werden und welche Zusammenfassungen Sie per E-Mail erhalten. Empfänger sind die Adressen unter „Benachrichtigungen an“.')
->columns(2)
->schema([
Select::make('reminder_interval_days')
->label('Offene Meldungen erneut senden')
->helperText('Gilt für mögliche Doppelbuchungen (solange sie im Postfach ungelesen sind und weiter bestehen) und offene Portal-Aufgaben.')
->options(self::REMINDER_INTERVALS)
->selectablePlaceholder(false)
->required()
->columnSpanFull(),
Toggle::make('digest_daily')->label('Tägliche Zusammenfassung'),
Toggle::make('digest_weekly')->label('Wöchentliche Zusammenfassung')->live(),
Select::make('digest_hour')
->label('Versand ab')
->options(collect(range(5, 21))->mapWithKeys(fn (int $hour): array => [$hour => sprintf('%02d:00 Uhr', $hour)])->all())
->selectablePlaceholder(false)
->required(),
Select::make('digest_weekday')
->label('Wochentag der Wochenübersicht')
->helperText('An diesem Tag kommt nur die Wochenübersicht, nicht zusätzlich die tägliche.')
->options(self::WEEKDAYS)
->selectablePlaceholder(false)
->visible(fn (Get $get): bool => (bool) $get('digest_weekly'))
->required(),
CheckboxList::make('digest_sections')
->label('Inhalt der Zusammenfassung')
->options(DigestSection::class)
->descriptions(collect(DigestSection::cases())->mapWithKeys(fn (DigestSection $section): array => [$section->value => $section->getDescription()])->all())
->columns(2)
->required()
->columnSpanFull(),
Toggle::make('digest_when_empty')
->label('Auch senden, wenn nichts ansteht')
->helperText('Sonst entfällt die Zusammenfassung an Tagen ohne offene Punkte.')
->columnSpanFull(),
]),
Section::make('Portal-Postfach')
->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.')
->columns(2)
@@ -215,6 +268,29 @@ public function content(Schema $schema): Schema
]);
}
protected function getHeaderActions(): array
{
return [
Action::make('sendDigest')
->label('Zusammenfassung jetzt senden')
->icon(Heroicon::OutlinedPaperAirplane)
->color('gray')
->modalDescription('Schickt die Zusammenfassung mit den gespeicherten Einstellungen sofort an die Benachrichtigungsadressen – auch wenn nichts ansteht. Der reguläre Versand bleibt unverändert.')
->schema([
Radio::make('weekly')
->label('Welche?')
->options([0 => 'Tagesübersicht', 1 => 'Wochenübersicht'])
->default(0)
->required(),
])
->action(function (array $data): void {
app(SendDigests::class)->send($this->tenant(), (bool) $data['weekly'], force: true);
Notification::make()->title('Zusammenfassung gesendet')->body(Settings::isLive() ? null : 'Testbetrieb: Sie geht an die Testadresse.')->success()->send();
}),
];
}
public function save(): void
{
$data = $this->form->getState();
@@ -243,6 +319,13 @@ public function save(): void
'mailbox_password' => $data['mailbox_password'] ?? null,
'mailbox_encryption' => $data['mailbox_encryption'] ?? null,
'mailbox_folder' => $data['mailbox_folder'] ?? null,
'reminder_interval_days' => (int) $data['reminder_interval_days'],
'digest_daily' => (bool) $data['digest_daily'],
'digest_weekly' => (bool) $data['digest_weekly'],
'digest_weekday' => (int) ($data['digest_weekday'] ?? $tenant->digest_weekday),
'digest_hour' => (int) $data['digest_hour'],
'digest_sections' => count($data['digest_sections']) === count(DigestSection::cases()) ? null : array_values($data['digest_sections']),
'digest_when_empty' => (bool) $data['digest_when_empty'],
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
]);
+2 -2
View File
@@ -31,7 +31,7 @@ class PricesAndOffers extends Page
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCurrencyEuro;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
protected static ?string $navigationLabel = 'Preise & Angebote';
@@ -39,7 +39,7 @@ class PricesAndOffers extends Page
protected static ?string $slug = 'preise-und-angebote';
protected static ?int $navigationSort = 5;
protected static ?int $navigationSort = 0;
#[Url(as: 'wohnung')]
public ?int $propertyId = null;
@@ -45,13 +45,13 @@ class BlockedPeriodResource extends Resource
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedNoSymbol;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Sperrzeit';
protected static ?string $pluralModelLabel = 'Sperrzeiten';
protected static ?int $navigationSort = 3;
protected static ?int $navigationSort = 10;
public static function form(Schema $schema): Schema
{
@@ -128,12 +128,12 @@ public static function portalActions(): array
TextEntry::make('recognized_representation')->label('Fachliche Einordnung')->state(fn (BlockedPeriod $record): string => ICalRuleEngine::REPRESENTATIONS[$record->ical_interpretation['representation'] ?? 'unspecified']),
TextEntry::make('original')->label('Originalereignis (entfaltet)')->state(fn (BlockedPeriod $record): string => $record->ical_raw)->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']),
]),
Action::make('resolve')->label('Belegung zuordnen / klären')
Action::make('resolve')->label('Klären: eigenständig oder Doppelung?')
->visible(fn (BlockedPeriod $record): bool => ! $record->trashed() && in_array($record->source, ['channel', 'email'], true))
->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
->modalDescription('Nur nach persönlicher Prüfung zuordnen. Eine Darstellung steuert keine eigene Belegung mehr; die führende Buchung oder Sperre übernimmt Änderungen und Stornierungen. Kalenderereignisse und UIDs bleiben nachvollziehbar erhalten.')
->modalDescription('Nur nach persönlicher Prüfung klären. Eigenständig mit Buchungskanal (oder privat) gilt danach als geklärt und verschwindet aus „Ungeklärt“. Eine Doppelung steuert keine eigene Belegung mehr; die führende Buchung oder Sperre übernimmt Änderungen und Stornierungen. Kalenderereignisse und UIDs bleiben nachvollziehbar erhalten.')
->schema([
Select::make('resolution')->label('Fachliche Klärung')->options(['independent' => 'Eigenständige Belegung bestätigen', 'block' => 'Weitere Darstellung einer Kalenderbelegung (Portalreservierung oder Sperrzeit)', 'booking' => 'Weitere Darstellung einer eigenen Buchung'])->default('independent')->required()->live(),
Select::make('resolution')->label('Fachliche Klärung')->options(['independent' => 'Eigenständige Belegung – keine Doppelung (Buchungskanal unten angeben)', 'block' => 'Doppelung: dieselbe Belegung steht schon als Portalreservierung oder Sperrzeit im Kalender', 'booking' => 'Doppelung: dieselbe Belegung ist eine unserer eigenen Buchungen'])->default('independent')->required()->live(),
Select::make('target_id')->label('Führende Belegung mit demselben Zeitraum')
->visible(fn (Get $get): bool => $get('resolution') !== 'independent')
->required(fn (Get $get): bool => $get('resolution') !== 'independent')
@@ -0,0 +1,59 @@
<?php
namespace App\Filament\Resources\BookingTasks;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\BookingTasks\Pages\ListBookingTasks;
use App\Filament\Resources\BookingTasks\Tables\BookingTasksTable;
use App\Models\BookingTask;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
class BookingTaskResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = BookingTask::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBanknotes;
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Buchungsaufgabe';
protected static ?string $pluralModelLabel = 'Zahlungen & Wünsche';
protected static ?int $navigationSort = 2;
public static function table(Table $table): Table
{
return BookingTasksTable::configure($table);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = BookingTask::query()->open()->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function getPages(): array
{
return [
'index' => ListBookingTasks::route('/'),
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Filament\Resources\BookingTasks\Pages;
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\BookingTasks\BookingTaskResource;
use App\Models\Property;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
class ListBookingTasks extends ListRecords
{
use ListsCurrentProperty;
protected static string $resource = BookingTaskResource::class;
protected function scopeToProperty(Builder $query, Property $property): Builder
{
return $query->whereHas('booking', fn (Builder $booking) => $booking->where('property_id', $property->id));
}
}
@@ -0,0 +1,80 @@
<?php
namespace App\Filament\Resources\BookingTasks\Tables;
use App\Actions\SendPaymentReminder;
use App\Enums\BookingTaskStatus;
use App\Exceptions\ReservationException;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\BookingTask;
use App\Support\Money;
use Filament\Actions\Action;
use Filament\Notifications\Notification;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Throwable;
class BookingTasksTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc')
->description('Fällige Zahlungen und Wünsche von Gästen. Es wird nichts automatisch an Gäste gesendet: Bitte erst den Zahlungseingang prüfen, dann die Erinnerung per Klick senden oder die Aufgabe abhaken.')
->columns([
TextColumn::make('booking.reference')->label('Buchung')->weight('medium')->description(fn (BookingTask $record): string => $record->booking->guest?->full_name ?? ''),
TextColumn::make('kind')->label('Aufgabe')->badge(),
TextColumn::make('due_on')->label('Fällig seit')->date('d.m.Y')->placeholder('–'),
TextColumn::make('open')->label('Offen')->state(fn (BookingTask $record): string => Money::format($record->booking->openAmount())),
TextColumn::make('status')->label('Status')->badge()
->description(fn (BookingTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
TextColumn::make('note')->label('Hinweis')->wrap()->placeholder('–'),
])
->filters([
SelectFilter::make('status')->label('Status')->options(BookingTaskStatus::class)->default(BookingTaskStatus::Open->value),
])
->recordActions([
Action::make('booking')
->label('Buchung')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->color('gray')
->url(fn (BookingTask $record): string => BookingResource::getUrl('view', ['record' => $record->booking])),
Action::make('send')
->label('Mail an Gast senden')
->icon(Heroicon::OutlinedEnvelope)
->requiresConfirmation()
->modalDescription('Haben Sie den Zahlungseingang geprüft? Der Gast erhält die Zahlungs-E-Mail sofort.')
->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open && $record->kind->reminder() !== null)
->action(function (BookingTask $record, SendPaymentReminder $send): void {
try {
$send->handle($record, auth()->user()->name);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
} catch (Throwable) {
Notification::make()->title('E-Mail konnte nicht gesendet werden')->body('Die Aufgabe bleibt offen.')->danger()->send();
return;
}
Notification::make()->title('E-Mail gesendet')->success()->send();
}),
Action::make('done')
->label('Erledigt')
->icon(Heroicon::OutlinedCheck)
->color('success')
->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open)
->action(fn (BookingTask $record) => $record->complete(auth()->user()->name)),
Action::make('dismiss')
->label('Verwerfen')
->icon(Heroicon::OutlinedXMark)
->color('gray')
->requiresConfirmation()
->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open)
->action(fn (BookingTask $record) => $record->update(['status' => BookingTaskStatus::Dismissed])),
]);
}
}
@@ -8,7 +8,9 @@
use App\Filament\Resources\Bookings\Pages\CreateBooking;
use App\Filament\Resources\Bookings\Pages\ListBookings;
use App\Filament\Resources\Bookings\Pages\ViewBooking;
use App\Filament\Resources\Bookings\RelationManagers\MessagesRelationManager;
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
use App\Filament\Resources\Bookings\RelationManagers\TasksRelationManager;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
use App\Filament\Resources\Bookings\Tables\BookingsTable;
@@ -28,11 +30,11 @@ class BookingResource extends Resource
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Buchung';
protected static ?string $modelLabel = 'Vorgang';
protected static ?string $pluralModelLabel = 'Anfragen & Buchungen';
protected static ?string $pluralModelLabel = 'Vorgänge';
protected static ?string $recordTitleAttribute = 'reference';
@@ -72,6 +74,8 @@ public static function getRelations(): array
{
return [
PaymentsRelationManager::class,
TasksRelationManager::class,
MessagesRelationManager::class,
];
}
@@ -4,8 +4,14 @@
use App\Actions\ConfirmBooking;
use App\Actions\CreateReservation;
use App\Actions\SendBookingDocuments;
use App\Actions\TakeOverExternalBooking;
use App\Exceptions\ReservationException;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Bookings\Schemas\BookingForm;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
@@ -14,48 +20,79 @@
use Filament\Resources\Pages\CreateRecord;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* Entry of a new case that did not come through the website: a request (A1/A2) goes the same way as a website request,
* a booking already binding on a portal (A3–A5) is taken over as it is.
*/
class CreateBooking extends CreateRecord
{
protected static string $resource = BookingResource::class;
protected static ?string $title = 'Buchung erfassen';
protected static ?string $title = 'Neu eintragen';
/**
* @param array<string, mixed> $data
*/
protected function handleRecordCreation(array $data): Model
{
try {
$booking = app(CreateReservation::class)->handle(
Property::findOrFail($data['property_id']),
new StayRequest(
CarbonImmutable::parse($data['arrival']),
CarbonImmutable::parse($data['departure']),
(int) $data['guests'],
promoCode: $data['promo_code'] ?: null,
),
Arr::only($data, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']),
source: 'manual',
sendMails: $data['send_mails'],
);
if ($data['confirm_immediately']) {
app(ConfirmBooking::class)->handle($booking, notifyGuest: $data['send_mails']);
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Buchung nicht möglich')->body($exception->getMessage())->danger()->send();
if (($data['kind'] ?? null) === BookingForm::OWN_USE) {
$this->redirect(BlockedPeriodResource::getUrl());
$this->halt();
}
$booking->update(['internal_notes' => $data['internal_notes'] ?: null]);
try {
$property = Property::query()->findOrFail($data['property_id']);
$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']);
if ($data['kind'] === BookingForm::EXTERNAL) {
return app(TakeOverExternalBooking::class)->handle($property, $channel, $arrival, $departure, [
'guest' => $guest,
'guests' => filled($data['guests'] ?? null) ? (int) $data['guests'] : null,
'portal_reference' => $data['portal_reference'] ?? null,
'portal_total' => filled($data['portal_total'] ?? null) ? (int) $data['portal_total'] : null,
'notes' => $data['internal_notes'] ?? null,
'guest_confirmed' => (bool) ($data['guest_confirmed'] ?? false),
]);
}
$stay = new StayRequest($arrival, $departure, (int) $data['guests'], promoCode: filled($data['promo_code'] ?? null) ? $data['promo_code'] : null);
$sendMails = (bool) ($data['send_mails'] ?? false);
$booking = app(CreateReservation::class)->handle($property, $stay, $guest, source: 'manual', sendMails: $sendMails && ! ($data['confirm_immediately'] ?? false), originChannel: $channel);
if ($data['confirm_immediately'] ?? false) {
DB::transaction(fn () => app(ConfirmBooking::class)->bind($booking));
if ($sendMails && filled($booking->guest?->email)) {
// The documents go out only when their composition needs no check; otherwise they wait on the case page.
$waiting = app(SendBookingDocuments::class)->automatically($booking->fresh());
if ($waiting !== []) {
Notification::make()->title('Gebucht – Unterlagen noch nicht gesendet')->body(implode(' ', $waiting))->warning()->send();
}
} else {
app(ConfirmBooking::class)->deliver($booking->fresh(), notifyGuest: false);
}
}
} catch (QuoteException|ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
$this->halt();
}
if (filled($data['internal_notes'] ?? null)) {
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '').$data['internal_notes'])]);
}
return $booking;
}
protected function getRedirectUrl(): string
{
return BookingResource::getUrl('view', ['record' => $this->getRecord()]);
/** @var Booking $record */
$record = $this->getRecord();
return BookingResource::getUrl('view', ['record' => $record]);
}
}
@@ -2,213 +2,615 @@
namespace App\Filament\Resources\Bookings\Pages;
use App\Actions\CancelBooking;
use App\Actions\ConfirmBooking;
use App\Actions\DeclineBooking;
use App\Actions\ProvideGuestContact;
use App\Actions\SendBookingDocuments;
use App\Actions\SendOffer;
use App\Actions\SetBookingStatus;
use App\Documents\OfferTerms;
use App\Documents\RentalContract;
use App\Enums\AdminMode;
use App\Enums\BookingStatus;
use App\Enums\DocumentKind;
use App\Enums\IntakeKind;
use App\Enums\ProcessingMode;
use App\Enums\Responsibility;
use App\Exceptions\ReservationException;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Forms\DocumentCompositionFields;
use App\Filament\Resources\Bookings\BookingResource;
use App\Models\Booking;
use App\Pricing\PriceCalculator;
use App\Models\ContractAnnex;
use App\Models\ContractTemplate;
use App\Models\Extra;
use App\Models\User;
use App\Pricing\PortalPrice;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\CaseLog;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Hidden;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Notifications\Notification;
use Filament\Resources\Pages\ViewRecord;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Icons\Heroicon;
use Throwable;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
/**
* The case page. At the top only what matters now: the next step as one large button, "Beenden" and the switch between
* automatic and manual handling. Everything else that is possible right now sits under "Weitere Möglichkeiten";
* technical functions only in the expert view. Ending a case always takes the proper way – a binding booking is
* cancelled with its consequences, it cannot be "set back" by a status change.
*
* @property Booking $record
*/
class ViewBooking extends ViewRecord
{
protected static string $resource = BookingResource::class;
/** Actions for the expert view only. */
private const EXPERT = ['offerLink', 'contractText', 'setStatus'];
public function getTitle(): string
{
return "{$this->record->reference} · {$this->record->guest->full_name}";
return "{$this->record->reference} · {$this->record->guestName()}";
}
public function getSubheading(): string|Htmlable|null
{
return CaseActivities::situation($this->record);
}
protected function getHeaderActions(): array
{
return [
$actions = collect([
$this->sendOfferAction(),
$this->provideContactAction(),
$this->requestContactAction(),
AssignGuestAction::make(),
Action::make('sendOffer')
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden')
->icon(Heroicon::OutlinedPaperAirplane)
->color('success')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->modalHeading('Angebot an den Gast senden')
->modalDescription('Der Gast erhält das Angebot mit Vertragsentwurf per E-Mail und kann es über einen Link annehmen oder ablehnen. Erst mit seiner Annahme ist die Buchung verbindlich.')
->modalSubmitActionLabel('Angebot senden')
->modalWidth('3xl')
->fillForm(fn (): array => [
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'promo_code' => $this->record->promo_code,
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
'price_adjustment_label' => $this->record->price_adjustment_label,
'valid_until' => now()->addHours($this->record->property->hold_hours)->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
'guest' => $this->record->guest->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']),
])
->schema([
$this->confirmAction(),
$this->sendDocumentsAction(),
$this->resendConfirmationAction(),
$this->portalPriceAction(),
$this->extendHoldAction(),
$this->servicesAction(),
$this->offerPdfAction(),
$this->contractAction(),
$this->offerLinkAction(),
$this->contractTextAction(),
$this->notesAction(),
$this->archiveAction(),
$this->setStatusAction(),
])->keyBy(fn (Action $action): string => $action->getName());
$next = CaseActivities::next($this->record)?->action;
$primary = $next !== null && $actions->has($next) ? $actions->pull($next)->color('primary')->size('lg')->icon(Heroicon::OutlinedArrowRightCircle) : null;
$expert = $actions->only(self::EXPERT)->values()->all();
$more = $actions->except(self::EXPERT)->values()->all();
return array_values(array_filter([
$primary,
$this->automationAction(),
$this->endAction(),
ActionGroup::make($more)->label('Weitere Möglichkeiten')->icon(Heroicon::OutlinedEllipsisHorizontal)->button()->color('gray'),
$this->isExpert() ? ActionGroup::make($expert)->label('Experte')->icon(Heroicon::OutlinedWrenchScrewdriver)->button()->color('gray') : null,
]));
}
private function isExpert(): bool
{
$user = auth()->user();
return $user instanceof User && $user->adminMode() === AdminMode::Expert;
}
private function sendOfferAction(): Action
{
return Action::make('sendOffer')
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true) && $this->record->intake !== IntakeKind::Booking)
->modalHeading('Angebot an den Gast')
->modalDescription('Alles ist vorbereitet: Preis, Vertragsvorlage, Anlagen und Gültigkeit kommen aus Ihren Einstellungen. Prüfen Sie die Zusammenstellung; „Anpassen“ nur bei Bedarf. Mit „Senden“ erhält der Gast das Angebot mit einem Link zum Annehmen.')
->modalSubmitActionLabel('Senden')
->modalWidth('4xl')
->fillForm(fn (): array => [
'expected_version' => $this->record->offer_version,
'arrival' => $this->record->arrival->toDateString(),
'departure' => $this->record->departure->toDateString(),
'guests' => $this->record->guests,
'promo_code' => $this->record->promo_code,
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
'price_adjustment_label' => $this->record->price_adjustment_label,
'valid_until' => now()->addHours($this->record->process()->holdHours())->format('Y-m-d H:i'),
'offer_message' => $this->record->offer_message,
'annex_ids' => OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? [],
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']) ?? [],
])
->schema([
Hidden::make('expected_version'),
...DocumentCompositionFields::make($this->record, DocumentKind::Offer, fn (Get $get): array => $this->offerChanges(self::formState($get, ['expected_version', 'arrival', 'departure', 'guests', 'promo_code', 'price_adjustment', 'price_adjustment_label', 'valid_until', 'offer_message', 'contract_template_id', 'annex_ids', 'guest']))),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3)->live(onBlur: true),
Section::make('Anpassen')->description('Zeitraum, Preis, Vorlage, Gültigkeit, Angaben zum Gast – die Zusammenstellung oben rechnet sofort neu.')->collapsed()->schema([
Section::make('Termin')->columns(3)->schema([
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
]),
Section::make('Preis')->columns(3)->schema([
TextInput::make('promo_code')->label('Rabattcode')->helperText('Sonderkondition aus den Angeboten')->maxLength(50)->live(onBlur: true),
TextInput::make('price_adjustment')
->label('Preisanpassung')
->helperText('Minus = Nachlass, z. B. -50')
->numeric()
->step(0.01)
->suffix('€')
->live(onBlur: true),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80),
Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(),
TextInput::make('promo_code')->label('Rabattcode')->maxLength(50)->live(onBlur: true),
TextInput::make('price_adjustment')->label('Preisanpassung')->helperText('Minus = Nachlass, z. B. -50')->numeric()->step(0.01)->suffix('€')->live(onBlur: true),
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80)->live(onBlur: true),
]),
Section::make('Gültigkeit & Nachricht')->columns(2)->schema([
DateTimePicker::make('valid_until')
->label('Angebot gültig bis')
->helperText(fn (): string => 'Standard: '.$this->record->property->hold_hours.' Stunden (Einstellung der Wohnung). Bis dahin bleibt der Zeitraum reserviert.')
->seconds(false)
->after('now')
->required(),
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
...$this->templateFields(),
DateTimePicker::make('valid_until')
->label('Angebot gültig bis')
->helperText(fn (): string => 'Eingestellt: '.$this->record->process()->holdHours().' Stunden. Bis dahin bleibt der Zeitraum reserviert.')
->seconds(false)
->after('now')
->required()
->live(onBlur: true),
Section::make('Gast – so erscheint er im Vertrag')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100)->live(onBlur: true),
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150)->live(onBlur: true),
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20)->live(onBlur: true),
TextInput::make('guest.city')->label('Ort')->maxLength(100)->live(onBlur: true),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50)->live(onBlur: true),
]),
Section::make('Gast – so erscheint er im Mietvertrag')->columns(2)->collapsed()->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
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),
TextInput::make('guest.phone')->label('Telefon')->maxLength(50),
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(
fn () => $send->handle($this->record, $this->offerChanges($data)),
'Angebot gesendet',
)),
Action::make('offerLink')
->label('Angebotslink')
->icon(Heroicon::OutlinedLink)
->color('gray')
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
->modalHeading('Link zum Angebot')
->modalDescription('Derselbe Link wie in der Angebots-E-Mail – z. B. zum Weitergeben per Messenger. Gültig bis zum Ende der Angebotsfrist.')
->schema([
TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable(),
])
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen'),
Action::make('offerPdf')
->label('Angebot (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->color('gray')
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf")),
Action::make('confirm')
->label('Direkt bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->color('gray')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Buchung direkt bestätigen')
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung bereits anders verbindlich vereinbart wurde (z. B. telefonisch). Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
->schema([
Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(true),
])
->action(fn (array $data, ConfirmBooking $confirm) => $this->runWorkflow(
fn () => $confirm->handle($this->record, $data['notify']),
'Buchung bestätigt',
)),
Action::make('decline')
->label('Ablehnen')
->icon(Heroicon::OutlinedXCircle)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->requiresConfirmation()
->modalHeading('Anfrage ablehnen')
->schema([
Toggle::make('notify')->label('Absage an den Gast senden')->default(true),
])
->action(fn (array $data, DeclineBooking $decline) => $this->runWorkflow(
fn () => $decline->handle($this->record, $data['notify']),
'Anfrage abgelehnt',
)),
Action::make('extendHold')
->label('Vormerkung verlängern')
->icon(Heroicon::OutlinedClock)
->color('gray')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
->schema([
TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required(),
])
->action(function (array $data): void {
$from = $this->record->hold_expires_at?->isFuture() ? $this->record->hold_expires_at : now()->toImmutable();
$this->record->update(['hold_expires_at' => $from->addHours((int) $data['hours'])]);
]),
])
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(fn () => $send->handle($this->record, $this->offerChanges($data)), 'Angebot gesendet'));
}
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
}),
Action::make('contract')
->label('Mietvertrag')
->icon(Heroicon::OutlinedDocumentText)
->color('gray')
->visible(fn (): bool => $this->record->contract_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")),
ActionGroup::make([
Action::make('regenerateContract')
->label('Mietvertrag neu erzeugen')
->icon(Heroicon::OutlinedArrowPath)
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true))
->requiresConfirmation()
->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.')
->action(function (RentalContract $contract): void {
$contract->generate($this->record);
Notification::make()->title('Mietvertrag neu erzeugt')->success()->send();
}),
Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->fillForm(fn (): array => ['internal_notes' => $this->record->internal_notes])
->schema([
Textarea::make('internal_notes')->label('Interne Notizen')->rows(6),
])
->action(fn (array $data) => $this->record->update($data)),
Action::make('cancel')
->label('Stornieren')
->icon(Heroicon::OutlinedNoSymbol)
->color('danger')
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
->requiresConfirmation()
->modalDescription('Der Zeitraum wird wieder freigegeben. Der Gast wird nicht automatisch benachrichtigt.')
->action(function (): void {
$this->record->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
/**
* The documents of a binding case (confirmation with contract, or booking documentation of a portal booking), sent
* after the landlord saw their composition.
*/
private function sendDocumentsAction(): Action
{
return Action::make('sendDocuments')
->label(fn (): string => SendBookingDocuments::kindFor($this->record) === DocumentKind::ExternalRecord ? 'Buchungsunterlagen prüfen und senden' : 'Bestätigung prüfen und senden')
->icon(Heroicon::OutlinedPaperAirplane)
->visible(fn (): bool => $this->record->isBinding() && $this->record->confirmation_sent_at === null && $this->record->confirmation_failed_at === null && $this->record->process()->documents() === Responsibility::Landlord)
->modalHeading(fn (): string => SendBookingDocuments::kindFor($this->record)->getLabel())
->modalDescription('So gehen die Unterlagen an den Gast. „Anpassen“ nur bei Bedarf.')
->modalSubmitActionLabel('Senden')
->modalWidth('4xl')
->fillForm(fn (): array => ['annex_ids' => $this->record->contract_path === null && $this->record->offer_version === 0 ? (OfferTerms::templateFor($this->record)?->annexesFor($this->record)->pluck('id')->all() ?? []) : null])
->schema(fn (): array => [
...DocumentCompositionFields::make($this->record, SendBookingDocuments::kindFor($this->record), fn (Get $get): array => $this->documentChanges(self::formState($get, ['contract_template_id', 'annex_ids']))),
Section::make('Anpassen')->description('Vorlage und Anlagen für diesen Vorgang.')->collapsed()->visible($this->record->contract_path === null && $this->record->offer_version === 0)->schema($this->templateFields()),
])
->action(function (array $data, SendBookingDocuments $documents): void {
$this->runWorkflow(function () use ($data, $documents): void {
if (! $documents->handle($this->record, $this->documentChanges($data), (bool) ($data['acknowledged'] ?? false))) {
throw new ReservationException('Der Versand ist fehlgeschlagen (Details im Postfach). Sie können ihn über „Unterlagen erneut senden“ wiederholen.');
}
}, 'Unterlagen gesendet');
});
}
Notification::make()->title('Buchung storniert')->success()->send();
}),
/**
* Choice of template and annexes for one case; changing the template proposes its annexes.
*
* @return list<Section>
*/
private function templateFields(): array
{
return [
Section::make('Vorlage und Anlagen')->schema([
Select::make('contract_template_id')
->label('Andere Vorlage für diesen Vorgang')
->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label().($template->isReleased() ? '' : ' – nicht freigegeben')])->all())
->placeholder('wie eingestellt')
->live()
->afterStateUpdated(fn (Set $set, $state) => $set('annex_ids', OfferTerms::templateFor($this->record, $state)?->annexesFor($this->record)->pluck('id')->all() ?? [])),
Select::make('annex_ids')
->label('Anlagen')
->multiple()
->live()
->options(fn (): array => ContractAnnex::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractAnnex $annex): array => [$annex->id => $annex->label()])->all()),
]),
];
}
private function provideContactAction(): Action
{
return Action::make('provideContact')
->label(fn (): string => $this->record->guest === null ? 'Gast eintragen' : 'Kontaktdaten eintragen')
->icon(Heroicon::OutlinedUserPlus)
->visible(fn (): bool => ! 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.')
->modalWidth('3xl')
->fillForm(fn (): array => [
'guest' => $this->record->guest?->only(['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city']) ?? [],
'process' => $this->record->processingMode() === ProcessingMode::Automatic ? ProvideGuestContact::AUTOMATIC : ProvideGuestContact::MANUAL,
'guest_confirmed' => $this->record->guest_confirmed_at !== null,
])
->schema([
Section::make('Gast')->columns(2)->schema([
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
TextInput::make('guest.email')->label('E-Mail')->email()->maxLength(255),
TextInput::make('guest.phone')->label('Telefon')->tel()->maxLength(50),
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),
]),
Section::make('Wie geht es danach weiter?')->schema([
Radio::make('process')->hiddenLabel()->options([
ProvideGuestContact::AUTOMATIC => 'Automatisch weitermachen – das System sendet als Nächstes Angebot bzw. Unterlagen',
ProvideGuestContact::MANUAL => 'Nur speichern – den nächsten Schritt gebe ich selbst frei',
])->required(),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung per E-Mail bestätigt'),
]),
])
->action(function (array $data, ProvideGuestContact $provide): void {
try {
$message = $provide->handle($this->record, $data['guest'], $data['process'], (bool) $data['guest_confirmed']);
} catch (ReservationException|QuoteException $exception) {
$this->record->refresh();
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
Notification::make()->title($message)->success()->send();
});
}
private function requestContactAction(): Action
{
return Action::make('requestContact')
->label('Gast um Kontaktdaten bitten')
->icon(Heroicon::OutlinedChatBubbleLeftEllipsis)
->visible(fn (): bool => blank($this->record->guest?->email) && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired], true))
->modalHeading('Gast um Kontaktdaten bitten')
->modalDescription('Den Text im Nachrichtenfenster des Portals einfügen (Sie senden ihn selbst). „Als angefragt vermerken“ hält fest, dass die Daten erfragt sind.')
->modalSubmitActionLabel('Als angefragt vermerken')
->fillForm(fn (): array => ['text' => $this->contactRequestText()])
->schema([Textarea::make('text')->label('Nachricht an den Gast')->rows(10)->extraInputAttributes(['readonly' => true, 'onclick' => 'this.select()'])])
->action(function (): void {
$this->record->forceFill(['contact_requested_at' => now()])->save();
Notification::make()->title('Als angefragt vermerkt')->success()->send();
});
}
private function confirmAction(): Action
{
$kind = fn (): DocumentKind => $this->record->intake === IntakeKind::Booking ? DocumentKind::ExternalRecord : DocumentKind::Confirmation;
return Action::make('confirm')
->label('Direkt verbindlich bestätigen')
->icon(Heroicon::OutlinedCheckCircle)
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
->modalHeading('Buchung direkt bestätigen')
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung schon anders verbindlich vereinbart wurde (z. B. am Telefon). Der Zeitraum wird fest belegt.')
->modalSubmitActionLabel('Bestätigen')
->modalWidth('4xl')
->fillForm(fn (): array => ['notify' => filled($this->record->guest?->email)])
->schema(fn (): array => [
Toggle::make('notify')->label('Unterlagen an den Gast senden')->live(),
Group::make(DocumentCompositionFields::make($this->record, $kind(), fn (Get $get): array => [], fn (Get $get): bool => (bool) $get('notify')))
->visible(fn (Get $get): bool => (bool) $get('notify')),
])
->action(function (array $data, ConfirmBooking $confirm, SendBookingDocuments $documents) use ($kind): void {
$notify = (bool) ($data['notify'] ?? false);
$acknowledged = (bool) ($data['acknowledged'] ?? false);
if ($notify) {
$composition = DocumentCompositionFields::compose($this->record, $kind(), []);
if (! $composition->canSendByHand($acknowledged)) {
Notification::make()->title('Nicht möglich')->body(implode(' ', [...$composition->blockers(), ...$composition->toConfirm()]))->danger()->send();
return;
}
}
$this->runWorkflow(function () use ($confirm, $documents, $notify, $acknowledged): void {
DB::transaction(fn () => $confirm->bind($this->record));
$notify ? $documents->handle($this->record->fresh(), [], $acknowledged) : $confirm->deliver($this->record->fresh(), notifyGuest: false);
}, 'Buchung bestätigt');
});
}
private function resendConfirmationAction(): Action
{
return Action::make('resendConfirmation')
->label(fn (): string => match (true) {
$this->record->confirmation_failed_at !== null && $this->record->confirmation_sent_at === null => 'Unterlagen erneut senden (Versand fehlgeschlagen)',
$this->record->confirmation_sent_at === null => 'Unterlagen an den Gast senden',
default => 'Bestätigung erneut senden',
})
->icon(Heroicon::OutlinedEnvelope)
->visible(fn (): bool => $this->record->isBinding() && filled($this->record->guest?->email) && ($this->record->confirmation_sent_at !== null || $this->record->confirmation_failed_at !== null))
->requiresConfirmation()
->modalDescription(fn (): string => 'Der Gast erhält dieselben Unterlagen noch einmal (Vorlage: '.(isset($this->record->offer_terms['template']['name']) ? $this->record->offer_terms['template']['name'].', Version '.$this->record->offer_terms['template']['version'] : 'Texte der Webseite').').')
->action(function (ConfirmBooking $confirm): void {
if ($this->record->contract_path === null) {
Notification::make()->title('Bitte zuerst prüfen')->body('Die Unterlagen wurden noch nie erstellt – bitte über „Unterlagen prüfen und senden“.')->warning()->send();
return;
}
$sent = $confirm->resend($this->record->fresh());
$this->record->refresh();
$notification = Notification::make()->title($sent ? 'Unterlagen gesendet' : 'Versand fehlgeschlagen');
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send();
});
}
private function portalPriceAction(): Action
{
return Action::make('portalPrice')
->label('Gesamtpreis laut Portal eintragen')
->icon(Heroicon::OutlinedCurrencyEuro)
->visible(fn (): bool => $this->record->intake === IntakeKind::Booking && ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined], true))
->modalDescription('Der Betrag, den der Gast beim Portal gebucht hat (Gesamtpreis). Er wird so übernommen und nicht in eigene Positionen zerlegt.')
->fillForm(fn (): array => ['portal_total' => $this->record->total, 'guests' => $this->record->guests])
->schema([
EuroInput::make('portal_total')->label('Gesamtpreis laut Portal')->required(),
TextInput::make('guests')->label('Personen (falls bekannt)')->integer()->minValue(1),
])
->action(function (array $data, PortalPrice $price): void {
$guests = filled($data['guests'] ?? null) ? (int) $data['guests'] : $this->record->guests;
$this->record->update(['guests' => $guests, ...$price->columns($this->record->property, $this->record->arrival, $this->record->departure, $guests, (int) $data['portal_total'], $this->record->processChannel()?->name)]);
CaseLog::record($this->record, 'price', 'Gesamtpreis laut Portal eingetragen: '.Money::format((int) $data['portal_total']));
$blockers = app(CaseAutomation::class)->advance($this->record->fresh());
$this->record->refresh();
Notification::make()->title('Preis gespeichert')->body($blockers === [] ? null : implode(' ', $blockers))->success()->send();
});
}
private function extendHoldAction(): Action
{
return Action::make('extendHold')
->label('Reservierung verlängern')
->icon(Heroicon::OutlinedClock)
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
->schema([TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required()])
->action(function (array $data): void {
$from = $this->record->hold_expires_at?->isFuture() ? $this->record->hold_expires_at : now()->toImmutable();
$this->record->update(['hold_expires_at' => $from->addHours((int) $data['hours'])]);
Notification::make()->title('Reserviert bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
});
}
private function servicesAction(): Action
{
return Action::make('services')
->label('Zusatzleistungen erfassen')
->icon(Heroicon::OutlinedPlusCircle)
->visible(fn (): bool => ! in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true))
->modalDescription('Gebuchte Zusatzleistungen (z. B. aus einer Portalbuchung). Sie bestimmen, welche Vertragsanlagen angehängt werden. Der Preis ändert sich dadurch nicht.')
->fillForm(fn (): array => ['items' => collect((array) $this->record->extras)->map(fn ($quantity, $id): array => ['extra_id' => (int) $id, 'quantity' => (int) $quantity])->values()->all()])
->schema([
Repeater::make('items')
->label('Leistungen')
->schema([
Select::make('extra_id')->label('Leistung')->options(fn (): array => Extra::query()->orderBy('name')->get()->mapWithKeys(fn (Extra $extra): array => [$extra->id => $extra->name.($extra->price > 0 ? ' ('.Money::format($extra->price).')' : ' (kostenlos)')])->all())->required(),
TextInput::make('quantity')->label('Menge')->integer()->minValue(1)->default(1)->required(),
])
->columns(2)
->addActionLabel('Leistung hinzufügen'),
])
->action(function (array $data): void {
$extras = [];
foreach ((array) ($data['items'] ?? []) as $item) {
$extras[(int) $item['extra_id']] = ((int) ($extras[(int) $item['extra_id']] ?? 0)) + max(1, (int) $item['quantity']);
}
$this->record->update(['extras' => $extras]);
CaseLog::record($this->record, 'services', 'Zusatzleistungen erfasst');
Notification::make()->title('Zusatzleistungen gespeichert')->success()->send();
});
}
private function offerPdfAction(): Action
{
return Action::make('offerPdf')
->label('Angebot (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf"));
}
private function contractAction(): Action
{
return Action::make('contract')
->label('Mietvertrag (PDF)')
->icon(Heroicon::OutlinedDocumentText)
->visible(fn (): bool => $this->record->contract_path !== null)
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf"));
}
private function offerLinkAction(): Action
{
return Action::make('offerLink')
->label('Angebotslink')
->icon(Heroicon::OutlinedLink)
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
->modalHeading('Link zum Angebot')
->modalDescription('Derselbe Link wie in der Angebots-E-Mail. Gültig bis zum Ende der Angebotsfrist.')
->schema([TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable()])
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen');
}
private function contractTextAction(): Action
{
return Action::make('contractText')
->label('Vertragstext ansehen')
->icon(Heroicon::OutlinedDocumentMagnifyingGlass)
->visible(fn (): bool => $this->record->offer_terms !== null)
->modalHeading(fn (): string => 'Vertrag '.$this->record->reference)
->modalContent(fn () => view('filament.booking-contract', ['booking' => $this->record]))
->modalSubmitAction(false)
->modalCancelActionLabel('Schließen')
->modalWidth('4xl');
}
private function notesAction(): Action
{
return Action::make('notes')
->label('Interne Notiz bearbeiten')
->icon(Heroicon::OutlinedPencilSquare)
->fillForm(fn (): array => ['internal_notes' => $this->record->internal_notes])
->schema([Textarea::make('internal_notes')->label('Interne Notizen')->rows(6)])
->action(fn (array $data) => $this->record->update($data));
}
private function archiveAction(): Action
{
return Action::make('archive')
->label(fn (): string => $this->record->archived_at ? 'Aus dem Archiv holen' : 'Archivieren')
->icon(Heroicon::OutlinedArchiveBox)
->visible(fn (): bool => $this->record->archived_at !== null || $this->record->canBeArchived())
->modalDescription(fn (): string => $this->record->archived_at ? 'Der Vorgang erscheint wieder in der Liste.' : 'Der Vorgang verschwindet aus der Standardliste. Verlauf, E-Mails, Zahlungen und Dokumente bleiben erhalten.')
->requiresConfirmation()
->action(function (): void {
$this->record->update(['archived_at' => $this->record->archived_at ? null : now()]);
Notification::make()->title($this->record->archived_at ? 'Archiviert' : 'Wieder aktiv')->success()->send();
});
}
private function setStatusAction(): Action
{
return Action::make('setStatus')
->label('Status von Hand ändern')
->icon(Heroicon::OutlinedAdjustmentsHorizontal)
->visible(fn (): bool => $this->record->source !== 'website' && $this->record->status !== BookingStatus::Declined)
->modalHeading('Status von Hand ändern (Experte)')
->modalDescription('Nur für Korrekturen. Es werden keine E-Mails versendet; der Grund steht im Verlauf. Eine verbindliche Buchung kann so nicht beendet oder zur Anfrage gemacht werden – dafür gibt es „Beenden“.')
->schema([
Select::make('status')->label('Neuer Status')->options(collect(SetBookingStatus::TARGETS)->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all())->required(),
Textarea::make('reason')->label('Grund')->required()->rows(2),
])
->action(function (array $data, SetBookingStatus $setStatus): void {
try {
$setStatus->handle($this->record, BookingStatus::from($data['status']), $data['reason'], auth()->user()->name);
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
Notification::make()->title('Status geändert')->success()->send();
});
}
/**
* Automatic or manual handling of this case.
*/
private function automationAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null;
}
$automatic = $this->record->processingMode() === ProcessingMode::Automatic;
return Action::make('automation')
->label($automatic ? 'Läuft automatisch' : 'Sie geben frei')
->icon($automatic ? Heroicon::OutlinedBolt : Heroicon::OutlinedHandRaised)
->color('gray')
->tooltip($automatic ? 'Das System macht selbst weiter, sobald alle Angaben da sind.' : 'Das System bereitet alles vor; Sie geben jeden Schritt frei.')
->modalHeading('Wie soll dieser Vorgang weiterlaufen?')
->modalDescription('Gilt nur für diesen Vorgang. Ihre allgemeine Einstellung finden Sie unter „So arbeite ich“.')
->fillForm(fn (): array => ['mode' => $this->record->processingMode()->value])
->schema([Radio::make('mode')->hiddenLabel()->options(ProcessingMode::class)->required()])
->action(function (array $data): void {
$this->record->update(['processing_mode' => $data['mode'] instanceof ProcessingMode ? $data['mode'] : ProcessingMode::from($data['mode'])]);
$blockers = app(CaseAutomation::class)->advance($this->record->fresh());
$this->record->refresh();
Notification::make()->title($this->record->processingMode()->getLabel())->body($blockers === [] ? null : 'Wartet auf: '.implode(' ', $blockers))->success()->send();
});
}
/**
* Ending a case: a request ends without booking; a binding booking is cancelled with its consequences (and on the
* portal as well when the contract was made there). There is no way around it by changing the status.
*/
private function endAction(): ?Action
{
if (in_array($this->record->status, [BookingStatus::Cancelled, BookingStatus::Declined, BookingStatus::Expired, BookingStatus::Completed], true)) {
return null;
}
$binding = $this->record->isBinding();
$hasEmail = filled($this->record->guest?->email);
return Action::make('end')
->label($binding ? 'Stornieren …' : 'Beenden …')
->icon(Heroicon::OutlinedStopCircle)
->color('danger')
->outlined()
->modalHeading($binding ? 'Gebuchten Vorgang stornieren' : 'Vorgang ohne Buchung beenden')
->modalDescription($binding
? 'Die Buchung ist verbindlich. Sie wird storniert, der Zeitraum frei. Stornokosten nach der vereinbarten Regel bleiben als Aufgabe offen.'.($this->record->caseType()->isExternallyBinding() ? ' Gebucht wurde beim Portal – dafür entsteht zusätzlich die Aufgabe, die Stornierung dort zu veranlassen bzw. zu prüfen.' : '')
: 'Es ist noch keine verbindliche Buchung zustande gekommen. Der reservierte Zeitraum wird wieder frei.')
->modalSubmitActionLabel($binding ? 'Stornieren' : 'Beenden')
->schema(array_values(array_filter([
$binding ? Radio::make('initiated_by')->label('Wer storniert?')->options(['guest' => 'Der Gast', 'landlord' => 'Wir (Vermieter)'])->required() : null,
Textarea::make('reason')->label('Grund')->required()->rows(2),
Toggle::make('notify')->label('Den Gast per E-Mail informieren')->default($hasEmail)->disabled(! $hasEmail),
$binding ? Toggle::make('costs_task')->label('Aufgabe „Stornokosten prüfen“ anlegen')->default(true) : null,
])))
->action(function (array $data, CancelBooking $cancel, DeclineBooking $decline) use ($binding, $hasEmail): void {
$notify = $hasEmail && (bool) ($data['notify'] ?? false);
try {
$informed = CaseLog::context(fn () => $binding
? $cancel->handle($this->record, $notify, (bool) ($data['costs_task'] ?? true), auth()->user()->name, $data['initiated_by'])
: $decline->handle($this->record, $notify), reason: trim((string) $data['reason']));
} catch (ReservationException $exception) {
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
return;
}
$this->record->refresh();
$notification = Notification::make()->title($binding ? 'Buchung storniert' : 'Vorgang beendet');
($informed === false ? $notification->warning()->body('Die Mail an den Gast konnte nicht gesendet werden – bitte selbst informieren.') : $notification->success())->send();
});
}
/**
* Suggested message asking a portal guest for the contact data the contract needs.
*/
private function contactRequestText(): string
{
$booking = $this->record;
$landlord = config('fewo.owner.name') ?: config('app.name');
$greeting = $booking->guest ? "Guten Tag {$booking->guest->first_name} {$booking->guest->last_name}," : 'Guten Tag,';
return "{$greeting}\n\n"
."vielen Dank für Ihre Buchung der {$booking->property->name} vom {$booking->arrival->format('d.m.Y')} bis {$booking->departure->format('d.m.Y')}. "
."Für den Mietvertrag benötigen wir noch Ihre Kontaktdaten: vollständige Anschrift (Straße, PLZ, Ort), eine E-Mail-Adresse und eine Telefonnummer.\n\n"
."Sobald wir die Angaben haben, senden wir Ihnen den Vertrag mit allen Informationen zu.\n\n"
."Freundliche Grüße\n{$landlord}";
}
/**
* Form data of the offer modal as SendOffer changes (euro input → cents).
*
@@ -219,28 +621,31 @@ private function offerChanges(array $data): array
{
return [
...$data,
'acknowledged' => (bool) ($data['acknowledged'] ?? false),
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
];
}
/**
* Live price shown in the offer modal, calculated exactly like the offer itself.
* The current values of some fields of a modal form.
*
* @param list<string> $fields
* @return array<string, mixed>
*/
private function offerPricePreview(Get $get): string
private static function formState(Get $get, array $fields): array
{
try {
$stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null);
$quote = app(PriceCalculator::class)->calculate($this->record->property, $stay);
} catch (QuoteException $exception) {
return 'Preis: '.$exception->getMessage();
} catch (Throwable) {
return 'Preis: bitte Termin und Personen angeben.';
}
return collect($fields)->mapWithKeys(fn (string $field): array => [$field => $get($field)])->all();
}
$adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0;
$promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : '';
return 'Gesamtpreis im Angebot: '.Money::format($quote->total() + $adjustment).' (bisher '.Money::format($this->record->total).')'.$promo;
/**
* Form data of the documents modal as composition changes.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function documentChanges(array $data): array
{
return array_filter(Arr::only($data, ['contract_template_id', 'annex_ids']), fn ($value): bool => $value !== null);
}
private function runWorkflow(callable $workflow, string $successTitle): void
@@ -253,6 +658,7 @@ private function runWorkflow(callable $workflow, string $successTitle): void
return;
}
$this->record->refresh();
Notification::make()->title($successTitle)->success()->send();
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Filament\Resources\Bookings\RelationManagers;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Communication log: every e-mail that went out for this booking.
*/
class MessagesRelationManager extends RelationManager
{
protected static string $relationship = 'messages';
protected static ?string $title = 'Mailverlauf';
public function isReadOnly(): bool
{
return true;
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('subject')
->defaultSort('sent_at', 'desc')
->emptyStateHeading('Noch keine E-Mails zu dieser Buchung')
->description('Betreff und Empfängerart jeder E-Mail zu dieser Buchung. Im Testbetrieb gehen alle Mails an die Testadresse.')
->columns([
TextColumn::make('sent_at')->label('Gesendet')->dateTime('d.m.Y, H:i'),
TextColumn::make('audience')->label('An')->badge()->formatStateUsing(fn (string $state): string => match ($state) {
'guest' => 'Gast',
'landlord' => 'Vermieter',
default => 'Testadresse',
}),
TextColumn::make('subject')->label('Betreff')->wrap(),
]);
}
}
@@ -0,0 +1,48 @@
<?php
namespace App\Filament\Resources\Bookings\RelationManagers;
use App\Enums\BookingTaskStatus;
use App\Models\BookingTask;
use Filament\Actions\Action;
use Filament\Resources\RelationManagers\RelationManager;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
/**
* Tasks of this booking (payment reminders, cancellation requests and costs).
*/
class TasksRelationManager extends RelationManager
{
protected static string $relationship = 'tasks';
protected static ?string $title = 'Aufgaben';
public function isReadOnly(): bool
{
return false;
}
public function table(Table $table): Table
{
return $table
->recordTitleAttribute('kind')
->defaultSort('created_at', 'desc')
->emptyStateHeading('Keine Aufgaben zu dieser Buchung')
->columns([
TextColumn::make('kind')->label('Aufgabe')->badge(),
TextColumn::make('status')->label('Status')->badge(),
TextColumn::make('due_on')->label('Seit / fällig')->date('d.m.Y')->placeholder('–'),
TextColumn::make('note')->label('Hinweis')->wrap()->placeholder('–'),
])
->recordActions([
Action::make('done')
->label('Erledigt')
->icon(Heroicon::OutlinedCheck)
->color('success')
->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open)
->action(fn (BookingTask $record) => $record->complete(auth()->user()->name)),
]);
}
}
@@ -2,65 +2,121 @@
namespace App\Filament\Resources\Bookings\Schemas;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Models\Channel;
use App\Models\Property;
use App\Support\CurrentProperty;
use Filament\Forms\Components\DatePicker;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/**
* Manual entry of a booking received by phone or e-mail. The price is calculated automatically.
* "Neu": one entry for everything that arrives outside the website. The first question is what it is – a request,
* a booking already binding on a portal, or own use / a block – and only the fields that matter for that answer follow.
* Nothing has to be invented: unknown guest data, number of guests or portal price stay empty.
*/
class BookingForm
{
public const INQUIRY = 'inquiry';
public const EXTERNAL = 'external';
public const OWN_USE = 'own_use';
public static function configure(Schema $schema): Schema
{
$is = fn (string $kind): \Closure => fn (Get $get): bool => $get('kind') === $kind;
$isCase = fn (Get $get): bool => in_array($get('kind'), [self::INQUIRY, self::EXTERNAL], true);
return $schema
->components([
Section::make('Aufenthalt')
Section::make('Was möchten Sie eintragen?')
->schema([
Radio::make('kind')
->hiddenLabel()
->options([
self::INQUIRY => 'Eine Anfrage – per Telefon, E-Mail oder Nachricht über ein Portal',
self::EXTERNAL => 'Eine Buchung, die bei einem Portal schon fest gebucht ist',
self::OWN_USE => 'Eigene Nutzung oder eine Sperre (z. B. Wartung)',
])
->default(self::INQUIRY)
->required()
->live(),
Text::make(new HtmlString('Eigene Nutzung und Sperren tragen Sie bis auf Weiteres unter <a class="underline" href="'.e(BlockedPeriodResource::getUrl()).'">Sperrzeiten</a> ein.'))
->visible($is(self::OWN_USE)),
]),
Section::make('Zeitraum')
->columns(2)
->visible($isCase)
->schema([
Select::make('property_id')
->label('Wohnung')
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
->default(fn (): ?int => app(CurrentProperty::class)->id())
->required(),
->required()
->live(),
TextInput::make('guests')
->label('Personen')
->integer()
->minValue(1)
->default(2)
->required(),
DatePicker::make('arrival')
->label('Anreise')
->required(),
DatePicker::make('departure')
->label('Abreise')
->after('arrival')
->required(),
TextInput::make('promo_code')
->label('Aktionscode'),
->helperText(fn (Get $get): ?string => $get('kind') === self::EXTERNAL ? 'Leer lassen, wenn nicht bekannt.' : null)
->required($is(self::INQUIRY)),
DatePicker::make('arrival')->label('Anreise')->required(),
DatePicker::make('departure')->label('Abreise')->after('arrival')->required(),
]),
Section::make('Portal')
->columns(2)
->visible($isCase)
->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())
->required($is(self::EXTERNAL)),
TextInput::make('portal_reference')->label('Buchungsnummer im Portal')->maxLength(100)->visible($is(self::EXTERNAL)),
EuroInput::make('portal_total')
->label('Gesamtpreis laut Portal')
->helperText('Der Betrag, den der Gast beim Portal gebucht hat. Leer lassen, wenn noch nicht bekannt – er wird nicht geschätzt.')
->visible($is(self::EXTERNAL)),
]),
Section::make('Gast')
->description('Nur eintragen, was bekannt ist. Fehlendes wird später ergänzt; das System erinnert daran.')
->columns(2)
->visible($isCase)
->schema([
TextInput::make('first_name')->label('Vorname')->required()->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required()->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->required()->maxLength(255),
TextInput::make('first_name')->label('Vorname')->required($is(self::INQUIRY))->maxLength(255),
TextInput::make('last_name')->label('Nachname')->required($is(self::INQUIRY))->maxLength(255),
TextInput::make('email')->label('E-Mail')->email()->maxLength(255),
TextInput::make('phone')->label('Telefon')->tel()->maxLength(50),
TextInput::make('street')->label('Straße')->maxLength(255),
TextInput::make('postal_code')->label('PLZ')->maxLength(20),
TextInput::make('city')->label('Ort')->maxLength(255),
Toggle::make('guest_confirmed')->label('Der Gast hat die Buchung bereits per E-Mail bestätigt')->visible($is(self::EXTERNAL)),
]),
Section::make('Abschluss')
Section::make('Wie geht es weiter?')
->visible($is(self::INQUIRY))
->schema([
Textarea::make('internal_notes')->label('Interne Notiz'),
Toggle::make('confirm_immediately')->label('Sofort verbindlich bestätigen')->default(true),
Toggle::make('send_mails')->label('E-Mails an den Gast senden')->default(false),
Toggle::make('confirm_immediately')
->label('Die Buchung ist mit dem Gast schon fest vereinbart – gleich verbindlich eintragen')
->helperText('Aus: Das System bereitet das Angebot vor; je nach Einstellung geht es automatisch hinaus oder wartet auf Ihre Freigabe.')
->default(false),
Toggle::make('send_mails')->label('Dem Gast E-Mails senden (Eingangsbestätigung bzw. Buchungsbestätigung)')->default(true),
TextInput::make('promo_code')->label('Aktionscode')->maxLength(50),
]),
Section::make('Notiz')
->visible($isCase)
->collapsed()
->schema([
Textarea::make('internal_notes')->hiddenLabel()->placeholder('Interne Notiz (nur für Sie sichtbar)'),
]),
]);
}
@@ -2,15 +2,34 @@
namespace App\Filament\Resources\Bookings\Schemas;
use App\Documents\OfferTerms;
use App\Enums\ActivityState;
use App\Enums\AdminMode;
use App\Enums\DocumentKind;
use App\Enums\ProcessingMode;
use App\Enums\ProcessSetting;
use App\Enums\Responsibility;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\IntakeObservation;
use App\Models\User;
use App\Process\CaseActivities;
use App\Process\CaseAutomation;
use App\Process\ProcessProfile;
use App\Support\Money;
use Carbon\CarbonImmutable;
use Filament\Infolists\Components\RepeatableEntry;
use Filament\Infolists\Components\RepeatableEntry\TableColumn;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Grid;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Illuminate\Support\HtmlString;
/**
* The case page: first where it stands and what is next, then the activities and the history, then the facts (guest,
* stay, price and payments, documents). Technical details are shown in the expert view only.
*/
class BookingInfolist
{
public static function configure(Schema $schema): Schema
@@ -18,78 +37,217 @@ public static function configure(Schema $schema): Schema
return $schema
->columns(3)
->components([
Section::make('Als Nächstes')
->columnSpanFull()
->schema([
TextEntry::make('next')
->hiddenLabel()
->state(fn (Booking $record): HtmlString => self::nextStep($record))
->html(),
]),
Grid::make(1)
->columnSpan(2)
->schema([
Section::make('Aufenthalt')
->columns(3)
->schema([
TextEntry::make('property.name')->label('Wohnung'),
TextEntry::make('arrival')->label('Anreise')->date('l, d.m.Y'),
TextEntry::make('departure')->label('Abreise')->date('l, d.m.Y'),
TextEntry::make('nights')->label('Nächte')->state(fn (Booking $record): int => $record->nights()),
TextEntry::make('guests')->label('Personen'),
TextEntry::make('promo_code')->label('Aktionscode')->placeholder('–'),
]),
Section::make('Preis')
Section::make('Ablauf')
->description('Was erledigt ist, was wartet und was noch kommt.')
->schema([TextEntry::make('activities')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::activities($record))->html()]),
Section::make('Preis und Zahlungen')
->schema([
TextEntry::make('price_unknown')
->hiddenLabel()
->state('Der Gesamtpreis ist noch nicht bekannt.')
->color('warning')
->visible(fn (Booking $record): bool => $record->total === null),
RepeatableEntry::make('quote.lines')
->hiddenLabel()
->table([
TableColumn::make('Leistung'),
TableColumn::make('Betrag')->alignEnd(),
])
->visible(fn (Booking $record): bool => filled($record->quote['lines'] ?? null))
->table([TableColumn::make('Leistung'), TableColumn::make('Betrag')->alignEnd()])
->schema([
TextEntry::make('label'),
TextEntry::make('amount')->formatStateUsing(fn (int $state): string => Money::format($state))->alignEnd(),
]),
Grid::make(4)->schema([
Grid::make(4)->visible(fn (Booking $record): bool => $record->total !== null)->schema([
TextEntry::make('total')->label('Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->weight('bold'),
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'),
TextEntry::make('open')->label('Offen')
->state(fn (Booking $record): string => $record->process()->payments() === Responsibility::Portal ? 'über das Portal' : Money::format($record->openAmount()))
->color(fn (Booking $record): string => $record->process()->payments() === Responsibility::Landlord && $record->openAmount() > 0 ? 'danger' : 'success'),
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y')->placeholder('–'),
]),
]),
Section::make('Verlauf')
->collapsible()
->schema([TextEntry::make('history')->hiddenLabel()->state(fn (Booking $record): HtmlString => self::history($record))->html()]),
Section::make('Nachricht des Gastes')
->visible(fn (Booking $record): bool => filled($record->message))
->schema([
TextEntry::make('message')->hiddenLabel(),
]),
->schema([TextEntry::make('message')->hiddenLabel()]),
]),
Grid::make(1)
->columnSpan(1)
->schema([
Section::make('Status')
->schema([
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('hold_expires_at')->label('Vorgemerkt bis')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->hold_expires_at !== null),
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
TextEntry::make('source')->label('Buchungskanal / Quelle')->state(fn (Booking $record): string => $record->bookingChannelLabel()),
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
TextEntry::make('utm')
->label('Kampagne (UTM)')
->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)
->visible(fn (Booking $record): bool => filled($record->utm_source)),
]),
Section::make('Gast')
->schema([
TextEntry::make('guest.full_name')->label('Name'),
TextEntry::make('guest.email')->label('E-Mail')->placeholder('Unbekannt')->copyable(),
TextEntry::make('guest_name')->label('Name')->state(fn (Booking $record): string => $record->guestName())
->color(fn (Booking $record): ?string => $record->guest === null ? 'warning' : null),
TextEntry::make('guest.email')->label('E-Mail')->placeholder('noch nicht bekannt')->copyable(),
TextEntry::make('guest.phone')->label('Telefon')->placeholder('–'),
TextEntry::make('guest_address')
->label('Adresse')
->state(fn (Booking $record): ?string => collect([$record->guest->street, trim("{$record->guest->postal_code} {$record->guest->city}")])->filter()->implode(', ') ?: null)
->state(fn (Booking $record): ?string => $record->guest === null ? null : (collect([$record->guest->street, trim("{$record->guest->postal_code} {$record->guest->city}")])->filter()->implode(', ') ?: null))
->placeholder('–'),
]),
Section::make('Interne Notizen')
Section::make('Aufenthalt')
->schema([
TextEntry::make('internal_notes')->hiddenLabel()->placeholder('Keine Notizen'),
TextEntry::make('property.name')->label('Wohnung'),
TextEntry::make('period')->label('Zeitraum')->state(fn (Booking $record): string => $record->arrival->translatedFormat('D, d.m.Y').' – '.$record->departure->translatedFormat('D, d.m.Y').' ('.$record->nights().' Nächte)'),
TextEntry::make('guests')->label('Personen')->placeholder('noch nicht bekannt'),
TextEntry::make('channel')->label('Über')->state(fn (Booking $record): string => $record->bookingChannelLabel().($record->portal_reference ? ' · Nr. '.$record->portal_reference : '')),
]),
Section::make('Dokumente')
->schema([
TextEntry::make('documents')->hiddenLabel()->html()->state(fn (Booking $record): HtmlString => self::documents($record)),
TextEntry::make('document_kind')->label('Vorgesehen')->state(fn (Booking $record): string => DocumentKind::forCase($record)?->getLabel() ?? 'Unterlagen schickt das Portal'),
TextEntry::make('template')->label('Vorlage')->state(fn (Booking $record): string => isset($record->offer_terms['template']) && ($record->contract_path !== null || $record->offer_path !== null)
? $record->offer_terms['template']['name'].' (Version '.$record->offer_terms['template']['version'].', festgeschrieben)'
: (OfferTerms::templateFor($record)?->label() ?? 'Texte der Webseite').' (vorgesehen)'),
]),
Section::make('Interne Notizen')
->collapsible()
->schema([TextEntry::make('internal_notes')->hiddenLabel()->placeholder('Keine Notizen')]),
]),
Section::make('Technische Angaben')
->description('Expertenansicht')
->columnSpanFull()
->collapsed()
->visible(fn (): bool => auth()->user() instanceof User && auth()->user()->adminMode() === AdminMode::Expert)
->columns(3)
->schema([
TextEntry::make('status')->label('Status')->badge(),
TextEntry::make('case_type')->label('Vorgangsart')->state(fn (Booking $record): string => strtoupper($record->caseType()->value).' – '.$record->caseType()->getLabel()),
TextEntry::make('intake')->label('Eingangsart')->state(fn (Booking $record): string => $record->intake?->getLabel() ?? '–'),
TextEntry::make('sources')->label('Quellen und Kalenderdarstellungen')->state(fn (Booking $record): HtmlString => self::sources($record))->html()->columnSpanFull(),
TextEntry::make('profile')->label('Abwicklungsprofil (eingefroren)')->state(fn (Booking $record): HtmlString => self::profile($record))->html()->columnSpanFull(),
TextEntry::make('hold_expires_at')->label('Reserviert bis')->dateTime('d.m.Y, H:i')->placeholder('–'),
TextEntry::make('offer_hash')->label('Angebot (Prüfsumme)')->state(fn (Booking $record): ?string => $record->offer_version > 0 ? 'Version '.$record->offer_version.' · '.substr((string) $record->offer_hash, 0, 16) : null)->placeholder('–'),
TextEntry::make('contract_pdf_sha256')->label('Vertrag (Prüfsumme)')->formatStateUsing(fn (?string $state): string => substr((string) $state, 0, 16))->placeholder('–'),
TextEntry::make('accepted_at')->label('Angenommen am')->dateTime('d.m.Y, H:i:s')->placeholder('–'),
TextEntry::make('source')->label('Quelle'),
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
TextEntry::make('utm')->label('Kampagne (UTM)')->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)->placeholder('–'),
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
]),
]);
}
/**
* The next step in large type, with what keeps an automatic case waiting.
*/
private static function nextStep(Booking $booking): HtmlString
{
$next = CaseActivities::next($booking);
$automatic = $booking->processingMode() === ProcessingMode::Automatic;
$waiting = collect(CaseActivities::for($booking))->first(fn ($activity): bool => $activity->state === ActivityState::Waiting);
$title = match (true) {
$next !== null => e($next->label),
$waiting !== null => 'Nichts zu tun – es wartet: '.e($waiting->label),
default => 'Nichts zu tun.',
};
$color = $next?->state === ActivityState::Problem ? '#dc2626' : ($next !== null ? '#b45309' : '#15803d');
$detail = $next?->detail ?? $waiting?->detail;
$mode = $automatic
? 'Dieser Vorgang läuft automatisch weiter, sobald alle Angaben da sind.'.(($blockers = self::blockers($booking)) !== [] ? ' Es fehlt: '.e(implode(' ', $blockers)) : '')
: 'Sie geben jeden Schritt selbst frei. Der Knopf oben rechts führt zum nächsten Schritt.';
return new HtmlString('<div style="font-size:1.35rem;font-weight:700;color:'.$color.'">'.$title.'</div>'
.($detail ? '<div style="margin-top:.2rem">'.e($detail).'</div>' : '')
.'<div style="margin-top:.5rem;color:#6b7280;font-size:.9rem">'.$mode.'</div>');
}
/**
* Every portal entry (calendar or e-mail) that belongs to the case, and what the intake recorded about it.
*/
private static function sources(Booking $booking): HtmlString
{
$lines = BlockedPeriod::query()->withTrashed()->with('channel')->where('linked_booking_id', $booking->id)->orderBy('id')->get()
->map(fn (BlockedPeriod $entry): string => e(($entry->source === 'email' ? 'E-Mail' : 'Kalender').' von '.($entry->channel?->name ?? '–').': '.$entry->starts_on->format('d.m.').'–'.$entry->ends_on->format('d.m.Y')
.($entry->trashed() ? ' · nicht mehr im Kalender' : '').($entry->starts_on->equalTo($booking->arrival) && $entry->ends_on->equalTo($booking->departure) ? '' : ' · abweichende Termine').' · Kennung '.$entry->external_uid));
$observations = IntakeObservation::query()->with('channel')->where('booking_id', $booking->id)->orderBy('occurred_at')->get()
->map(fn (IntakeObservation $observation): string => e($observation->occurred_at->format('d.m.Y H:i').' · '.$observation->sourceLabel().' '.$observation->channel?->name.' · '.$observation->outcome->getLabel().($observation->applied ? '' : ' (nur protokolliert)')));
$html = $lines->isEmpty() ? 'Keine Portaleinträge zugeordnet.' : $lines->implode('<br>');
return new HtmlString($observations->isEmpty() ? $html : $html.'<br><span style="color:#6b7280">Eingang: '.$observations->implode('<br>').'</span>');
}
/**
* The documents made for the case, as recorded when they were created (kind, template, date).
*/
private static function documents(Booking $booking): HtmlString
{
$lines = $booking->events()->where('type', 'document')->whereNotNull('data')->reorder()->orderBy('occurred_at')->orderBy('id')->get()
->filter(fn ($event): bool => isset($event->data['kind']))
->map(fn ($event): string => e($event->occurred_at->format('d.m.Y').' · '.$event->summary));
if ($lines->isEmpty()) {
$lines = collect([
$booking->offer_path ? 'Angebot Version '.$booking->offer_version : null,
$booking->contract_path ? 'Mietvertrag' : null,
$booking->confirmation_sent_at ? 'Bestätigung gesendet am '.$booking->confirmation_sent_at->format('d.m.Y') : null,
])->filter()->map(fn (string $line): string => e($line));
}
return new HtmlString($lines->isEmpty() ? 'Noch keine' : $lines->implode('<br>'));
}
/**
* @return list<string>
*/
private static function blockers(Booking $booking): array
{
return $booking->isBinding() && $booking->confirmation_sent_at === null && $booking->process()->documents() === Responsibility::Landlord
? app(CaseAutomation::class)->documentBlockers($booking)
: [];
}
private static function activities(Booking $booking): HtmlString
{
$colors = ['success' => '#15803d', 'warning' => '#b45309', 'danger' => '#dc2626', 'info' => '#2563eb', 'gray' => '#9ca3af'];
$rows = collect(CaseActivities::for($booking))
->reject(fn ($activity): bool => $activity->state === ActivityState::NotApplicable)
->map(function ($activity) use ($colors): string {
$color = $colors[$activity->state->getColor()];
$strong = $activity->state->needsAction() ? 'font-weight:700' : '';
return '<li style="display:flex;gap:.75rem;padding:.45rem 0;border-bottom:1px solid rgba(128,128,128,.2)">'
.'<span style="width:1.4rem;text-align:center;font-weight:700;color:'.$color.'">'.$activity->state->icon().'</span>'
.'<span style="flex:1;'.$strong.'">'.e($activity->label)
.($activity->detail ? ' <span style="font-weight:400;color:#6b7280">· '.e($activity->detail).'</span>' : '')
.($activity->url && $activity->state->needsAction() ? ' <a href="'.e($activity->url).'" style="color:#2563eb;text-decoration:underline">erledigen</a>' : '')
.'</span><span style="color:'.$color.';font-size:.85rem">'.e($activity->state->getLabel()).'</span></li>';
})->implode('');
return new HtmlString('<ul style="list-style:none;margin:0;padding:0">'.$rows.'</ul>');
}
private static function history(Booking $booking): HtmlString
{
$rows = $booking->events()->get()->map(fn ($event): string => '<li style="margin:.25rem 0"><span style="color:#6b7280">'.$event->occurred_at->format('d.m.Y H:i').'</span> · '.e($event->summary)
.($event->actor ? ' <span style="color:#6b7280">('.e($event->actor).')</span>' : '')
.($event->reason ? '<div style="color:#6b7280;margin-left:1rem">Grund: '.e($event->reason).'</div>' : '').'</li>')->implode('');
return new HtmlString($rows === '' ? 'Noch keine Einträge.' : '<ul style="list-style:none;padding:0;margin:0;font-size:.9rem">'.$rows.'</ul>');
}
private static function profile(Booking $booking): HtmlString
{
$profile = $booking->process();
$rows = collect(ProcessSetting::cases())
->reject(fn (ProcessSetting $setting): bool => in_array($setting, ProcessProfile::LIVE, true))
->map(fn (ProcessSetting $setting): string => '<li>'.e($setting->question()).' <strong>'.e($setting->describe($profile->value($setting))).'</strong> <span style="color:#6b7280">('.e(ProcessProfile::sourceLabel($profile->source($setting))).')</span></li>')
->implode('');
return new HtmlString('<ul style="list-style:disc;padding-left:1.2rem">'.$rows.'</ul><div style="color:#6b7280;font-size:.85rem">Festgelegt '.e(($profile->origin === 'migration' ? 'bei der Übernahme der bisherigen Daten' : 'beim Eingang').($profile->frozenAt ? ' am '.CarbonImmutable::parse($profile->frozenAt)->format('d.m.Y H:i') : '')).($booking->processing_mode ? ' · Bearbeitung für diesen Vorgang: '.e($booking->processing_mode->getLabel()) : '').'</div>');
}
}
@@ -4,9 +4,12 @@
use App\Availability\OccupancyOverview;
use App\Enums\BookingStatus;
use App\Models\Channel;
use App\Models\Property;
use App\Support\CurrentProperty;
use Filament\Actions\Action;
use Filament\Forms\Components\DatePicker;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\Filter;
use Filament\Tables\Filters\SelectFilter;
@@ -18,7 +21,7 @@ class BookingsTable
public static function configure(Table $table, ?int $guestId = null): Table
{
return $table
->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.')
->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. „Öffnen“ zeigt alles zu einem Vorgang: nächster Schritt, Vertrag, Zahlungen, Aufgaben und E-Mails. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.')
->records(function (?string $search, ?string $sortColumn, ?string $sortDirection, array $filters, int $page, int|string $recordsPerPage) use ($guestId, $table): LengthAwarePaginator {
$propertyId = filled($filters['property']['value'] ?? null) ? (int) $filters['property']['value'] : null;
$records = app(OccupancyOverview::class)->records($propertyId, $guestId);
@@ -32,11 +35,30 @@ public static function configure(Table $table, ?int $guestId = null): Table
if ($filters['without_guest']['isActive'] ?? false) {
$records = $records->where('guest_assigned', false);
}
if (filled($filters['channel']['value'] ?? null)) {
$records = $records->where('channel_id', (int) $filters['channel']['value']);
}
if ($filters['contact_missing']['isActive'] ?? false) {
$records = $records->filter(fn (array $record): bool => $record['record_type'] === 'booking' && blank($record['guest_email']));
}
if (filled($filters['period']['arrival_from'] ?? null)) {
$records = $records->filter(fn (array $record): bool => $record['arrival'] >= $filters['period']['arrival_from']);
}
if (filled($filters['period']['arrival_until'] ?? null)) {
$records = $records->filter(fn (array $record): bool => $record['arrival'] <= $filters['period']['arrival_until']);
}
if (filled($filters['kind']['value'] ?? null)) {
$records = $records->where('record_type', $filters['kind']['value']);
}
if (filled($filters['status']['values'] ?? [])) {
$records = $records->whereIn('status_key', $filters['status']['values']);
} elseif (! ($filters['show_closed']['isActive'] ?? false)) {
// Cancelled, declined and expired requests leave the main list (they stay available as archive).
$records = $records->reject(fn (array $record): bool => in_array($record['status_key'], ['cancelled', 'declined', 'expired'], true));
}
if (! ($filters['show_closed']['isActive'] ?? false)) {
// Bookings the landlord moved to the archive; they keep their whole history and show again with the archive filter.
$records = $records->reject(fn (array $record): bool => $record['archived_booking']);
}
$column = in_array($sortColumn, ['arrival', 'departure', 'reference', 'guest', 'source', 'total'], true) ? $sortColumn : 'arrival';
$records = $records->sortBy($column, SORT_REGULAR, $sortDirection === 'desc');
@@ -47,15 +69,16 @@ public static function configure(Table $table, ?int $guestId = null): Table
->defaultSort('arrival')->searchable()->recordAction(null)
->columns([
TextColumn::make('reference')->label('Nr. / Referenz')->sortable(),
TextColumn::make('kind_label')->label('Art')->badge(),
TextColumn::make('kind_label')->label('Art')->badge()->toggleable(),
TextColumn::make('status')->label('Status')->badge()->color(fn (array $record): string => $record['color']),
TextColumn::make('guest')->label('Gast / Namensinformation')->sortable()
->description(fn (array $record): string => $record['guest_assigned'] ? ($record['guest_email'] ?? 'E-Mail unbekannt') : 'Gastzuordnung offen'),
TextColumn::make('source')->label('Buchungskanal / Quelle')->sortable(),
TextColumn::make('source')->label('Buchungskanal / Quelle')->sortable()->toggleable(),
TextColumn::make('arrival')->label('Anreise')->date('d.m.Y')->sortable(),
TextColumn::make('departure')->label('Abreise')->date('d.m.Y')->sortable()
->description(fn (array $record): string => $record['nights'].' Nächte'),
TextColumn::make('persons')->label('Personen')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true),
IconColumn::make('archived_booking')->label('Archiviert')->boolean()->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('total')->label('Bekannter Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true),
TextColumn::make('property')->label('Wohnung')->toggleable(isToggledHiddenByDefault: true),
])
@@ -68,10 +91,17 @@ 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()),
Filter::make('period')->label('Anreise im Zeitraum')->schema([
DatePicker::make('arrival_from')->label('Anreise ab'),
DatePicker::make('arrival_until')->label('Anreise bis'),
])->columns(2),
Filter::make('upcoming')->label('Nur kommende Aufenthalte'),
Filter::make('contact_missing')->label('Kontaktdaten des Gastes fehlen'),
Filter::make('show_closed')->label('Archiv anzeigen (archiviert, storniert, abgelehnt, abgelaufen)'),
Filter::make('without_guest')->label('Gastzuordnung offen'),
])
->recordUrl(fn (array $record): string => $record['url'])
->recordActions([Action::make('view')->label('Details')->url(fn (array $record): string => $record['url'])]);
->recordActions([Action::make('view')->label(fn (array $record): string => $record['record_type'] === 'booking' ? 'Öffnen' : ($record['kind'] === 'block' ? 'Details' : 'Als Buchung übernehmen'))->icon('heroicon-o-folder-open')->button()->color('primary')->url(fn (array $record): string => $record['url'])]);
}
}
@@ -0,0 +1,93 @@
<?php
namespace App\Filament\Resources\CancellationPolicies;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\CancellationPolicies\Pages\CreateCancellationPolicy;
use App\Filament\Resources\CancellationPolicies\Pages\EditCancellationPolicy;
use App\Filament\Resources\CancellationPolicies\Pages\ListCancellationPolicies;
use App\Models\CancellationPolicy;
use BackedEnum;
use Filament\Actions\DeleteAction;
use Filament\Actions\EditAction;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Text;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Support\HtmlString;
use UnitEnum;
/**
* Cancellation rules: stepped percentages by days before arrival. Assigned to contract templates.
*/
class CancellationPolicyResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = CancellationPolicy::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedReceiptPercent;
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
protected static ?string $modelLabel = 'Stornoregel';
protected static ?string $pluralModelLabel = 'Stornoregeln';
protected static ?int $navigationSort = 3;
public static function form(Schema $schema): Schema
{
return $schema->components([
TextInput::make('name')->label('Name')->required()->maxLength(120)->helperText('z. B. „Direktbuchung“ oder „FeWo-direkt“.'),
Select::make('base')
->label('Berechnungsgrundlage')
->options([CancellationPolicy::BASE_RENT => 'Mietpreis (ohne Endreinigung, Service und Kurtaxe)', CancellationPolicy::BASE_TOTAL => 'Gesamtpreis'])
->default(CancellationPolicy::BASE_RENT)
->required(),
Repeater::make('tiers')
->label('Stufen')
->helperText('Jede Stufe gilt, wenn bis zur Anreise mindestens so viele Tage bleiben. Beispiel: ab 60 Tagen 0 %, ab 30 Tagen 50 %, ab 0 Tagen 100 %. Die letzte Stufe (0 Tage) gilt für alles danach.')
->schema([
TextInput::make('min_days')->label('Ab Tagen vor Anreise')->integer()->minValue(0)->required(),
TextInput::make('percent')->label('Entschädigung')->integer()->minValue(0)->maxValue(100)->suffix('%')->required(),
])
->columns(2)
->default([['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]])
->minItems(1)
->required()
->columnSpanFull(),
EuroInput::make('replacement_fee')->label('Gebühr bei Ersatzmieter (optional)'),
Text::make(fn (?CancellationPolicy $record): HtmlString => new HtmlString($record ? '<strong>So steht es im Vertrag ({{ storno_regel }}):</strong><ul style="margin-top:.4rem">'.collect(CancellationPolicy::describe($record->snapshot()))->map(fn (string $line): string => '<li>'.e($line).'</li>')->implode('').'</ul>' : ''))->columnSpanFull(),
Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(),
]);
}
public static function table(Table $table): Table
{
return $table
->defaultSort('name')
->columns([
TextColumn::make('name')->label('Regel')->weight('medium')->searchable(),
TextColumn::make('base')->label('Grundlage')->formatStateUsing(fn (string $state): string => $state === CancellationPolicy::BASE_TOTAL ? 'Gesamtpreis' : 'Mietpreis'),
TextColumn::make('steps')->label('Stufen')->state(fn (CancellationPolicy $record): string => collect(CancellationPolicy::normalise((array) $record->tiers))->map(fn (array $tier): string => 'ab '.$tier['min_days'].' T: '.$tier['percent'].' %')->implode(' · ')),
])
->recordActions([EditAction::make(), DeleteAction::make()]);
}
public static function getPages(): array
{
return [
'index' => ListCancellationPolicies::route('/'),
'create' => CreateCancellationPolicy::route('/create'),
'edit' => EditCancellationPolicy::route('/{record}/edit'),
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use App\Models\CancellationPolicy;
use Filament\Resources\Pages\CreateRecord;
class CreateCancellationPolicy extends CreateRecord
{
protected static string $resource = CancellationPolicyResource::class;
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeCreate(array $data): array
{
$data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? []));
return $data;
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use App\Models\CancellationPolicy;
use Filament\Actions\DeleteAction;
use Filament\Resources\Pages\EditRecord;
class EditCancellationPolicy extends EditRecord
{
protected static string $resource = CancellationPolicyResource::class;
protected function getHeaderActions(): array
{
return [DeleteAction::make()];
}
/**
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
protected function mutateFormDataBeforeSave(array $data): array
{
$data['tiers'] = CancellationPolicy::normalise((array) ($data['tiers'] ?? []));
return $data;
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Filament\Resources\CancellationPolicies\Pages;
use App\Filament\Resources\CancellationPolicies\CancellationPolicyResource;
use Filament\Actions\CreateAction;
use Filament\Resources\Pages\ListRecords;
class ListCancellationPolicies extends ListRecords
{
protected static string $resource = CancellationPolicyResource::class;
protected function getHeaderActions(): array
{
return [CreateAction::make()];
}
}
@@ -0,0 +1,119 @@
<?php
namespace App\Filament\Resources\Cancellations;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Forms\Components\EuroInput;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Cancellations\Pages\ListCancellations;
use App\Models\Cancellation;
use App\Support\Money;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Forms\Components\Textarea;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use UnitEnum;
/**
* Cancellation management: every cancelled booking with the days before arrival, the cost proposed by its
* cancellation rule, the amount finally charged, what was paid and what is still to collect or refund.
*/
class CancellationResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = Cancellation::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArchiveBoxXMark;
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Stornierung';
protected static ?string $pluralModelLabel = 'Stornierungen';
protected static ?int $navigationSort = 6;
public static function table(Table $table): Table
{
return $table
->defaultSort('cancelled_on', 'desc')
->description('Storno-Verwaltung: Kosten werden nach der Stornoregel der Vertragsvorlage vorgeschlagen. Sie legen den Betrag endgültig fest, rechnen ab oder erlassen ihn. Gäste erhalten hierzu keine automatische Mail.')
->columns([
TextColumn::make('booking.reference')->label('Buchung')->weight('medium')->description(fn (Cancellation $record): string => $record->booking->guest?->full_name ?? ''),
TextColumn::make('cancelled_on')->label('Storniert am')->date('d.m.Y')->description(fn (Cancellation $record): string => $record->initiated_by === 'guest' ? 'durch den Gast' : 'durch die Verwaltung'),
TextColumn::make('days_before')->label('Tage vor Anreise')->placeholder('–'),
TextColumn::make('policy_name')->label('Stornoregel')->placeholder('Keine Regel')->description(fn (Cancellation $record): ?string => $record->percent !== null ? $record->percent.' % von '.Money::format((int) $record->base_amount) : null),
TextColumn::make('calculated_fee')->label('Vorschlag')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)),
TextColumn::make('final_fee')->label('Festgelegt')->formatStateUsing(fn (?int $state): string => $state === null ? '–' : Money::format($state)),
TextColumn::make('paid_amount')->label('Bezahlt')->formatStateUsing(fn (int $state): string => Money::format($state)),
TextColumn::make('balance')->label('Saldo')->state(fn (Cancellation $record): string => $record->balance() > 0 ? Money::format($record->balance()).' einzufordern' : ($record->balance() < 0 ? Money::format(-$record->balance()).' zu erstatten' : 'ausgeglichen')),
TextColumn::make('status')->label('Status')->badge()->formatStateUsing(fn (string $state): string => match ($state) {
Cancellation::SETTLED => 'Abgerechnet',
Cancellation::WAIVED => 'Erlassen',
default => 'Offen',
})->color(fn (string $state): string => $state === Cancellation::OPEN ? 'warning' : 'success'),
])
->filters([
SelectFilter::make('status')->label('Status')->options([Cancellation::OPEN => 'Offen', Cancellation::SETTLED => 'Abgerechnet', Cancellation::WAIVED => 'Erlassen'])->default(Cancellation::OPEN),
])
->recordActions([
Action::make('booking')->label('Buchung')->icon(Heroicon::OutlinedArrowTopRightOnSquare)->color('gray')
->url(fn (Cancellation $record): string => BookingResource::getUrl('view', ['record' => $record->booking])),
Action::make('decide')
->label('Kosten festlegen')
->icon(Heroicon::OutlinedPencilSquare)
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->fillForm(fn (Cancellation $record): array => ['final_fee' => $record->final_fee ?? $record->calculated_fee, 'note' => $record->note])
->schema([
EuroInput::make('final_fee')->label('Endgültige Stornokosten')->required(),
Textarea::make('note')->label('Begründung / Notiz')->rows(2),
])
->action(fn (array $data, Cancellation $record) => $record->update(['final_fee' => $data['final_fee'], 'note' => $data['note']])),
Action::make('settle')
->label('Abgerechnet')
->icon(Heroicon::OutlinedCheck)
->color('success')
->requiresConfirmation()
->modalDescription('Die Stornokosten sind beglichen bzw. Rückzahlung und Forderung sind erledigt.')
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::SETTLED, 'settled_at' => now()])),
Action::make('waive')
->label('Erlassen')
->icon(Heroicon::OutlinedXMark)
->color('gray')
->requiresConfirmation()
->modalDescription('Es werden keine Stornokosten berechnet.')
->visible(fn (Cancellation $record): bool => $record->status === Cancellation::OPEN)
->action(fn (Cancellation $record) => $record->update(['status' => Cancellation::WAIVED, 'settled_at' => now()])),
]);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$open = Cancellation::query()->where('status', Cancellation::OPEN)->count();
return $open > 0 ? (string) $open : null;
}
public static function getNavigationBadgeColor(): string
{
return 'warning';
}
public static function getPages(): array
{
return [
'index' => ListCancellations::route('/'),
];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Filament\Resources\Cancellations\Pages;
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\Cancellations\CancellationResource;
use App\Models\Property;
use Filament\Resources\Pages\ListRecords;
use Illuminate\Database\Eloquent\Builder;
class ListCancellations extends ListRecords
{
use ListsCurrentProperty;
protected static string $resource = CancellationResource::class;
protected function scopeToProperty(Builder $query, Property $property): Builder
{
return $query->whereHas('booking', fn (Builder $booking) => $booking->where('property_id', $property->id));
}
}
@@ -20,13 +20,13 @@ class ChannelTaskResource extends Resource
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Verwaltung';
protected static ?string $modelLabel = 'Portal-Aufgabe';
protected static ?string $pluralModelLabel = 'Portal-Aufgaben';
protected static ?int $navigationSort = 4;
protected static ?int $navigationSort = 3;
public static function table(Table $table): Table
{
@@ -2,9 +2,13 @@
namespace App\Filament\Resources\ChannelTasks\Tables;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskProof;
use App\Enums\ChannelTaskStatus;
use App\Models\ChannelTask;
use Filament\Actions\Action;
use Filament\Forms\Components\Radio;
use Filament\Forms\Components\Textarea;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
@@ -24,6 +28,8 @@ public static function configure(Table $table): Table
TextColumn::make('reason')->label('Anlass')->wrap(),
TextColumn::make('status')->label('Status')->badge()
->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
TextColumn::make('proof')->label('Nachweis')->state(fn (ChannelTask $record): string => $record->proofLabel())
->description(fn (ChannelTask $record): ?string => $record->proof_by ? "{$record->proof_by}, {$record->proof_at?->format('d.m. H:i')}" : null)->wrap(),
TextColumn::make('created_at')->label('Seit')->since(),
TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true),
])
@@ -45,7 +51,26 @@ public static function configure(Table $table): Table
->icon(Heroicon::OutlinedCheck)
->color('success')
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)),
->modalHeading(fn (ChannelTask $record): string => ($record->action === ChannelTaskAction::Block ? 'Sperre in ' : 'Freigabe in ').$record->channel->name.' erledigt')
->modalDescription('Was können Sie sagen? Ein bereitgestellter Kalender beweist nicht, dass das Portal ihn schon übernommen hat.')
->fillForm(['proof' => ChannelTaskProof::Initiated->value])
->schema(fn (ChannelTask $record): array => [
Radio::make('proof')->hiddenLabel()->required()
->options(collect(ChannelTaskProof::cases())->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()),
Textarea::make('note')->label('Notiz (optional)')->placeholder('z. B. „im Vermieterkalender rot markiert“')->rows(2),
])
->action(fn (ChannelTask $record, array $data) => $record->complete(auth()->user()->name, ChannelTaskProof::from($data['proof']), $data['note'] ?? null)),
Action::make('prove')
->label('Nachweis ergänzen')
->icon(Heroicon::OutlinedShieldCheck)
->color('gray')
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Done && $record->proof !== ChannelTaskProof::Confirmed)
->schema(fn (ChannelTask $record): array => [
Radio::make('proof')->hiddenLabel()->required()
->options(collect([ChannelTaskProof::Observed, ChannelTaskProof::Confirmed])->mapWithKeys(fn (ChannelTaskProof $proof): array => [$proof->value => $proof->question($record->action === ChannelTaskAction::Block)])->all()),
Textarea::make('note')->label('Notiz (optional)')->rows(2),
])
->action(fn (ChannelTask $record, array $data) => $record->prove(ChannelTaskProof::from($data['proof']), auth()->user()->name, $data['note'] ?? null)),
Action::make('dismiss')
->label('Verwerfen')
->icon(Heroicon::OutlinedXMark)
@@ -27,7 +27,7 @@ class ChannelResource extends Resource
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedArrowsRightLeft;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static string|UnitEnum|null $navigationGroup = 'Einrichtung';
protected static ?string $navigationLabel = 'Kalenderabgleich (iCal)';
@@ -3,13 +3,18 @@
namespace App\Filament\Resources\Channels\Schemas;
use App\Channels\ChannelRegistry;
use App\Enums\CaseIntakeMode;
use App\Enums\ChannelBookingModel;
use App\Enums\ChannelEchoBehavior;
use App\Enums\ChannelExportMode;
use App\Enums\ChannelStatus;
use App\Enums\IntakeKind;
use App\Enums\ProcessSetting;
use App\Filament\Forms\ProcessSettingFields;
use App\Models\Channel;
use App\Models\Property;
use App\Support\CurrentProperty;
use App\Support\Settings;
use Filament\Forms\Components\DateTimePicker;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
@@ -17,6 +22,7 @@
use Filament\Forms\Components\Toggle;
use Filament\Infolists\Components\TextEntry;
use Filament\Schemas\Components\Group;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Schema;
@@ -48,8 +54,16 @@ public static function configure(Schema $schema, bool $selectProperty = false):
->required()
->maxLength(100),
Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(),
Select::make('booking_model')->label('Buchungsmodell')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required()
->helperText('Fachliche Einordnung; löst keine automatischen Buchungsentscheidungen aus.'),
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.')
@@ -95,4 +109,39 @@ public static function configure(Schema $schema, bool $selectProperty = false):
->columnSpanFull(),
]);
}
/**
* What a contract template brings along, shown under the template choice.
*/
/**
* Deviations of this portal from the landlord's defaults, separately for requests and for bookings that are already
* binding when they arrive. Empty fields follow the defaults (System › So arbeite ich).
*
* @return list<Section>
*/
private static function processSections(): 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);
};
$settingsFor = fn (IntakeKind $intake): array => array_values(array_filter(ProcessSetting::cases(), fn (ProcessSetting $setting): bool => in_array($intake, $setting->channelIntakes(), true)));
return [
Section::make('Anfragen über dieses Portal')
->description('Nur ausfüllen, was bei diesem Portal anders ist als in Ihren Standardeinstellungen.')
->columns(2)
->columnSpanFull()
->collapsible()
->schema(ProcessSettingFields::make('process_overrides.inquiry.', $settingsFor(IntakeKind::Inquiry), $inherited)),
Section::make('Feste Buchungen über dieses Portal')
->description('Buchungen, die beim Portal schon verbindlich sind. Die Vertragsvorlage bringt Vertragstext, Stornoregel und Anlagen mit.')
->columns(2)
->columnSpanFull()
->collapsible()
->schema(ProcessSettingFields::make('process_overrides.booking.', $settingsFor(IntakeKind::Booking), $inherited)),
];
}
}
Loaded 100 of 333 files, more files were not shown because too many files have changed in this diff. Show more