Buchungsprozess: Angebots-Snapshot, atomare Annahme, Auto-Angebot, Kanalfreigabe
Deploy FeWo mit PipelineManager / deploy (push) Failing after 3m38s
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>
This commit is contained in:
1 parent
e7cc37a15b
commit
eafab8a2cb
47 files changed
+2099
-104
No files matched your search
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.
|
||||
@@ -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.**
|
||||
+141
-24
@@ -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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Availability\CalendarClearance;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OfferMode;
|
||||
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),
|
||||
* and the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed).
|
||||
*/
|
||||
class AutoOffer
|
||||
{
|
||||
public function __construct(
|
||||
private SendOffer $sendOffer,
|
||||
private CalendarClearance $clearance,
|
||||
private AvailabilityChecker $availability,
|
||||
) {}
|
||||
|
||||
public function applies(Booking $booking): bool
|
||||
{
|
||||
return $booking->property->offer_mode === OfferMode::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 (! $property->pre_reservation_enabled) {
|
||||
$reasons[] = 'Die Vorreservierung ist für diese Wohnung ausgeschaltet; 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).';
|
||||
}
|
||||
|
||||
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->property->pre_reservation_enabled) {
|
||||
$this->clearance->refresh($booking->property);
|
||||
}
|
||||
|
||||
$reasons = $this->blockers($booking);
|
||||
if ($reasons !== []) {
|
||||
return $reasons;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->sendOffer->handle($booking->fresh());
|
||||
} 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'));
|
||||
}
|
||||
}
|
||||
@@ -3,56 +3,128 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Mail\BookingConfirmed;
|
||||
use App\Models\Booking;
|
||||
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();
|
||||
$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): bool
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
|
||||
try {
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if (! $notifyGuest) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'hold_expires_at' => null,
|
||||
'confirmed_at' => now(),
|
||||
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
|
||||
]);
|
||||
});
|
||||
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if ($notifyGuest) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
|
||||
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->saveQuietly();
|
||||
|
||||
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()])->saveQuietly();
|
||||
$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);
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
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;
|
||||
|
||||
@@ -84,7 +85,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' => $property->pre_reservation_enabled ? now()->addHours($property->hold_hours) : null,
|
||||
'message' => $message,
|
||||
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
||||
]);
|
||||
@@ -138,15 +139,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) {
|
||||
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]);
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
-11
@@ -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));
|
||||
|
||||
@@ -3,10 +3,13 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
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 +17,14 @@
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Pricing\StayRequest;
|
||||
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,6 +38,7 @@ public function __construct(
|
||||
private PriceCalculator $calculator,
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
private Inbox $inbox,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -51,6 +58,12 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
|
||||
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||
|
||||
@@ -84,19 +97,48 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
||||
'offer_version' => $booking->offer_version + 1,
|
||||
'offer_sent_at' => now(),
|
||||
'offer_message' => $changes['offer_message'] ?? null,
|
||||
'offer_terms' => OfferTerms::capture(),
|
||||
]);
|
||||
$booking->refresh();
|
||||
$booking->update(['offer_hash' => OfferTerms::hash($booking)]);
|
||||
});
|
||||
|
||||
$booking->refresh();
|
||||
$this->contract->generate($booking, draft: true);
|
||||
|
||||
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.
|
||||
*/
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\AutoOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OfferMode;
|
||||
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())
|
||||
->whereHas('property', fn ($query) => $query->where('offer_mode', OfferMode::Automatic)->where('pre_reservation_enabled', true))
|
||||
->with(['property', 'guest'])
|
||||
->get();
|
||||
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
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, texts: array<string, ?string>, deposit_due_days: int, owner: array<string, mixed>, bank: array<string, mixed>}
|
||||
*/
|
||||
public static function capture(): array
|
||||
{
|
||||
return [
|
||||
'captured_at' => now()->toIso8601String(),
|
||||
'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => Content::get($key)])->all(),
|
||||
'deposit_due_days' => (int) config('fewo.deposit_due_days'),
|
||||
'owner' => (array) config('fewo.owner'),
|
||||
'bank' => (array) config('fewo.bank'),
|
||||
];
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -11,18 +11,27 @@
|
||||
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 => 'danger',
|
||||
self::ChannelConflict, self::SyncFailed => 'danger',
|
||||
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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.");
|
||||
|
||||
@@ -168,6 +168,18 @@ protected function getHeaderActions(): array
|
||||
|
||||
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
|
||||
}),
|
||||
Action::make('resendConfirmation')
|
||||
->label(fn (): string => $this->record->confirmation_failed_at !== null ? 'Bestätigung erneut senden (Versand fehlgeschlagen)' : 'Bestätigung erneut senden')
|
||||
->icon(Heroicon::OutlinedEnvelope)
|
||||
->color(fn (): string => $this->record->confirmation_failed_at !== null ? 'danger' : 'gray')
|
||||
->visible(fn (): bool => in_array($this->record->status, BookingStatus::occupying(), true))
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Die Buchungsbestätigung mit dem Mietvertrag wird noch einmal an den Gast gesendet.')
|
||||
->action(function (ConfirmBooking $confirm): void {
|
||||
$sent = $confirm->resend($this->record->fresh());
|
||||
$notification = Notification::make()->title($sent ? 'Bestätigung gesendet' : 'Versand fehlgeschlagen');
|
||||
($sent ? $notification->success() : $notification->danger()->body('Details im Postfach.'))->send();
|
||||
}),
|
||||
Action::make('contract')
|
||||
->label('Mietvertrag')
|
||||
->icon(Heroicon::OutlinedDocumentText)
|
||||
@@ -180,7 +192,7 @@ protected function getHeaderActions(): array
|
||||
->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.')
|
||||
->modalDescription('Der Vertrag wird mit den Bedingungen des angenommenen Angebots 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();
|
||||
|
||||
@@ -68,6 +68,20 @@ public static function configure(Schema $schema): Schema
|
||||
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('processing')
|
||||
->label('Bearbeitung / Vorreservierung')
|
||||
->state(fn (Booking $record): string => $record->property->offer_mode->value === 'automatic' ? 'Automatisch' : 'Manuell')
|
||||
->visible(fn (Booking $record): bool => $record->isDirect()),
|
||||
TextEntry::make('offer')
|
||||
->label('Angebot')
|
||||
->state(fn (Booking $record): string => 'Version '.$record->offer_version.', gesendet '.$record->offer_sent_at?->format('d.m.Y, H:i').' · Prüfsumme '.substr((string) $record->offer_hash, 0, 12))
|
||||
->visible(fn (Booking $record): bool => $record->offer_version > 0),
|
||||
TextEntry::make('accepted_at')->label('Angenommen am')->dateTime('d.m.Y, H:i:s')->visible(fn (Booking $record): bool => $record->accepted_at !== null),
|
||||
TextEntry::make('confirmation')
|
||||
->label('Bestätigungs-E-Mail')
|
||||
->state(fn (Booking $record): string => $record->confirmation_sent_at !== null ? 'Gesendet '.$record->confirmation_sent_at->format('d.m.Y, H:i') : 'Nicht zugestellt – bitte „Bestätigung erneut senden“')
|
||||
->color(fn (Booking $record): string => $record->confirmation_sent_at !== null ? 'success' : 'danger')
|
||||
->visible(fn (Booking $record): bool => $record->confirmation_sent_at !== null || $record->confirmation_failed_at !== null),
|
||||
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')
|
||||
|
||||
@@ -2,14 +2,17 @@
|
||||
|
||||
namespace App\Filament\Resources\Properties\Schemas;
|
||||
|
||||
use App\Enums\OfferMode;
|
||||
use App\Filament\Forms\Components\EuroInput;
|
||||
use App\ImageWorlds\ImageWorldRegistry;
|
||||
use App\Models\Site;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\TimePicker;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
@@ -113,6 +116,22 @@ public static function configure(Schema $schema): Schema
|
||||
->minValue(1)
|
||||
->suffix('Stunden')
|
||||
->default(48),
|
||||
Toggle::make('pre_reservation_enabled')
|
||||
->label('Anfrage blockiert den Kalender (Vorreservierung)')
|
||||
->helperText('Aus: eine bloße Anfrage sperrt keinen Zeitraum. Dann ist kein automatisches Angebot möglich.')
|
||||
->default(true)
|
||||
->live(),
|
||||
Select::make('offer_mode')
|
||||
->label('Bearbeitung von Anfragen')
|
||||
->options(OfferMode::class)
|
||||
->default(OfferMode::Manual)
|
||||
->required()
|
||||
->helperText('Automatisch: das Angebot geht sofort an den Gast, wenn die Kalenderprüfung bestanden ist (Kalenderstand aktuell, bei Portalen mit Sofortbuchung unser Feed nachweislich abgerufen). Sonst entscheiden Sie von Hand. Unabhängig vom Testbetrieb der E-Mails.')
|
||||
->rules([fn (Get $get): Closure => function (string $attribute, mixed $value, Closure $fail) use ($get): void {
|
||||
if (($value === OfferMode::Automatic->value || $value === OfferMode::Automatic) && ! $get('pre_reservation_enabled')) {
|
||||
$fail('Automatische Angebote brauchen die Vorreservierung: ohne Sperre im Kalender kann ein verbindlich annehmbares Angebot nicht sicher erteilt werden.');
|
||||
}
|
||||
}]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -49,24 +49,41 @@ public function accept(Request $request, Booking $booking, AcceptOffer $accept):
|
||||
{
|
||||
$request->validate(['terms' => ['accepted']], ['terms.accepted' => 'Bitte bestätigen Sie, dass Sie die Bedingungen gelesen haben.']);
|
||||
|
||||
return $this->answer($request, $booking, fn (int $version) => $accept->handle($booking, $version), 'Vielen Dank! Ihre Buchung ist verbindlich. Die Bestätigung mit dem Mietvertrag haben wir Ihnen per E-Mail gesendet.');
|
||||
return $this->answer($request, $booking, function (int $version) use ($accept, $booking): string {
|
||||
$concluded = $accept->handle($booking, $version);
|
||||
$booking->refresh();
|
||||
|
||||
if (! $concluded) {
|
||||
return 'Ihre Buchung ist bereits verbindlich bestätigt – Sie müssen nichts weiter tun.';
|
||||
}
|
||||
|
||||
return $booking->confirmation_sent_at !== null
|
||||
? 'Vielen Dank! Ihre Buchung ist verbindlich. Die Bestätigung mit dem Mietvertrag haben wir Ihnen per E-Mail gesendet.'
|
||||
: 'Vielen Dank! Ihre Buchung ist verbindlich. Die Bestätigung mit dem Mietvertrag erhalten Sie in Kürze per E-Mail; kommt sie nicht an, melden wir uns bei Ihnen.';
|
||||
});
|
||||
}
|
||||
|
||||
public function reject(Request $request, Booking $booking, RejectOffer $reject): RedirectResponse
|
||||
{
|
||||
return $this->answer($request, $booking, fn (int $version) => $reject->handle($booking, $version), 'Schade – wir haben Ihre Absage erhalten und den Zeitraum wieder freigegeben. Vielleicht ein anderes Mal!');
|
||||
return $this->answer($request, $booking, function (int $version) use ($reject, $booking): string {
|
||||
$reject->handle($booking, $version);
|
||||
|
||||
return 'Schade – wir haben Ihre Absage erhalten und den Zeitraum wieder freigegeben. Vielleicht ein anderes Mal!';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the answer and returns to a freshly signed offer page with the result.
|
||||
* Runs the answer (it returns the success message) and returns to a freshly signed offer page with the result.
|
||||
*
|
||||
* @param callable(int): string $action
|
||||
*/
|
||||
private function answer(Request $request, Booking $booking, callable $action, string $success): RedirectResponse
|
||||
private function answer(Request $request, Booking $booking, callable $action): RedirectResponse
|
||||
{
|
||||
$version = (int) $request->query('v');
|
||||
$back = $this->signed($booking, 'offers.show', now()->addDays(30), $version);
|
||||
|
||||
try {
|
||||
$action($version);
|
||||
$success = $action($version);
|
||||
} catch (ReservationException $exception) {
|
||||
return redirect()->to($back)->with('offer.error', $exception->getMessage());
|
||||
}
|
||||
|
||||
@@ -17,12 +17,16 @@ class NewReservation extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Booking $booking) {}
|
||||
/**
|
||||
* @param bool $offerSent the offer already went to the guest automatically
|
||||
* @param list<string> $blockers why the automatic offer was not sent (automatic mode only)
|
||||
*/
|
||||
public function __construct(public Booking $booking, public bool $offerSent = false, public array $blockers = []) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Neue Anfrage '.$this->booking->reference.': '.$this->booking->guest->full_name.', '.$this->booking->arrival->format('d.m.').'–'.$this->booking->departure->format('d.m.Y'),
|
||||
subject: ($this->offerSent ? 'Angebot automatisch versendet' : 'Neue Anfrage').' '.$this->booking->reference.': '.$this->booking->guest->full_name.', '.$this->booking->arrival->format('d.m.').'–'.$this->booking->departure->format('d.m.Y'),
|
||||
replyTo: [new Address($this->booking->guest->email, $this->booking->guest->full_name)],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ public function __construct(public Booking $booking) {}
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Ihre Anfrage '.$this->booking->reference.' – Termin vorgemerkt, Angebot folgt',
|
||||
subject: 'Ihre Anfrage '.$this->booking->reference.($this->booking->isHoldActive() ? ' – Termin vorgemerkt, Angebot folgt' : ' – Eingang bestätigt, Angebot folgt'),
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ReferralSource;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
@@ -18,6 +19,7 @@
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
/**
|
||||
* A reservation or booking. arrival is the first night, departure the day the guest leaves,
|
||||
@@ -53,10 +55,14 @@
|
||||
'offer_sent_at',
|
||||
'offer_message',
|
||||
'offer_path',
|
||||
'offer_terms',
|
||||
'offer_hash',
|
||||
'message',
|
||||
'internal_notes',
|
||||
'confirmed_at',
|
||||
'accepted_at',
|
||||
'confirmation_sent_at',
|
||||
'confirmation_failed_at',
|
||||
'acceptance',
|
||||
'declined_by',
|
||||
'cancelled_at',
|
||||
@@ -132,6 +138,9 @@ protected function casts(): array
|
||||
'offer_sent_at' => 'immutable_datetime',
|
||||
'accepted_at' => 'immutable_datetime',
|
||||
'acceptance' => 'array',
|
||||
'offer_terms' => 'array',
|
||||
'confirmation_sent_at' => 'immutable_datetime',
|
||||
'confirmation_failed_at' => 'immutable_datetime',
|
||||
'cancelled_at' => 'immutable_datetime',
|
||||
'review_requested_at' => 'immutable_datetime',
|
||||
'deposit_reminded_at' => 'immutable_datetime',
|
||||
@@ -262,6 +271,31 @@ public function nights(): int
|
||||
return (int) $this->arrival->diffInDays($this->departure);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inside a transaction: locks the property (the lock every writer of bookings takes) and this booking's row
|
||||
* and reloads the attributes from the locked row, so status and dates are the latest committed ones.
|
||||
*/
|
||||
public function lockForTransition(): void
|
||||
{
|
||||
Property::withoutGlobalScope('tenant')->whereKey($this->property_id)->lockForUpdate()->first();
|
||||
|
||||
$locked = static::withoutGlobalScope('tenant')->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
|
||||
$this->setRawAttributes($locked->getAttributes(), sync: true);
|
||||
}
|
||||
|
||||
/**
|
||||
* A contract text of this offer version (frozen snapshot, live text for bookings without one).
|
||||
*/
|
||||
public function offerText(string $key): ?string
|
||||
{
|
||||
return OfferTerms::text($this, $key);
|
||||
}
|
||||
|
||||
public function offerHtml(string $key): HtmlString
|
||||
{
|
||||
return OfferTerms::html($this, $key);
|
||||
}
|
||||
|
||||
public function isHoldActive(): bool
|
||||
{
|
||||
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\OfferMode;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Factories\PropertyFactory;
|
||||
@@ -29,6 +30,8 @@
|
||||
'deposit_percent',
|
||||
'balance_due_days_before_arrival',
|
||||
'hold_hours',
|
||||
'offer_mode',
|
||||
'pre_reservation_enabled',
|
||||
'check_in_time',
|
||||
'check_out_time',
|
||||
'changeover_weekday',
|
||||
@@ -56,12 +59,16 @@ class Property extends Model
|
||||
'min_stay_fill_gaps' => true,
|
||||
'min_stay_until_changeover' => false,
|
||||
'min_stay_absolute' => 2,
|
||||
'offer_mode' => 'manual',
|
||||
'pre_reservation_enabled' => true,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'offer_mode' => OfferMode::class,
|
||||
'pre_reservation_enabled' => 'boolean',
|
||||
'min_stay_fill_gaps' => 'boolean',
|
||||
'min_stay_until_changeover' => 'boolean',
|
||||
'changeover_weekday' => 'integer',
|
||||
|
||||
@@ -5,11 +5,15 @@
|
||||
use App\Actions\CreateChannelTasks;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Property;
|
||||
use App\Support\Inbox;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Keeps manually maintained portals in step when a booking starts or stops occupying the calendar.
|
||||
@@ -42,6 +46,26 @@ public function updated(Booking $booking): void
|
||||
}
|
||||
}
|
||||
|
||||
private function reportSyncFailure(int $propertyId, int $bookingId, string $reason, Throwable $exception): void
|
||||
{
|
||||
Log::error('Portalaufgaben für Buchung nicht angelegt', ['booking' => $bookingId, 'exception' => $exception::class]);
|
||||
|
||||
rescue(function () use ($propertyId, $bookingId, $reason): void {
|
||||
$property = Property::withoutGlobalScope('tenant')->find($propertyId);
|
||||
if ($property === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($property->tenant, fn () => app(Inbox::class)->post(
|
||||
InboxMessageKind::SyncFailed,
|
||||
'booking-'.$bookingId.':'.now()->format('YmdH'),
|
||||
'Portalabgleich für '.$reason.' fehlgeschlagen',
|
||||
'Die Buchung ist gespeichert, aber die Sperr-/Freigabeaufgaben für die Portale konnten nicht angelegt werden. Bitte den Kalender der Portale prüfen und gegebenenfalls von Hand sperren.',
|
||||
propertyId: $propertyId,
|
||||
));
|
||||
}, report: false);
|
||||
}
|
||||
|
||||
private function occupies(BookingStatus|string|null $status): bool
|
||||
{
|
||||
$status = is_string($status) ? BookingStatus::tryFrom($status) : $status;
|
||||
@@ -58,10 +82,16 @@ private function tasks(Booking $booking, ChannelTaskAction $action, ?CarbonImmut
|
||||
$startsOn ??= $booking->arrival;
|
||||
$endsOn ??= $booking->departure;
|
||||
$reason = "Buchung {$booking->reference}";
|
||||
DB::afterCommit(function () use ($propertyId, $channelId, $originId, $external, $startsOn, $endsOn, $action, $reason): void {
|
||||
$property = Property::withoutGlobalScope('tenant')->find($propertyId);
|
||||
if ($property !== null) {
|
||||
app(TenantContext::class)->run($property->tenant, fn () => $this->createChannelTasks->handle($property, $startsOn, $endsOn, $action, $reason, $channelId, $originId, $external));
|
||||
$bookingId = $booking->id;
|
||||
DB::afterCommit(function () use ($propertyId, $channelId, $originId, $external, $startsOn, $endsOn, $action, $reason, $bookingId): void {
|
||||
// The booking is already saved: a failing portal task must never turn into an error for the guest.
|
||||
try {
|
||||
$property = Property::withoutGlobalScope('tenant')->find($propertyId);
|
||||
if ($property !== null) {
|
||||
app(TenantContext::class)->run($property->tenant, fn () => $this->createChannelTasks->handle($property, $startsOn, $endsOn, $action, $reason, $channelId, $originId, $external));
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
$this->reportSyncFailure($propertyId, $bookingId, $reason, $exception);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ class Inbox
|
||||
/**
|
||||
* @return InboxMessage|null the message to e-mail now – new (wasRecentlyCreated) or due for a reminder – else null
|
||||
*/
|
||||
public function post(InboxMessageKind $kind, string $fingerprint, string $subject, string $body, ?Channel $channel = null, ?string $actionUrl = null): ?InboxMessage
|
||||
public function post(InboxMessageKind $kind, string $fingerprint, string $subject, string $body, ?Channel $channel = null, ?string $actionUrl = null, ?int $propertyId = null): ?InboxMessage
|
||||
{
|
||||
$fingerprint = $kind->value.':'.$fingerprint;
|
||||
|
||||
@@ -37,7 +37,7 @@ public function post(InboxMessageKind $kind, string $fingerprint, string $subjec
|
||||
'subject' => mb_substr($subject, 0, 255),
|
||||
'body' => $body,
|
||||
'channel_id' => $channel?->id,
|
||||
'property_id' => $channel?->property_id,
|
||||
'property_id' => $channel?->property_id ?? $propertyId,
|
||||
'action_url' => $actionUrl,
|
||||
'notified_at' => now(),
|
||||
'last_seen_at' => now(),
|
||||
|
||||
@@ -92,6 +92,8 @@
|
||||
'channels' => [
|
||||
// An import without success for this long triggers an alert.
|
||||
'stale_after_minutes' => (int) env('FEWO_CHANNEL_STALE_AFTER_MINUTES', 60),
|
||||
// Automatic offers and the guest's acceptance need an import at most this old (sync runs every 5 minutes).
|
||||
'fresh_within_minutes' => (int) env('FEWO_CHANNEL_FRESH_WITHIN_MINUTES', 15),
|
||||
// Open manual blocking tasks are reminded after this time.
|
||||
'task_reminder_after_minutes' => (int) env('FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES', 120),
|
||||
// Token for GET /health/sync (external monitoring, e.g. n8n). Empty = endpoint disabled.
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Frozen offer terms + integrity hash per offer version, and delivery tracking of the booking confirmation.
|
||||
* Additive and nullable: existing bookings keep working (NULL = texts are read live, as before).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->json('offer_terms')->nullable()->after('offer_path');
|
||||
$table->string('offer_hash', 64)->nullable()->after('offer_terms');
|
||||
$table->timestamp('confirmation_sent_at')->nullable()->after('accepted_at');
|
||||
$table->timestamp('confirmation_failed_at')->nullable()->after('confirmation_sent_at');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->dropColumn(['offer_terms', 'offer_hash', 'confirmation_sent_at', 'confirmation_failed_at']);
|
||||
});
|
||||
}
|
||||
};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Per property: manual (default) or automatic offers, and whether a request blocks the calendar (pre-reservation).
|
||||
* The defaults reproduce the behaviour before these settings existed.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('properties', function (Blueprint $table) {
|
||||
$table->string('offer_mode', 10)->default('manual')->after('hold_hours');
|
||||
$table->boolean('pre_reservation_enabled')->default(true)->after('offer_mode');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('properties', function (Blueprint $table) {
|
||||
$table->dropColumn(['offer_mode', 'pre_reservation_enabled']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Link nicht mehr gültig', 'message' => 'Dieser Link ist abgelaufen oder ungültig. Bitte verwenden Sie den Link aus unserer neuesten E-Mail oder melden Sie sich bei uns – an Ihrer Buchung wurde nichts verändert.'])
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Seite nicht gefunden', 'message' => 'Diese Seite gibt es nicht (mehr). Vielleicht hilft Ihnen die Startseite weiter.'])
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Sitzung abgelaufen', 'message' => 'Die Seite war zu lange geöffnet. Bitte öffnen Sie sie erneut, zum Beispiel über den Link in unserer E-Mail – Ihre Eingabe wurde nicht gespeichert und an Ihrer Buchung wurde nichts verändert.'])
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Zu viele Anfragen', 'message' => 'Bitte versuchen Sie es in einigen Minuten noch einmal.'])
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Es ist ein Fehler aufgetreten', 'message' => 'Das tut uns leid. Bitte versuchen Sie es später noch einmal oder rufen Sie uns an.'])
|
||||
@@ -0,0 +1 @@
|
||||
@include('errors.layout', ['title' => 'Wartungsarbeiten', 'message' => 'Die Seite ist in Kürze wieder erreichbar.'])
|
||||
@@ -0,0 +1,23 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>{{ $title }}</title>
|
||||
<style>
|
||||
body { font-family: system-ui, sans-serif; background: #f6f2ea; color: #2b3640; margin: 0; }
|
||||
main { max-width: 36rem; margin: 12vh auto; padding: 0 1.5rem; line-height: 1.6; }
|
||||
h1 { font-size: 1.6rem; margin-bottom: .5rem; }
|
||||
a { color: #2c5f7c; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="inhalt">
|
||||
<h1>{{ $title }}</h1>
|
||||
<p>{{ $message }}</p>
|
||||
<p>Fragen? {{ config('fewo.owner.name') }} · {{ config('fewo.owner.phone') }} · <a href="mailto:{{ config('fewo.owner.email') }}">{{ config('fewo.owner.email') }}</a></p>
|
||||
<p><a href="{{ url('/') }}">Zur Startseite</a></p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,29 @@
|
||||
{{-- Shared shell of the public error pages. Self-contained on purpose: no Vite, theme or database access, so it also renders when the application itself is failing. --}}
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="robots" content="noindex">
|
||||
<title>{{ $title }} · {{ config('app.name') }}</title>
|
||||
<style>
|
||||
body { margin: 0; font: 18px/1.6 system-ui, -apple-system, "Segoe UI", Roboto, Arial, sans-serif; color: #1D2A33; background: #F6F2EA; }
|
||||
main { max-width: 36rem; margin: 0 auto; padding: 4rem 1.25rem; }
|
||||
h1 { font-size: 1.75rem; line-height: 1.2; margin: 0 0 1rem; }
|
||||
a { color: #2C5F7C; }
|
||||
a:focus-visible { outline: 2px solid #2C5F7C; outline-offset: 2px; }
|
||||
.code { color: #4E5C66; font-size: .9rem; margin-top: 2rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<h1>{{ $title }}</h1>
|
||||
<p>{{ $text }}</p>
|
||||
<p><a href="{{ url('/') }}">Zur Startseite</a></p>
|
||||
@if (filled(config('fewo.owner.email')))
|
||||
<p>Wir helfen gern persönlich: <a href="mailto:{{ config('fewo.owner.email') }}">{{ config('fewo.owner.email') }}</a>@if (filled(config('fewo.owner.phone'))) · <a href="tel:{{ preg_replace('/[^0-9+]/', '', (string) config('fewo.owner.phone')) }}">{{ config('fewo.owner.phone') }}</a>@endif</p>
|
||||
@endif
|
||||
<p class="code">Fehlercode {{ $code }}</p>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -5,7 +5,7 @@
|
||||
<p class="mt-3 text-emerald-900">
|
||||
Ihre Anfrage <strong>{{ $booking->reference }}</strong> ist eingegangen. Wir haben den Zeitraum
|
||||
<strong>{{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}</strong>
|
||||
bis <strong>{{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr</strong> für Sie vorgemerkt.
|
||||
@if ($booking->isHoldActive())bis <strong>{{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr</strong> für Sie vorgemerkt.@elseif ($booking->status === \App\Enums\BookingStatus::OfferSent)bereits geprüft – unser Angebot ist unterwegs zu Ihnen.@else– eine Reservierung ist damit noch nicht verbunden.@endif
|
||||
</p>
|
||||
<p class="mt-2 text-emerald-900">Eine Bestätigung mit allen Details haben wir an {{ $booking->guest->email }} gesendet.</p>
|
||||
</div>
|
||||
|
||||
@@ -10,7 +10,20 @@
|
||||
@if ($booking->promo_code)
|
||||
**Aktionscode:** {{ $booking->promo_code }}<br>
|
||||
@endif
|
||||
**Vorgemerkt bis:** {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr
|
||||
@if ($booking->isHoldActive() || $booking->status === \App\Enums\BookingStatus::OfferSent)
|
||||
**{{ $offerSent ? 'Angebot gültig bis' : 'Vorgemerkt bis' }}:** {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr
|
||||
@else
|
||||
**Vorreservierung:** keine – der Zeitraum ist nicht im Kalender gesperrt.
|
||||
@endif
|
||||
|
||||
@if ($offerSent)
|
||||
**Das Angebot wurde automatisch an den Gast gesendet.** Sie müssen nichts tun; Annahme oder Ablehnung melden wir Ihnen.
|
||||
@elseif ($blockers !== [])
|
||||
**Automatisches Angebot nicht möglich – bitte selbst prüfen:**
|
||||
@foreach ($blockers as $blocker)
|
||||
- {{ $blocker }}
|
||||
@endforeach
|
||||
@endif
|
||||
|
||||
@include('mail.partials.quote')
|
||||
|
||||
@@ -20,6 +33,6 @@
|
||||
@endif
|
||||
|
||||
<x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])">
|
||||
Angebot senden oder Anfrage ablehnen
|
||||
{{ $offerSent ? 'Vorgang ansehen' : 'Angebot senden oder Anfrage ablehnen' }}
|
||||
</x-mail::button>
|
||||
</x-mail::message>
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
Guten Tag {{ $booking->guest->full_name }},
|
||||
|
||||
wir haben Ihre unverbindliche Anfrage für die **{{ $booking->property->name }}** erhalten und den Zeitraum für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**.
|
||||
wir haben Ihre unverbindliche Anfrage für die **{{ $booking->property->name }}** erhalten.@if ($booking->isHoldActive()) Wir haben den Zeitraum in unserem Kalender für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**.@else Der Zeitraum ist damit noch **nicht reserviert**; er kann in der Zwischenzeit anderweitig vergeben werden.@endif
|
||||
|
||||
**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br>
|
||||
**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@php($owner = \App\Documents\OfferTerms::owner($booking))
|
||||
@php($money = fn (int $cents): string => \App\Support\Money::format($cents))
|
||||
@extends('theme::layouts.app', ['title' => 'Ihr Angebot'])
|
||||
|
||||
@@ -47,10 +48,10 @@
|
||||
<tr class="font-semibold"><td class="pt-3">Gesamtpreis</td><td class="pt-3 text-right">{{ $money($booking->total) }}</td></tr>
|
||||
</table>
|
||||
<p class="mt-3 text-sm text-muted">
|
||||
@if ($booking->balance_due_on->lessThanOrEqualTo(today()->addDays(config('fewo.deposit_due_days'))))
|
||||
Da die Anreise kurz bevorsteht, ist der Gesamtbetrag innerhalb von {{ config('fewo.deposit_due_days') }} Tagen nach Buchung fällig.
|
||||
@if ($booking->balance_due_on->lessThanOrEqualTo(today()->addDays(\App\Documents\OfferTerms::depositDueDays($booking))))
|
||||
Da die Anreise kurz bevorsteht, ist der Gesamtbetrag innerhalb von {{ \App\Documents\OfferTerms::depositDueDays($booking) }} Tagen nach Buchung fällig.
|
||||
@else
|
||||
Anzahlung {{ $money($booking->deposit) }} innerhalb von {{ config('fewo.deposit_due_days') }} Tagen nach Buchung,
|
||||
Anzahlung {{ $money($booking->deposit) }} innerhalb von {{ \App\Documents\OfferTerms::depositDueDays($booking) }} Tagen nach Buchung,
|
||||
Restbetrag {{ $money($booking->total - $booking->deposit) }} bis {{ $booking->balance_due_on->format('d.m.Y') }}.
|
||||
@endif
|
||||
Die Kurtaxe ist nicht enthalten und wird vor Ort entrichtet.
|
||||
@@ -61,10 +62,10 @@
|
||||
@endif
|
||||
|
||||
<h2 class="mt-8 font-display text-2xl">Bedingungen</h2>
|
||||
<div class="prose-theme mt-3">{{ \App\Support\Content::html('contract.terms') }}</div>
|
||||
@if (\App\Support\Content::get('stay.cancellation'))
|
||||
<div class="prose-theme mt-3">{{ $booking->offerHtml('contract.terms') }}</div>
|
||||
@if ($booking->offerText('stay.cancellation'))
|
||||
<h3 class="mt-6 font-semibold">Rücktritt / Stornierung</h3>
|
||||
<div class="prose-theme mt-2">{{ \App\Support\Content::html('stay.cancellation') }}</div>
|
||||
<div class="prose-theme mt-2">{{ $booking->offerHtml('stay.cancellation') }}</div>
|
||||
@endif
|
||||
<p class="mt-4 text-sm text-muted">Den vollständigen Vertragsentwurf finden Sie als PDF im Anhang unserer E-Mail.</p>
|
||||
</section>
|
||||
@@ -78,8 +79,8 @@
|
||||
<span>Ich habe die Angaben und Bedingungen dieses Angebots gelesen.</span>
|
||||
</label>
|
||||
@error('terms')<p class="mt-1 text-sm" role="alert">{{ $message }}</p>@enderror
|
||||
<p class="mt-4 text-sm text-muted">{{ \App\Support\Content::get('offer.accept_note') }}</p>
|
||||
<button type="submit" class="btn-accent mt-4 w-full sm:w-auto">{{ \App\Support\Content::get('offer.accept_button') }}</button>
|
||||
<p class="mt-4 text-sm text-muted">{{ $booking->offerText('offer.accept_note') }}</p>
|
||||
<button type="submit" class="btn-accent mt-4 w-full sm:w-auto">{{ $booking->offerText('offer.accept_button') }}</button>
|
||||
</form>
|
||||
<form method="post" action="{{ $rejectUrl }}" class="mt-6 border-t border-line pt-4">
|
||||
@csrf
|
||||
@@ -88,6 +89,6 @@
|
||||
</section>
|
||||
@endif
|
||||
|
||||
<p class="mt-8 text-sm text-muted">Fragen? {{ config('fewo.owner.name') }} · {{ config('fewo.owner.phone') }} · <a class="underline" href="mailto:{{ config('fewo.owner.email') }}">{{ config('fewo.owner.email') }}</a></p>
|
||||
<p class="mt-8 text-sm text-muted">Fragen? {{ $owner['name'] ?? '' }} · {{ $owner['phone'] ?? '' }} · <a class="underline" href="mailto:{{ $owner['email'] ?? '' }}">{{ $owner['email'] ?? '' }}</a></p>
|
||||
</div>
|
||||
@endsection
|
||||
@@ -1,4 +1,6 @@
|
||||
@php($money = fn (int $cents): string => \App\Support\Money::format($cents))
|
||||
@php($owner = \App\Documents\OfferTerms::owner($booking))
|
||||
@php($bank = \App\Documents\OfferTerms::bank($booking))
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
@@ -23,7 +25,7 @@
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="footer">{{ config('fewo.owner.name') }} · {{ config('fewo.owner.street') }} · {{ config('fewo.owner.city') }} · {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }}</div>
|
||||
<div class="footer">{{ ($owner['name'] ?? null) }} · {{ ($owner['street'] ?? null) }} · {{ ($owner['city'] ?? null) }} · {{ ($owner['phone'] ?? null) }} · {{ ($owner['email'] ?? null) }}</div>
|
||||
|
||||
@if ($logo ?? null)
|
||||
<img src="{{ $logo }}" alt="" style="max-height: 18mm; max-width: 60mm; margin-bottom: 4mm;">
|
||||
@@ -32,22 +34,22 @@
|
||||
@if ($draft ?? false)
|
||||
<h1>Angebot und Mietvertrag (Entwurf)</h1>
|
||||
<p class="muted">Angebot {{ $booking->reference }} · Version {{ $booking->offer_version }} · erstellt am {{ ($booking->offer_sent_at ?? now())->format('d.m.Y') }} · gültig bis {{ $booking->hold_expires_at?->format('d.m.Y, H:i') }} Uhr</p>
|
||||
<p><strong>{{ \App\Support\Content::get('offer.contract_note') }}</strong></p>
|
||||
<p><strong>{{ $booking->offerText('offer.contract_note') }}</strong></p>
|
||||
@else
|
||||
<h1>Mietvertrag Ferienwohnung</h1>
|
||||
<p class="muted">Buchungsnummer {{ $booking->reference }} · ausgestellt am {{ ($booking->confirmed_at ?? now())->format('d.m.Y') }}@if ($booking->accepted_at) · Angebot angenommen am {{ $booking->accepted_at->format('d.m.Y, H:i') }} Uhr @endif</p>
|
||||
@endif
|
||||
|
||||
<p>{{ \App\Support\Content::get('contract.intro') }}</p>
|
||||
<p>{{ $booking->offerText('contract.intro') }}</p>
|
||||
|
||||
<table class="parties">
|
||||
<tr>
|
||||
<td>
|
||||
<h2>Vermieter</h2>
|
||||
{{ config('fewo.owner.name') }}<br>
|
||||
{{ config('fewo.owner.street') }}<br>
|
||||
{{ config('fewo.owner.city') }}<br>
|
||||
Tel. {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }}
|
||||
{{ ($owner['name'] ?? null) }}<br>
|
||||
{{ ($owner['street'] ?? null) }}<br>
|
||||
{{ ($owner['city'] ?? null) }}<br>
|
||||
Tel. {{ ($owner['phone'] ?? null) }} · {{ ($owner['email'] ?? null) }}
|
||||
</td>
|
||||
<td>
|
||||
<h2>Mieter</h2>
|
||||
@@ -84,24 +86,24 @@
|
||||
<p>Anzahlung <strong>{{ $money($booking->deposit) }}</strong> bis zum <strong>{{ $booking->deposit_due_on?->format('d.m.Y') }}</strong>,
|
||||
Restbetrag <strong>{{ $money($booking->total - $booking->deposit) }}</strong> bis zum <strong>{{ $booking->balance_due_on->format('d.m.Y') }}</strong>.</p>
|
||||
@endif
|
||||
@if (config('fewo.bank.iban'))
|
||||
<p>Bankverbindung: {{ config('fewo.bank.account_holder') }} · IBAN {{ config('fewo.bank.iban') }}@if (config('fewo.bank.bic')) · BIC {{ config('fewo.bank.bic') }}@endif · Verwendungszweck: {{ $booking->reference }}</p>
|
||||
@if (($bank['iban'] ?? null))
|
||||
<p>Bankverbindung: {{ ($bank['account_holder'] ?? null) }} · IBAN {{ ($bank['iban'] ?? null) }}@if (($bank['bic'] ?? null)) · BIC {{ ($bank['bic'] ?? null) }}@endif · Verwendungszweck: {{ $booking->reference }}</p>
|
||||
@endif
|
||||
|
||||
<h2>Mietbedingungen</h2>
|
||||
<div class="rich">{{ \App\Support\Content::html('contract.terms') }}</div>
|
||||
<div class="rich">{{ $booking->offerHtml('contract.terms') }}</div>
|
||||
|
||||
@if (\App\Support\Content::get('stay.cancellation'))
|
||||
@if ($booking->offerText('stay.cancellation'))
|
||||
<h2>Rücktritt / Stornierung</h2>
|
||||
<div class="rich">{{ \App\Support\Content::html('stay.cancellation') }}</div>
|
||||
<div class="rich">{{ $booking->offerHtml('stay.cancellation') }}</div>
|
||||
@endif
|
||||
|
||||
@if (\App\Support\Content::get('stay.house_rules'))
|
||||
@if ($booking->offerText('stay.house_rules'))
|
||||
<h2>Hausordnung</h2>
|
||||
<div class="rich">{{ \App\Support\Content::html('stay.house_rules') }}</div>
|
||||
<div class="rich">{{ $booking->offerHtml('stay.house_rules') }}</div>
|
||||
@endif
|
||||
|
||||
<p style="margin-top: 8mm">{{ \App\Support\Content::get('contract.closing') }}</p>
|
||||
<p>{{ config('fewo.owner.name') }}</p>
|
||||
<p style="margin-top: 8mm">{{ $booking->offerText('contract.closing') }}</p>
|
||||
<p>{{ ($owner['name'] ?? null) }}</p>
|
||||
</body>
|
||||
</html>
|
||||
@@ -16,6 +16,10 @@
|
||||
*/
|
||||
Schedule::command('bookings:expire-holds')->everyFiveMinutes()->withoutOverlapping();
|
||||
|
||||
Schedule::command('bookings:auto-offers')->everyFiveMinutes()->withoutOverlapping();
|
||||
|
||||
Schedule::command('bookings:resend-confirmations')->everyFifteenMinutes()->withoutOverlapping();
|
||||
|
||||
Schedule::command('channels:sync')->everyFiveMinutes()->withoutOverlapping(10);
|
||||
|
||||
Schedule::command('channels:fetch-mail')->everyMinute()->withoutOverlapping(5);
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\AcceptOffer;
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OfferMode;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\NewReservation;
|
||||
use App\Mail\OfferMade;
|
||||
use App\Mail\ReservationReceived;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelExportRequest;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Database\Seeders\SiteSeeder;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Offer mode (manual / automatic), optional pre-reservation and the channel dependent release of automatic offers.
|
||||
*/
|
||||
class AutoOfferTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Property $property;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
|
||||
$this->seed([PropertySeeder::class, SiteSeeder::class]);
|
||||
$this->property = Property::sole();
|
||||
Mail::fake();
|
||||
Storage::fake('local');
|
||||
Http::fake(['*' => Http::response('', 500)]);
|
||||
}
|
||||
|
||||
public function test_manual_mode_sends_the_receipt_and_no_offer(): void
|
||||
{
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->status);
|
||||
$this->assertTrue($booking->isHoldActive());
|
||||
Mail::assertSent(ReservationReceived::class, 1);
|
||||
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => ! $mail->offerSent && $mail->blockers === []);
|
||||
Mail::assertNotSent(OfferMade::class);
|
||||
}
|
||||
|
||||
public function test_automatic_mode_sends_the_offer_instead_of_the_receipt(): void
|
||||
{
|
||||
$this->automatic();
|
||||
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->status);
|
||||
$this->assertSame(1, $booking->offer_version);
|
||||
$this->assertNotNull($booking->offer_hash);
|
||||
Mail::assertSent(OfferMade::class, 1);
|
||||
Mail::assertNotSent(ReservationReceived::class);
|
||||
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->offerSent);
|
||||
}
|
||||
|
||||
public function test_automatic_offer_can_be_accepted_end_to_end(): void
|
||||
{
|
||||
$this->automatic();
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertTrue(app(AcceptOffer::class)->handle($booking->fresh(), 1));
|
||||
|
||||
$this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_without_pre_reservation_a_request_blocks_nothing(): void
|
||||
{
|
||||
$this->property->update(['pre_reservation_enabled' => false]);
|
||||
|
||||
$first = $this->request();
|
||||
$second = $this->request('other@example.org');
|
||||
|
||||
$this->assertNull($first->hold_expires_at);
|
||||
$this->assertFalse($first->isHoldActive());
|
||||
$this->assertSame(0, Booking::query()->occupying()->count());
|
||||
$this->assertSame(BookingStatus::Reserved, $second->status);
|
||||
Mail::assertSent(ReservationReceived::class, fn (ReservationReceived $mail): bool => str_contains($mail->render(), 'nicht reserviert') && ! str_contains($mail->render(), 'vorgemerkt'));
|
||||
}
|
||||
|
||||
public function test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why(): void
|
||||
{
|
||||
$this->property->update(['offer_mode' => OfferMode::Automatic, 'pre_reservation_enabled' => false]);
|
||||
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->status);
|
||||
$this->assertStringContainsString('vorreservierung', mb_strtolower($booking->internal_notes));
|
||||
Mail::assertNotSent(OfferMade::class);
|
||||
Mail::assertSent(ReservationReceived::class, 1);
|
||||
Mail::assertSent(NewReservation::class, fn (NewReservation $mail): bool => $mail->blockers !== []);
|
||||
}
|
||||
|
||||
public function test_instant_booking_portal_holds_the_offer_back_until_it_fetched_our_feed(): void
|
||||
{
|
||||
$this->automatic();
|
||||
$channel = $this->channel(['name' => 'Sofort-Portal', 'booking_model' => 'portal_booking']);
|
||||
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->status);
|
||||
$this->assertStringContainsString('Sofort-Portal', $booking->internal_notes);
|
||||
Mail::assertNotSent(OfferMade::class);
|
||||
|
||||
$this->travel(10)->minutes();
|
||||
$this->feedFetch($channel);
|
||||
$this->artisan('bookings:auto-offers')->assertSuccessful();
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->fresh()->status);
|
||||
Mail::assertSent(OfferMade::class, 1);
|
||||
}
|
||||
|
||||
public function test_feed_fetch_before_the_block_or_failed_fetch_or_other_channel_is_no_proof(): void
|
||||
{
|
||||
$this->automatic();
|
||||
$channel = $this->channel(['booking_model' => 'portal_booking']);
|
||||
$other = $this->channel(['name' => 'Anderes Portal', 'booking_model' => 'inquiry']);
|
||||
$this->feedFetch($channel, at: now()->subMinutes(5));
|
||||
$booking = $this->request();
|
||||
$this->travel(5)->minutes();
|
||||
$this->feedFetch($channel, status: 503);
|
||||
$this->feedFetch($other);
|
||||
|
||||
$this->artisan('bookings:auto-offers')->assertSuccessful();
|
||||
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->fresh()->status);
|
||||
}
|
||||
|
||||
public function test_portal_without_instant_booking_needs_no_proof(): void
|
||||
{
|
||||
$this->automatic();
|
||||
$this->channel(['booking_model' => 'inquiry']);
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $this->request()->status);
|
||||
}
|
||||
|
||||
public function test_stale_calendar_import_blocks_the_automatic_offer(): void
|
||||
{
|
||||
$this->automatic();
|
||||
$this->channel(['booking_model' => 'inquiry', 'last_success_at' => now()->subHours(3), 'import_enabled' => true]);
|
||||
|
||||
$booking = $this->request();
|
||||
|
||||
$this->assertSame(BookingStatus::Reserved, $booking->status);
|
||||
$this->assertStringContainsString('nicht aktuell', $booking->internal_notes);
|
||||
}
|
||||
|
||||
public function test_unattributable_feed_request_is_not_recorded_as_proof(): void
|
||||
{
|
||||
$this->get('/kalender/falsches-token.ics')->assertNotFound();
|
||||
|
||||
$this->assertSame(0, ChannelExportRequest::query()->count());
|
||||
}
|
||||
|
||||
public function test_acceptance_is_refused_while_a_portal_calendar_is_stale(): void
|
||||
{
|
||||
$offer = app(SendOffer::class)->handle(Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10', 'guests' => 2]));
|
||||
$this->channel(['booking_model' => 'inquiry', 'last_success_at' => now()->subHours(3)]);
|
||||
|
||||
try {
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
$this->fail('Acceptance needs a recent calendar.');
|
||||
} catch (ReservationException $exception) {
|
||||
$this->assertSame(ReservationException::calendarUnverified()->getMessage(), $exception->getMessage());
|
||||
}
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $offer->fresh()->status);
|
||||
$this->assertNull($offer->fresh()->acceptance);
|
||||
}
|
||||
|
||||
public function test_live_operation_needs_released_contract_texts_for_automatic_offers(): void
|
||||
{
|
||||
$this->automatic();
|
||||
Settings::tenant()->update(['operating_mode' => Settings::MODE_LIVE]);
|
||||
|
||||
$sample = $this->request();
|
||||
$this->assertSame(BookingStatus::Reserved, $sample->status);
|
||||
$this->assertStringContainsString('freigegeben', $sample->internal_notes);
|
||||
|
||||
Content::save(['contract.terms' => '<p>Echte Bedingungen</p>', 'stay.cancellation' => '<p>Echtes Storno</p>']);
|
||||
Settings::tenant()->update(['bank_iban' => 'DE02120300000000202051']);
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $this->request('real@example.org', '2026-12-01', '2026-12-05')->status);
|
||||
}
|
||||
|
||||
private function automatic(): void
|
||||
{
|
||||
$this->property->update(['offer_mode' => OfferMode::Automatic]);
|
||||
}
|
||||
|
||||
private function request(string $email = 'gast@example.org', string $arrival = '2026-11-07', string $departure = '2026-11-10'): Booking
|
||||
{
|
||||
return app(CreateReservation::class)->handle(
|
||||
$this->property->fresh(),
|
||||
new StayRequest(CarbonImmutable::parse($arrival), CarbonImmutable::parse($departure), 2),
|
||||
['first_name' => 'Gast', 'last_name' => 'Test', 'email' => $email],
|
||||
)->fresh(['guest', 'property']);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $attributes
|
||||
*/
|
||||
private function channel(array $attributes = []): Channel
|
||||
{
|
||||
return Channel::factory()->for($this->property)->create([
|
||||
'last_success_at' => now(),
|
||||
'export_enabled' => true,
|
||||
...$attributes,
|
||||
]);
|
||||
}
|
||||
|
||||
private function feedFetch(Channel $channel, int $status = 200, ?DateTimeInterface $at = null): void
|
||||
{
|
||||
ChannelExportRequest::query()->create([
|
||||
'tenant_id' => $channel->tenant_id,
|
||||
'channel_id' => $channel->id,
|
||||
'requested_at' => $at ?? now(),
|
||||
'method' => 'GET',
|
||||
'user_agent' => 'Portal/1.0',
|
||||
'response_status' => $status,
|
||||
'export_state' => $status === 200 ? 'live' : 'frozen',
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,334 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Feature;
|
||||
|
||||
use App\Actions\AcceptOffer;
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Actions\CreateChannelTasks;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingConfirmed;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Mail\OfferMade;
|
||||
use App\Models\Booking;
|
||||
use App\Models\InboxMessage;
|
||||
use App\Models\Property;
|
||||
use App\Support\Content;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Seeders\PropertySeeder;
|
||||
use Database\Seeders\SiteSeeder;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Mail\Events\MessageSending;
|
||||
use Illuminate\Mail\Events\MessageSent;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use RuntimeException;
|
||||
use Tests\TestCase;
|
||||
|
||||
/**
|
||||
* Safety core of the acceptance: frozen offer, locked and idempotent acceptance, contained mail/sync failures.
|
||||
*/
|
||||
class BookingAcceptanceTest extends TestCase
|
||||
{
|
||||
use RefreshDatabase;
|
||||
|
||||
private Property $property;
|
||||
|
||||
private Booking $booking;
|
||||
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this->travelTo(CarbonImmutable::parse('2026-10-22 10:00'));
|
||||
$this->seed([PropertySeeder::class, SiteSeeder::class]);
|
||||
$this->property = Property::sole();
|
||||
Mail::fake();
|
||||
Storage::fake('local');
|
||||
$this->withoutVite();
|
||||
|
||||
$this->booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create([
|
||||
'arrival' => '2026-11-07',
|
||||
'departure' => '2026-11-10',
|
||||
'guests' => 2,
|
||||
]);
|
||||
}
|
||||
|
||||
public function test_offer_freezes_terms_hash_and_payment_data(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
|
||||
$this->assertSame(Content::get('contract.terms'), $offer->offer_terms['texts']['contract.terms']);
|
||||
$this->assertSame(7, $offer->offer_terms['deposit_due_days']);
|
||||
$this->assertSame(OfferTerms::hash($offer), $offer->offer_hash);
|
||||
$this->assertSame(64, strlen($offer->offer_hash));
|
||||
}
|
||||
|
||||
public function test_changed_website_texts_do_not_alter_a_sent_offer_nor_the_contract(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$original = Content::get('contract.terms');
|
||||
Content::save(['contract.terms' => '<p>NEUE BEDINGUNGEN NACH VERSAND</p>']);
|
||||
|
||||
$this->get(app(SendOffer::class)->offerUrl($offer))->assertOk()->assertDontSee('NEUE BEDINGUNGEN NACH VERSAND');
|
||||
$this->assertSame($original, $offer->fresh()->offerText('contract.terms'));
|
||||
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::Confirmed, $booking->status);
|
||||
$this->assertSame($original, $booking->offerText('contract.terms'));
|
||||
$this->assertSame(hash('sha256', json_encode($booking->offer_terms['texts'])), $booking->acceptance['terms_sha256']);
|
||||
}
|
||||
|
||||
public function test_acceptance_records_the_evidence_and_confirms_once(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
|
||||
$this->assertTrue(app(AcceptOffer::class)->handle($offer->fresh(), 1));
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::Confirmed, $booking->status);
|
||||
$this->assertSame($offer->offer_hash, $booking->acceptance['offer_hash']);
|
||||
$this->assertSame(1, $booking->acceptance['offer_version']);
|
||||
$this->assertNotNull($booking->acceptance['valid_until']);
|
||||
$this->assertNotNull($booking->confirmation_sent_at);
|
||||
Storage::disk('local')->assertExists($booking->contract_path);
|
||||
Mail::assertSent(BookingConfirmed::class, 1);
|
||||
Mail::assertSent(OfferAnswered::class, 1);
|
||||
}
|
||||
|
||||
public function test_second_acceptance_of_the_same_version_is_idempotent(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$accept = app(AcceptOffer::class);
|
||||
|
||||
$this->assertTrue($accept->handle($offer->fresh(), 1));
|
||||
$confirmedAt = $offer->fresh()->confirmed_at;
|
||||
$this->travel(5)->minutes();
|
||||
|
||||
$this->assertFalse($accept->handle($offer->fresh(), 1));
|
||||
|
||||
$this->assertEquals($confirmedAt, $offer->fresh()->confirmed_at);
|
||||
Mail::assertSent(BookingConfirmed::class, 1);
|
||||
Mail::assertSent(OfferAnswered::class, 1);
|
||||
}
|
||||
|
||||
public function test_stale_copy_of_the_booking_cannot_accept_again(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$stale = $offer->fresh();
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
|
||||
// The second request still holds the model as it was before the first one committed.
|
||||
$this->assertFalse(app(AcceptOffer::class)->handle($stale, 1));
|
||||
Mail::assertSent(BookingConfirmed::class, 1);
|
||||
}
|
||||
|
||||
public function test_tampered_offer_is_refused_without_a_trace_of_acceptance(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$offer->update(['total' => $offer->total - 10000]);
|
||||
|
||||
try {
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
$this->fail('A changed offer must not be accepted.');
|
||||
} catch (ReservationException $exception) {
|
||||
$this->assertSame(ReservationException::offerChanged()->getMessage(), $exception->getMessage());
|
||||
}
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->status);
|
||||
$this->assertNull($booking->accepted_at);
|
||||
$this->assertNull($booking->acceptance);
|
||||
$this->assertSame(1, InboxMessage::query()->where('kind', InboxMessageKind::OfferRejected)->count());
|
||||
Mail::assertNotSent(BookingConfirmed::class);
|
||||
}
|
||||
|
||||
public function test_changed_terms_snapshot_is_refused(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$terms = $offer->offer_terms;
|
||||
$terms['texts']['stay.cancellation'] = 'Kostenlos stornierbar';
|
||||
$offer->update(['offer_terms' => $terms]);
|
||||
|
||||
$this->expectException(ReservationException::class);
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
}
|
||||
|
||||
public function test_conflicting_occupation_prevents_acceptance_and_leaves_no_evidence(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$this->property->blockedPeriods()->create(['starts_on' => '2026-11-08', 'ends_on' => '2026-11-09', 'reason' => 'Portal']);
|
||||
|
||||
try {
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
$this->fail('A conflicting occupation must prevent the booking.');
|
||||
} catch (ReservationException $exception) {
|
||||
$this->assertSame(ReservationException::notAvailable()->getMessage(), $exception->getMessage());
|
||||
}
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->status);
|
||||
$this->assertNull($booking->accepted_at);
|
||||
$this->assertNull($booking->acceptance);
|
||||
}
|
||||
|
||||
public function test_expired_offer_cannot_be_accepted(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$this->travel(49)->hours();
|
||||
|
||||
$this->expectExceptionMessage(ReservationException::offerExpired()->getMessage());
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
}
|
||||
|
||||
public function test_failing_confirmation_mail_keeps_the_binding_booking_and_can_be_resent(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$mailServer = $this->useRealMailer();
|
||||
|
||||
$this->assertTrue(app(AcceptOffer::class)->handle($offer->fresh(), 1));
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::Confirmed, $booking->status);
|
||||
$this->assertNull($booking->confirmation_sent_at);
|
||||
$this->assertNotNull($booking->confirmation_failed_at);
|
||||
$message = InboxMessage::query()->where('kind', InboxMessageKind::ConfirmationFailed)->sole();
|
||||
$this->assertStringNotContainsString('guest@example.org', $message->subject.$message->body);
|
||||
|
||||
$mailServer->down = false;
|
||||
$this->assertTrue(app(ConfirmBooking::class)->resend($booking));
|
||||
|
||||
$booking = $booking->fresh();
|
||||
$this->assertNotNull($booking->confirmation_sent_at);
|
||||
$this->assertNull($booking->confirmation_failed_at);
|
||||
$this->assertSame(1, $mailServer->delivered);
|
||||
}
|
||||
|
||||
public function test_failing_offer_mail_is_reported_but_the_offer_stays(): void
|
||||
{
|
||||
$this->useRealMailer();
|
||||
|
||||
try {
|
||||
app(SendOffer::class)->handle($this->booking->fresh());
|
||||
$this->fail('The caller must learn that the mail was not sent.');
|
||||
} catch (ReservationException) {
|
||||
// expected
|
||||
}
|
||||
|
||||
$this->assertSame(BookingStatus::OfferSent, $this->booking->fresh()->status);
|
||||
$this->assertSame(1, InboxMessage::query()->where('kind', InboxMessageKind::OfferMailFailed)->count());
|
||||
}
|
||||
|
||||
public function test_failing_portal_task_creation_does_not_fail_the_acceptance(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$this->mock(CreateChannelTasks::class)->shouldReceive('handle')->andThrow(new RuntimeException('db gone'));
|
||||
|
||||
$this->assertTrue(app(AcceptOffer::class)->handle($offer->fresh(), 1));
|
||||
|
||||
$this->assertSame(BookingStatus::Confirmed, $offer->fresh()->status);
|
||||
$this->assertSame(1, InboxMessage::query()->where('kind', InboxMessageKind::SyncFailed)->count());
|
||||
}
|
||||
|
||||
public function test_get_on_the_offer_link_never_changes_the_booking(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$url = app(SendOffer::class)->offerUrl($offer);
|
||||
|
||||
$this->get($url)->assertOk();
|
||||
$this->get($url)->assertOk();
|
||||
|
||||
$booking = $offer->fresh();
|
||||
$this->assertSame(BookingStatus::OfferSent, $booking->status);
|
||||
$this->assertNull($booking->accepted_at);
|
||||
}
|
||||
|
||||
public function test_two_overlapping_stays_cannot_both_become_binding(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$other = Booking::factory()->for($this->property)->reserved(now()->subHour())->create([
|
||||
'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'guests' => 2,
|
||||
]);
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
|
||||
$this->expectException(ReservationException::class);
|
||||
app(ConfirmBooking::class)->handle($other->fresh(), notifyGuest: false);
|
||||
}
|
||||
|
||||
public function test_accepting_twice_over_http_shows_success_both_times_and_mails_once(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$page = app(SendOffer::class)->offerUrl($offer);
|
||||
preg_match('~action="([^"]*/annehmen[^"]*)"~', $this->get($page)->getContent(), $match);
|
||||
$action = html_entity_decode($match[1]);
|
||||
|
||||
$this->followingRedirects()->post($action, ['terms' => '1'])->assertOk()->assertSee('Ihre Buchung ist verbindlich');
|
||||
$this->followingRedirects()->post($action, ['terms' => '1'])->assertOk()->assertSee('bereits verbindlich bestätigt');
|
||||
|
||||
Mail::assertSent(BookingConfirmed::class, 1);
|
||||
}
|
||||
|
||||
public function test_invalid_signature_shows_the_german_error_page(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
|
||||
$this->get(app(SendOffer::class)->offerUrl($offer).'x')->assertForbidden()->assertSee('Link nicht mehr gültig');
|
||||
}
|
||||
|
||||
public function test_command_retries_failed_confirmations_once_the_mail_server_is_back(): void
|
||||
{
|
||||
$offer = $this->makeOffer();
|
||||
$mailServer = $this->useRealMailer();
|
||||
app(AcceptOffer::class)->handle($offer->fresh(), 1);
|
||||
$this->assertNotNull($offer->fresh()->confirmation_failed_at);
|
||||
|
||||
$mailServer->down = false;
|
||||
$this->artisan('bookings:resend-confirmations')->assertSuccessful();
|
||||
|
||||
$this->assertNotNull($offer->fresh()->confirmation_sent_at);
|
||||
$this->assertNull($offer->fresh()->confirmation_failed_at);
|
||||
$this->assertSame(1, $mailServer->delivered);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the mail fake by the real (array) mailer behind a switchable "mail server".
|
||||
*/
|
||||
private function useRealMailer(): object
|
||||
{
|
||||
Mail::clearResolvedInstance('mail.manager');
|
||||
$this->app->forgetInstance('mail.manager');
|
||||
$this->app->forgetInstance('mailer');
|
||||
|
||||
$server = new class
|
||||
{
|
||||
public bool $down = true;
|
||||
|
||||
public int $delivered = 0;
|
||||
};
|
||||
Event::listen(MessageSending::class, function () use ($server): void {
|
||||
if ($server->down) {
|
||||
throw new RuntimeException('SMTP down: guest@example.org');
|
||||
}
|
||||
});
|
||||
Event::listen(MessageSent::class, function () use ($server): void {
|
||||
$server->delivered++;
|
||||
});
|
||||
|
||||
return $server;
|
||||
}
|
||||
|
||||
private function makeOffer(): Booking
|
||||
{
|
||||
$offer = app(SendOffer::class)->handle($this->booking->fresh());
|
||||
Mail::assertSent(OfferMade::class);
|
||||
Mail::fake();
|
||||
|
||||
return $offer;
|
||||
}
|
||||
}
|
||||
@@ -96,9 +96,7 @@ public function test_guest_accepts_the_offer_and_the_booking_becomes_binding():
|
||||
Mail::assertSent(BookingConfirmed::class);
|
||||
Mail::assertSent(OfferAnswered::class, fn (OfferAnswered $mail): bool => $mail->accepted);
|
||||
|
||||
$html = $this->get($url)->getContent();
|
||||
preg_match('~<main.*</main>~s', $html, $m);
|
||||
dump(strip_tags($m[0] ?? substr($html, 0, 3000)));
|
||||
$this->get($url)->assertOk()->assertSee('angenommen');
|
||||
}
|
||||
|
||||
public function test_link_of_an_older_offer_version_cannot_be_used(): void
|
||||
|
||||
Reference in new issue
Block a user