Compare commits

...
Author SHA1 Message Date
LarsandClaude Opus 5.5 d42c42059c Titelvideo, Rundgang mit Kapiteln, naechste freie Termine, ruhigere Buchungsseite
- Webseite > Videos (Datei, Standbild, Kapitel mit Raum im Grundriss); Upload bis 100 MB
- Titelbereich: Video statt Foto (stumme Schleife, respektiert Bewegung reduzieren/Save-Data)
  und naechste freie Termine mit Gesamtpreis (NextFreeStays)
- Neuer Baustein Rundgang (Video) mit waehlbarer Anordnung; Grundriss springt ins Video
- Buchungsseite: Preis unter dem Kalender, Formular rechts, Ablauf als Grafik
- Seebad: Fahrkarten, Fahrplan-Kapitel, Sonnenaufgang als einmaliges Ereignis

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

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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 09:52:35 +01:00
LarsandClaude Opus 5.5 876a0a20f3 Wohnungsumschalter, Saisonfotos und zentrale Banner zusammenfuehren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m2s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:02:13 +01:00
LarsandClaude Opus 5.5 4e6ad792eb Stand Wohnungsumschalter, Saisonfotos und Banner dokumentieren
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:02:01 +01:00
LarsandClaude Opus 5.5 d2b1a853dc Banner zentral: je Website, Saison und Prioritaet, auch fuer Sonderangebote
Hinweise werden zu Bannern mit Website, Erscheinungsbildern, Prioritaet und
optionalem Sonderangebot (Text, Termin und Link aus dem Angebot, sichtbar nur
solange es beworben wird). Sonderangebote lassen sich mit einem Klick als Banner
zeigen; die Liste nennt das heute sichtbare Banner. Banner-Texte der
Erscheinungsbilder werden zu saisonalen Bannern.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 19:01:48 +01:00
LarsandClaude Opus 5.5 791786ed3e Saisonfotos am Foto statt am Erscheinungsbild
Ein Foto gehoert zu keinem (ganzjaehrig) oder mehreren Erscheinungsbildern und
erscheint nur dort, vor den ganzjaehrigen Fotos. Bausteine waehlen "automatisch"
oder eine eigene Auswahl; Titelbereich und Abschluss zeigen das erste passende
Foto ihrer Liste. Titelbild und "Bilder je Baustein" des Erscheinungsbilds werden
in die Bausteine uebernommen und entfallen dort.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:53:56 +01:00
LarsandClaude Opus 5.5 d02f3e05c7 Eigene Fotokategorie fuer Grundrisse und Plaene, nie in Galerien
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:43:02 +01:00
LarsandClaude Opus 5.5 8bcda9a4bc Wohnungsumschalter im Verwaltungsmenue und wohnungsbezogene Listen
Oben im Seitenmenue waehlt man die Wohnung; Listen, neue Eintraege, Belegungsplan
und Preise & Angebote folgen ihr. Ein geoeffneter Eintrag einer anderen Wohnung
schaltet auf diese um. Galerie und Ersatz-Titelbild der Website zeigen nur Fotos
der Wohnung des Bausteins und Fotos ohne Wohnung.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:40:13 +01:00
Lars e74033a958 Bereitstellung der Kalenderspiegelungen und abweichende Originaltermine dokumentieren [skip ci] 2026-10-29 17:05:59 +01:00
Lars add2367869 Eindeutige iCal-Kalenderspiegelungen automatisch und widerrufbar zuordnen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s
2026-10-29 17:01:30 +01:00
Lars 8b36e07dc4 Bereitgestellte Regeldialog-Korrektur und lesende Abnahme dokumentieren [skip ci] 2026-10-29 16:30:25 +01:00
Lars a0497fcccd iCal-Regelanwendung bei Zeitstempelupdates erlauben und Dialogfehler anzeigen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m53s
2026-10-29 16:25:29 +01:00
Lars 678e15256d Bereitgestellte Zeitstempel-Kompatibilitaet und echten Abruf dokumentieren [skip ci] 2026-10-29 16:08:31 +01:00
Lars 2ae48e77fa iCal-Ereignisse mit LAST-MODIFIED statt fehlendem DTSTAMP lesen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m3s
2026-10-29 15:53:55 +01:00
Lars 386e2cf0a9 Bereitgestellte iCal-Regelbedienung und Konfigurationsbefund dokumentieren [skip ci] 2026-10-29 15:44:04 +01:00
Lars 54efd3b858 Portalreservierungen im Zuordnungsdialog eindeutig benennen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m42s
2026-10-29 15:39:13 +01:00
Lars 7d998e2b81 iCal-Regelentwuerfe sichtbar speichern und Aktivierungsstand anzeigen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 3m0s
2026-10-29 15:34:02 +01:00
Lars e7efb06277 Grundrissvarianten und Hausgrafiken als Entwuerfe sichern [skip ci] 2026-10-29 14:58:41 +01:00
Lars 94df35e702 Lokalen iCal-Snapshotvergleich versionieren [skip ci] 2026-10-29 14:58:41 +01:00
Lars bc3872c01f n8n-Betriebsnachweise und Wiederherstellung dokumentieren [skip ci] 2026-10-29 14:58:40 +01:00
Lars 0bba50bd7b Fachliche Architektur und Vermietungskonzept versionieren [skip ci] 2026-10-29 14:57:38 +01:00
Lars 5bffe44435 Bereitgestellten Sperrzweck und Privat-Kanal dokumentieren [skip ci] 2026-10-27 22:30:54 +01:00
Lars 4389894959 Sperrzeiten um Eigenbelegung und privaten Buchungskanal erweitern
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m49s
2026-10-27 22:26:47 +01:00
Lars 2b2e732612 Bereitgestellte vollstaendige Gastanlage im Dialog dokumentieren [skip ci] 2026-10-27 22:17:51 +01:00
Lars 78aafd7c28 Vollstaendige Gastdaten direkt im Zuordnungsdialog erfassen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m48s
2026-10-27 22:13:43 +01:00
Lars 13f1b5856c Bereitgestellte Belegungsverwaltung und unveraenderten Kalenderbestand dokumentieren [skip ci] 2026-10-27 22:01:37 +01:00
Lars f19d698203 Sperrgruende im Belegungsplan anzeigen und zugeordnete Gaeste verlinken
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m47s
2026-10-27 21:57:06 +01:00
Lars f369018a68 Zentralen Belegungsplan und plattformuebergreifende Buchungs- und Gaesteverwaltung integrieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m41s
2026-10-27 21:51:56 +01:00
Lars c74199e978 Automatischen n8n-Scheduler mit zwei Importlaeufen nachweisen [skip ci] 2026-10-27 21:01:50 +01:00
Lars 4186872b3f n8n-Zugang ueber lokalen SSH-Tunnel wiederherstellen und dokumentieren [skip ci] 2026-10-27 20:52:38 +01:00
Lars f80c0f9f3b Angelegten n8n-Scheduler und erfolgreichen Einzeltest dokumentieren [skip ci] 2026-10-27 20:44:10 +01:00
Lars 1fb839b24e Externen FewoPortal-Scheduler als n8n-Workflow vorbereiten [skip ci] 2026-10-27 19:44:49 +01:00
Lars 2dca2bccfa Fehlende Detailansicht importierter Ostseeklar-Eintraege festhalten [skip ci] 2026-10-27 19:28:54 +01:00
Lars 952f8574c8 Ostseeklar-Rueckmeldung zur fehlenden Namensanzeige dokumentieren [skip ci] 2026-10-27 19:27:46 +01:00
Lars 089d7f894b Umlaute im Auslieferungsnachweis korrigieren [skip ci] 2026-10-27 19:19:45 +01:00
Lars 606ef8850f Abnahme und Auslieferungsstand der iCal-Regelengine dokumentieren [skip ci] 2026-10-27 19:19:22 +01:00
Lars 7c7955b982 Namensweitergabe direkt abschaltbar machen und reale Regelresultate dokumentieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m39s
2026-10-27 19:14:39 +01:00
Lars e9db98701b Visuelle iCal-Regelengine mit Originaldaten und individuellen Exportfeldern integrieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m37s
2026-10-27 19:00:25 +01:00
Lars c4ebccbbea Bereitgestellten iCal-Funktionsbereich dokumentieren [skip ci] 2026-10-27 18:12:05 +01:00
Lars 8927f2eeb1 Kalenderabgleich ueber iCal von weiteren Portalfunktionen abgrenzen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m37s
2026-10-27 18:07:48 +01:00
Lars 25b5a61461 Exportlink und Statuskorrektur als ausgeliefert festhalten [skip ci] 2026-10-27 18:02:59 +01:00
Lars e5a083ce71 Ausstehenden Erstimport von veraltetem Kalender unterscheiden
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m41s
2026-10-27 17:58:07 +01:00
Lars 0be1cfcdb8 Exportlink direkt in der Portalkonfiguration anzeigen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m34s
2026-10-27 17:55:59 +01:00
Lars 2893192344 Kacheln und nachgewiesene Kalenderabrufe dokumentieren [skip ci] 2026-10-27 17:53:41 +01:00
Lars 511faa64d2 Portale als Kacheln zeigen und Kalenderabrufe je Kanal protokollieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m41s
2026-10-27 17:48:17 +01:00
Lars 98eabaeb0c Bereitgestellte Portalverwaltung und Abnahme dokumentieren [skip ci] 2026-10-27 17:35:43 +01:00
Lars 1f59cbb9a5 Eigene Verwaltung fuer frei konfigurierbare Portale und Kalender anbieten
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m34s
2026-10-27 17:29:24 +01:00
Lars 783068501c Generische iCal-Kanäle mit Bestandsklärung und sicheren Exporten bereitstellen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m33s
2026-10-27 17:14:45 +01:00
Lars 6fe5bbc6e3 Doku: Mandantenabschluss auf Strato bestätigt [skip ci] 2026-10-26 17:14:38 +01:00
Lars 06df80e4db Mandantenabschluss: Marken, Vertragsdateien und Archive trennen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m23s
2026-10-26 17:07:11 +01:00
Lars Stommer 86374b1659 Phase-7-Abschluss im Mandantenplan und Übergabestand konsistent festhalten
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m30s
2026-10-26 16:00:02 +01:00
Lars Stommer 1b03689c46 Erprobten Pipeline-Weg und Agentenregeln für FeWo festhalten
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m44s
2026-10-26 14:52:59 +01:00
Lars Stommer e7f79e4075 Runner-Benutzer für OpenSSH im Deployment-Container auflösen
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m42s
2026-10-26 14:47:05 +01:00
Lars Stommer f5d8be5eaf FeWo-Pilot mit freigegebenem PipelineManager 0.1.1 ausführen
Deploy FeWo mit PipelineManager / deploy (push) Failing after 1m59s
2026-10-26 14:43:58 +01:00
Lars Stommer 92fb01da9d PDF-Featuretests im Pipeline-Container mit 512 MB ausführen
Deploy FeWo mit PipelineManager / deploy (push) Failing after 1m10s
2026-10-26 14:36:12 +01:00
Lars Stommer 01900d6550 FeWo-Paket für Stratos Dateilimit bereinigen
Deploy FeWo mit PipelineManager / deploy (push) Failing after 39s
2026-10-26 14:34:50 +01:00
Lars Stommer 8eae37e11d FeWo als Pilot an den eigenständigen PipelineManager anbinden 2026-10-26 13:27:52 +01:00
Lars Stommer 92ccf40312 CI: Host-Umgebung vor PHP-Setup prüfen und Self-hosted-Modus setzen
Deploy / test (push) Failing after 15s
Deploy / deploy (push) Skipped
2026-10-26 08:31:46 +01:00
Lars Stommer 6d8f1d6692 Doku: Phase 7 auf Strato ausgeliefert, Release 20261026072521
Deploy / test (push) Failing after 14s
Deploy / deploy (push) Skipped
2026-10-26 08:27:04 +01:00
Lars Stommer abf0e9004b Wohnung je Baustein wählen und Gitea-Runner-Kompatibilität herstellen
Deploy / test (push) Failing after 2m47s
Deploy / deploy (push) Skipped
2026-10-26 08:23:14 +01:00
Lars StommerandClaude Opus 5 3a0bb6e40f Doku: Phase 6 ist ausgeliefert (Release 20261026065920)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Server und main sind wieder gleich. Die Prüfung am lebenden Server steht
dabei: Bildwelt ostsee mit 11 Plätzen, Auflösung über die Vorgabe der
Installation, Marke noch leer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-26 08:03:19 +01:00
Lars StommerandClaude Opus 5 361acfa12a Doku: Übergabe für die Phase-7-Sitzung
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Der wichtigste Hinweis steht jetzt als erstes in Abschnitt 7: `main` ist
dem Server voraus. Phase 6 liegt auf `main` und ist nicht ausgeliefert, und
sie bringt eine Migration mit. Wer das übersieht, deployt entweder blind
oder hält Server und Code für gleich.

Dazu, was Phase 7 anfassen muss: `Theme::property()` merkt sich die
Wohnung, es fehlt ein Weg, sie je Baustein zu setzen und zurückzusetzen –
mit dem ausdrücklichen Hinweis, dass es eine solche Methode heute nicht
gibt. Und die Regel, die über den ganzen Umbau gilt: jede neue Tabelle
bekommt `tenant_id` und gehört in `TenantArchive::DELETE_ORDER`, sonst
überlebt sie die Kündigung ihres Mandanten.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-26 07:56:04 +01:00
Lars StommerandClaude Opus 5 c459f7f83c Doku: Bildwelten und Marke in STATUS, Plan und Vertragsprotokoll; Platzhalter-Hash korrigiert
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-26 07:38:45 +01:00
Lars StommerandClaude Opus 5 4e66add1f0 Phase 6, Anwendungsseite: Bildwelten und die Marke je Website
Die Theme-Sitzung wartete darauf: Seebad ruft schon ortsneutrale Plätze
über `partials/motif` auf und behilft sich mit einem eigenen `motifs/`-
Ordner. Der Kommentar dort sagt es selbst – „so a later picture-world
system can replace the mapping below". Das System gibt es jetzt.

**Bildwelten** (A18–A20) sind Pakete wie Themes: `resources/image-worlds/
<key>/` mit `world.json` und `svg/`. Eine Website wählt eine Bildwelt, eine
Wohnung darf eine andere tragen – das ist der Platz für die Bergwohnung auf
einer Küsten-Website. Vorlagen fragen über `$theme->motif($slot)` nach einem
Platz, nie nach einer Datei.

Die Render-Logik ist aus Seebads Partial in die Anwendung gewandert, damit
jedes Theme sie bekommt: Inline-SVG (nimmt die Textfarbe an, kein zweiter
Request), Titel und ARIA entfernt, und die internen Ids je Aufruf eindeutig
gemacht – zwei Kopien derselben Grafik auf einer Seite würden sonst auf
denselben Verlauf zeigen und eine davon verlöre ihre Farben.

Ein leerer Platz ist kein Fehler: die Vorlage bekommt schlicht keine
Dekoration. Weil das leicht zu übersehen ist, meldet
`php artisan image-worlds:check`, welcher Platz ohne Datei dasteht.

**Marke je Website** (A14/A22): Logo, Favicon und ein Logo für E-Mail und
Vertrag als Medien der Website. Der Mietvertrag bettet die Datei ein statt
eine URL zu holen – er wird auf dem Server gerendert und darf nicht davon
abhängen, dass dieser sich selbst erreicht. Ohne Logo bleibt der Vertrag
wie bisher.

`resources/themes/**` ist unberührt: die Ostsee-Grafiken sind kopiert, nicht
verschoben. Was die Theme-Sitzung nun tun kann, steht in
ZUSAMMENARBEIT.md §6; ihr Wunsch aus §5 ist als erledigt vermerkt.

272 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-26 07:35:17 +01:00
Lars StommerandClaude Opus 5 f686996122 Doku: ausgelieferter Stand 20261024152057 und die Prüfungen am Server
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 17:39:06 +02:00
Lars Stommer 2c5b5fc2d7 Merge branch 'feature/mandanten-phase4-5' (Phasen 4 und 5)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-24 17:15:31 +02:00
Lars StommerandClaude Opus 5 9cd39f791f Doku: Phasen 1 bis 5 umgesetzt, Grundumbau der Mandantenfähigkeit fertig
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 17:15:30 +02:00
Lars StommerandClaude Opus 5 c55937d20e Phase 4 und 5: Hintergrundläufe je Mandant, Export und Kündigung
**Phase 4 – was im Hintergrund lief, kannte keinen Mandanten.**

`App\Tenancy\TenantRunner` führt jeden Lauf einmal je aktivem Mandanten
aus, mit gesetztem Kontext. Ohne ihn sah der Scheduler bei zwei Mandanten
gar keinen: Abfragen filterten nicht mehr und der Absender fiel auf die
.env zurück – eine Erinnerung des einen Vermieters wäre unter der Adresse
des anderen verschickt worden. Seit gestern gibt es zwei Mandanten; nur
weil der Cronjob auf Strato noch nicht eingerichtet ist, ist das bisher
niemandem passiert.

Betroffen: Vormerkungen, Portal-Abgleich, Portal-Postfach, Überwachung,
Erinnerungen, Bewertungsbitten, Anonymisierung. Die Datenbank-Sicherung
bleibt global – eine Datenbank, ein Dump. Ein Mandant, dessen Lauf
scheitert, hält die anderen nicht auf.

Das Postfach gehört jetzt dem Mandanten (`mailbox_*`, Passwort
verschlüsselt, leerer Server = aus). Es steht im Mandanten-Admin und nur,
wenn der Betreiber den Dienst freigeschaltet hat. Auch die Zustands-
Schlüssel im Cache tragen den Mandanten – sonst meldeten zwei Mandanten
einander ihre letzte erfolgreiche Abholung.

**Phase 5 – Kündigung.**

`App\Tenancy\TenantArchive` mit zwei Befehlen des Betreibers:
`tenants:export <slug>` schreibt alle Zeilen und Dateien in ein Zip,
`tenants:delete <slug>` exportiert erst, fragt nach und löscht dann in
der Reihenfolge, die die Fremdschlüssel erlauben, Medien eingeschlossen.

Konten, die nur zu diesem Mandanten gehörten, gehen mit – ein Konto, das
nirgends mehr hineinkommt, ist personenbezogenes Datum ohne Zweck. Wer
noch für einen anderen Mandanten arbeitet, und der Betreiber, bleiben.
Der Export nennt die Konten mit Rolle, aber ohne Passwort-Hashes und ohne
2FA-Geheimnisse: er wird herausgegeben.

Löschen ist bewusst keine Schaltfläche im Panel.

`TenantSeparationTest` füllt jeden Bereich aus A1 für zwei Mandanten,
exportiert und löscht einen und prüft, dass der andere Zeile für Zeile
unverändert ist – auch die Hosts, die über die Website am Mandanten
hängen und keine eigene tenant_id haben. Dieser Test merkt künftig, wenn
eine neue Tabelle ihre tenant_id vergisst.

262 Feature-Tests grün. Der Export einmal auf echten Daten ausgeführt
(2,3 MB mit Fotos); das Löschen nicht, weil es Dateien aus dem echten
Speicher entfernt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 11:15:55 +02:00
Lars StommerandClaude Opus 5 c2cf632ad5 Doku: Betreiber-Provisionierung, Sperrseite und systemweite Einstellungen
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Dazu ein genauerer Testname: Links tragen die Hauptadresse ihrer Website,
nicht die Adresse, über die der Besucher kam. Das ist der kanonische Host
und war vorher falsch benannt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 10:25:48 +02:00
Lars Stommer f2e78446a8 Merge branch 'feature/betreiber-provisionierung'
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-24 10:20:28 +02:00
Lars StommerandClaude Opus 5 03ad4667ac Betreiber richtet Mandanten vollständig ein: Adressen, Sperrseite, Systemwerte
Ein neu angelegter Mandant war eine Sackgasse. Er bekam keine Website, also
keinen Host, also keine Adresse – und der Host wird im Mandanten-Admin
eingetragen, den er ohne Adresse nicht erreicht. „Im Admin öffnen" half
nicht: ohne Domain landete es beim Mandanten des aktuellen Hosts.

Einsprungsadressen gehören jetzt dem Betreiber, weil Webspace und Hosting
ihm gehören und ein Mandant nicht die Adresse eines anderen auf sich
zeigen lassen darf. Im Mandanten-Formular: Websites mit ihren Adressen.
Beim Anlegen entstehen Website, Host-Einträge und eine leere Startseite –
ohne Startseite antwortet die Website mit 404. Im Mandanten-Admin sind die
Adressen nur noch sichtbar, nicht änderbar. Die Domain beim Hoster auf das
Verzeichnis zu legen bleibt ein Schritt von Hand.

Gesperrter Mandant: statt 404 ein Hinweis mit Status 503, Text je Mandant
einstellbar. 503 hält die Seiten im Suchindex, weil die Sperre vorübergehend
ist.

Behoben: `URL::forceRootUrl(APP_URL)` zwang **alle** Links auf einen festen
Host. Mit einem Mandanten unsichtbar; mit zwei Domains hätte jeder interne
Link der zweiten Website auf die erste gezeigt. Der Ursprung ist jetzt der
Host der aufgelösten Website.

Neu: systemweite Einstellungen sind im Betreiber-Bereich änderbar
(Löschfristen, Bot-Schutz, Flutgrenze, Sicherungen, Portal-Fristen,
Versandweg, SMTP, harte Mail-Umleitung, Tokens). Leer heißt: der Wert der
.env gilt wieder – und zwar sofort, nicht erst beim nächsten Start.
Geheimnisse liegen verschlüsselt. Datenbank-Zugang und APP_KEY bleiben in
der .env, weil sie gebraucht werden, um die Datenbank zu öffnen und das
Gespeicherte zu entschlüsseln.

253 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 10:20:18 +02:00
Lars StommerandClaude Opus 5 d9383cf3e5 Betreiber: Knopf zum Anlegen heißt jetzt "Neuen Mandanten anlegen"
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Die Schaltfläche hieß nur "Erstellen" (Filaments Vorgabe) und war als
Einstieg nicht erkennbar. Dazu ein Test, der den ganzen Weg geht: Liste,
Formular, Anlegen samt Dienste-Freischaltung – und prüft, dass ein neuer
Mandant nichts von dem Mandanten erbt, den der Betreiber gerade ansieht.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:39:41 +02:00
Lars StommerandClaude Opus 5 e0e8c1d856 Doku: Dienste-Steuerung, Host-Verwaltung und der zweite Mandant auf stommer.info
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:33:07 +02:00
Lars Stommer 2f2aceb3bd Merge branch 'feature/mandanten-dienste' (Dienste-Steuerung und Host-Verwaltung)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-24 09:25:23 +02:00
Lars StommerandClaude Opus 5 2e3f2ca938 Mehrere Adressen je Website, damit ein zweiter Mandant niemanden abschaltet
Bisher schrieb das Feld „Domain" genau einen Host nach `site_domains` und
löschte den vorherigen. Solange es einen Mandanten gibt, fällt das nicht
auf: jede Adresse liefert die Standard-Website. Ab dem zweiten Mandanten
bekommt jede nicht eingetragene Adresse 404 – und „www.beispiel.de" ist
eine eigene Adresse. stommer.info hätte einen zweiten Mandanten nicht
überlebt.

Das Formular hat jetzt „Hauptadresse" (steht in Gästelinks) und „Weitere
Adressen". Eingaben werden normalisiert, „https://WWW.Beispiel.de/" wird
zu „www.beispiel.de".

Eine Adresse, die schon zu einer anderen Website gehört, wird abgelehnt.
Ohne diese Sperre könnte ein Mandant die Besucher eines anderen auf seine
eigene Seite ziehen, indem er dessen Adresse einträgt.

242 Feature-Tests grün.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:25:22 +02:00
Lars StommerandClaude Opus 5 fd2a7f7ded Dienste wirklich anschließen: zentrale Steuerung statt folgenloser Schalter
Die Schalter aus Phase 3 schrieben nur in eine Tabelle, die niemand las.
Ein gesperrter Portal-Abgleich lief trotzdem weiter. Das ist behoben.

`App\Tenancy\TenantFeatures` ist die eine Stelle, die beantwortet, ob ein
Mandant einen Dienst hat. Sie wird an allen Wegen abgefragt, die zum Dienst
führen:

- `RolePolicy::allows()` – damit greift die Mandanten-Ebene in *jeder*
  Richtlinie des Admins. Die Rolle sagt, was ein Benutzer darf; der Dienst
  sagt, was der Mandant überhaupt hat. Keine Rolle wiegt einen gesperrten
  Dienst auf.
- `Channel::importsOccupations()` – Import und Scheduler.
- Der öffentliche iCal-Feed antwortet mit 404.
- `ProcessPortalMail` und `channels:fetch-mail` für den Postfach-Schnellweg.

`TenantServiceKey::isWired()` trennt Gebautes von Geplantem. Nur verdrahtete
Dienste erscheinen als Schalter; die drei KI-Dienste stehen als Hinweis da,
bis die Anwendung sie abfragt. Eigene API-Schlüssel sind aus dem Betreiber-
Formular verschwunden – sie gehören in den Admin des Mandanten, wenn es
soweit ist (A16).

Neu im Betreiber-Bereich: Seite „System" mit den Grenzen, die für alle
Mandanten gelten (aus der .env, bewusst nicht änderbar), der Mandantenliste
und dem Zugriffsprotokoll. Bisher war dort nur die Mandantenliste.

Die Migration schaltet jedem vorhandenen Mandanten die Portal-Dienste frei,
damit der Umbau laufenden Betrieb nicht stillschweigend stoppt.

240 Feature-Tests grün, davon fünf neue in `TenantServiceGateTest`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-24 09:14:10 +02:00
Lars StommerandClaude Opus 5 220ec6bfdb Doku: Sicherung, Migrationsstand und Prüfung des Phase-3-Deploys
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:02:29 +02:00
Lars StommerandClaude Opus 5 afffa79289 Doku: Phase 3 ist auf stommer.info; Release-Nummern korrigiert
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Im Stand stand noch `20261023100346`, obwohl danach vier weitere Deploys
liefen (Grundriss, Fotos-Fix). Jetzt steht überall die wirklich aktive
Version `20261023195835` mit Phase 3.

Neu vermerkt: die Bankverbindung ist am Mandanten leer, weil die .env von
stommer.info keine `FEWO_BANK_*`-Werte hat – sie gehört jetzt in
System › Betrieb.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 22:01:53 +02:00
Lars Stommer f143a4f5f4 Merge branch 'feature/mandanten-phase3' (Mandanten Phase 3)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 20:49:47 +02:00
Lars StommerandClaude Opus 5 e6d4d89141 Mandanten Phase 3: Einstellungen, Texte und Dienste gehören dem Mandanten
Vermieterdaten, Bank, Steuerangabe, Adressen, Betriebsart und Fristen sind
Spalten von `tenants`. `App\Tenancy\TenantConfig` legt sie über
`config('fewo.*')` und `mail.from`, sobald der Mandantenkontext wechselt –
so lesen Vorlagen, Mails und der Mietvertrag weiter dieselben Schlüssel und
`resources/themes/**` bleibt unangetastet.

Die `.env` ist die Grundlinie: Rückfall, solange kein Mandant feststeht, und
Grenze für Löschfristen und Bot-Schutz (nur verschärfen, nicht lockern). Die
Flutgrenze bleibt global. Bank, Steuerangabe und eigene Dienst-Schlüssel
liegen verschlüsselt.

Die Seite System › Betrieb schreibt jetzt den Mandanten und enthält
zusätzlich Vermieterdaten, Bank und die Fristen. Tabelle `settings` und
Modell `Setting` entfallen; die Migration übernimmt die bisherigen Werte
aus `settings` und der Konfiguration in den Mandanten Stommer.

Neu: `tenant_services` (Freischaltung je Dienst mit optionalem eigenem
API-Schlüssel, nur im Betreiber-Bereich schaltbar) und `service_usages`.
Es zählt noch nichts, weil kein Dienst aufruft.

235 Feature-Tests grün. Der Umbauweg wurde zusätzlich auf einer Kopie der
lokalen Datenbank durchgespielt.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-23 20:49:22 +02:00
LarsandClaude Opus 5.5 12e4079126 Docs: photo storage fix (admin uploads were private) in BETRIEB §8 and STATUS
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 20:17:18 +02:00
LarsandClaude Opus 5.5 1871c04507 Fix: photos uploaded in the admin were stored privately and did not show on the website
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
The admin upload field used Filament's default disk (FILESYSTEM_DISK=local, private), while imports
and the website use the public disk – a photo uploaded in the admin appeared in the photo list but
its web sizes returned 403 (e.g. as floor plan picture). The photo collection and the upload field
now always use the public disk; a data migration moves photos already stored privately (original and
web sizes, folder = media id) to the public disk. Tests for the upload and the migration.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 17:12:32 +02:00
LarsandClaude Opus 5.5 dfd3f77a5d Floor plan editor: move corners by drag or arrow keys, insert on edges, delete by double click
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Corners stay editable after drawing: drag a corner (mouse or touch), focus it and nudge with the arrow
keys (Shift for larger steps), '+' on an edge inserts a corner in its middle, double click or Delete
removes one. Tested in a browser harness with the real field markup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 16:47:55 +02:00
LarsandClaude Opus 5.5 f7cbc66451 Section "Grundriss (interaktiv)": floor plan with rooms, admin editor, Seebad view
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
- Table floor_plans (tenant_id, one per apartment, picture = website photo, rooms as JSON with
  corners in percent of the picture), model FloorPlan with BelongsToTenant, Property::floorPlan()
- Admin › Webseite › Grundriss: room list with name, description, photos, equipment (from the
  equipment list), accessibility hint, visibility, and an area editor (click the corners on the picture)
- Section floor_plan: base view without JavaScript (areas jump to the room list), Seebad view with
  room buttons, highlighted area and a cartouche per room (theme.js initFloorPlans)
- Tests: tenant inheritance, point parsing, website output, admin create incl. validation; the
  render test for all themes now includes the floor plan
- Docs: THEMES §5, ZUSAMMENARBEIT §6, STATUS §6 (incl. note for tenancy phase 5)
- styles/grundriss: revised rendering, WebP renditions, room areas of the Stommer flat in percent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:26:02 +02:00
LarsandClaude Opus 5.5 04b5189bd8 Floor plan: rendering (source + WebP 900/1712) and room areas in image coordinates
Seven rooms incl. entrance; the areas use the image's own coordinate system (viewBox 0 0 1712 919),
so an SVG overlay scales exactly with the image. A traced vector version was tested and rejected
(2.7 MB, posterised).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 15:11:17 +02:00
LarsandClaude Opus 5.5 9b8a851ce9 Floor plan in a light 3D view (cutaway): SVG, generator and projected room areas
Generated from the plan coordinates of the scanned floor plan (photo 20); the JSON holds the room
polygons in the same projection for the interactive section. Draft for the planned section
'Interaktiver Grundriss' (STATUS §6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:52:06 +02:00
Lars b3114cdfe3 Merge remote-tracking branch 'origin/main' into theme/seebad
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 12:33:33 +02:00
LarsandCursor faf2133232 Record that the staging admin works after the tenancy deploy.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:33:26 +02:00
LarsandClaude Opus 5.5 d2f53ceb84 Theme Seebad 0.4.0: menu panels; fix missing chevron icons; render test for all themes
- Menu panels: arrow next to each main menu item opens a panel with the page description (SEO text),
  jump links to the headed sections and a cartouche with booking and phone; Escape/outside click closes,
  focus returns; without JavaScript the menu stays plain links
- Header: booking button hidden between 1280 and 1535 px (too narrow with the arrows), desktop phone removed
- Fix: offers carousel and menu used outline chevron icons that do not exist (500 as soon as offers are shown);
  now mini chevrons
- New test: every installed theme renders all pages with reviews and offers in every display mode
- Wish: menu photo per page (ZUSAMMENARBEIT §5)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 12:33:11 +02:00
LarsandCursor ab1dffc72f Record the tenancy handoff so the next session can start at phase 3.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
STATUS section 7 names the deployed release, the pieces that are built, and what must stay untouched.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:26:29 +02:00
LarsandCursor fc61369c4a Record that stommer.info now runs as the Stommer landlord.
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:05:57 +02:00
Lars cec49da1be Merge branch 'feature/mandanten' 2026-10-23 12:00:22 +02:00
LarsandCursor 8ebc1a3878 Assign the existing site to one landlord so stommer.info can run tenancy.
Seebad 0.3 stays in this release. With a single landlord every host still reaches the default website.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:00:11 +02:00
LarsandClaude Opus 5.5 d9e52c4789 Status: design theme section (open points, plan for new sections)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:08:03 +02:00
Lars 3621f7e924 Merge branch 'theme/seebad' (Seebad 0.3.0: all sections)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 10:02:11 +02:00
LarsandClaude Opus 5.5 6930d3ab0f Theme Seebad 0.3.0: own gallery, offers, reviews, FAQ, contact, booking and rich text
- All 15 sections now in Seebad style: offers and contact framed with terrace-brace brackets,
  reviews with large average and serif quotes, FAQ with large toggles, gallery with captions on focus
- Booking page offers the phone number ("Lieber persönlich?")

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:01:58 +02:00
Lars c215da0590 Merge branch 'theme/seebad' (Seebad 0.2.0: logo, Bäderstil details)
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
2026-10-23 09:53:16 +02:00
LarsandClaude Opus 5.5 e49f160496 Theme Seebad 0.2.0: logo from satz4 and Bäderstil details of the house
- Logo (satz4) traced to SVG masters (styles/satz4/svg: full logo, picture mark, wordmark) with a palette
  sampled from the original; WebP renditions for the website; favicon/apple touch icon = simplified corner bay
- House details as theme elements: arched dormer (crest of the cartouche), hero arch with window surround and
  keystone, terrace braces as corner brackets (search box, cartouche), balcony railing on the dark band
- Colours from the logo (navy, roof terracotta as accent, wave blues, sun)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 09:52:57 +02:00
Lars bc2b175556 Merge branch 'theme/seebad' (Seebad 0.1.1)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
2026-10-23 08:39:22 +02:00
LarsandClaude Opus 5.5 5416b37dfc Theme Seebad 0.1.1: header no longer overlaps, readable amenities and prices
- Header: full menu from 1280 px, menu button below; site name never shrinks into the menu
- Hero: photo and text side by side from 1024 px
- Own amenities (serif area headings, check marks) and prices (extras as list, larger table, mobile layout)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:39:12 +02:00
Lars StommerandClaude Opus 5.5 30e9aa7b26 Git auto-sync script (fast-forward only), lockfile resynced so npm ci works again
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:32:32 +02:00
Lars 4951f227f1 Merge branch 'theme/seebad' (Theme Seebad, first version)
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
2026-10-23 08:25:20 +02:00
LarsandClaude Opus 5.5 a9ad4dbf0b Theme Seebad: first version of design direction A
- New child theme "seebad": Newsreader + Atkinson Hyperlegible Next (self-hosted), larger base size,
  tokens chalk white / ink blue / brick / evening blue
- Picture world "Ostsee" as inline SVG slots (partials/motif): villa mark, wave bands, shell, gulls, vignettes
- Own layout, header (mobile menu as dark panel with call button), footer, banner, mobile booking bar
- Sections: hero with arch photo and search box, facts, text_image, location, host, cta in cartouche
- Wishes to the application recorded in ZUSAMMENARBEIT.md §5

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:22:23 +02:00
LarsandClaude Opus 5.5 e276cd0548 Design concept, multi-tenancy requirements, graphic set 3 (originals + hand-drawn SVGs)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
- docs/DESIGN-KONZEPT.md: target group couples, three design directions, configurator extensions
- docs/MANDANTEN-ANFORDERUNGEN.md: requirements for tenants (SaaS landlord websites), roles per tenant
- styles/satz3: AI-generated originals and clean SVG redraws (villa mark, vignettes, bands, ornaments)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 08:07:20 +02:00
Lars StommerandClaude Opus 5.5 0c98d82cf2 Addresses of the internal communication in the admin (notification recipients, contact/reply-to, sender)
Deploy / test (push) Failing after 2s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:14:25 +02:00
Lars StommerandClaude Opus 5.5 749537342e Status: switch contact address to info@fewo-stommer.de at go-live
Deploy / test (push) Failing after 3s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:09:12 +02:00
Lars StommerandClaude Opus 5.5 b681327d3a Sender address info@fewo-stommer.de (SMTP login with that mailbox)
Deploy / test (push) Failing after 11s
Deploy / deploy (push) Skipped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:01:23 +02:00
Lars StommerandClaude Opus 5.5 bde99657cf mail:test: clear message for the log mailer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:04:58 +02:00
Lars StommerandClaude Opus 5.5 d018c97be4 Operating mode in the admin (test mode sends all mail to a test recipient until switched live), bot protection for booking requests, mail rendering tests, mail:test command
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 23:01:44 +02:00
Lars StommerandClaude Opus 5.5 fdcb68d578 Documentation: project README, status, rules for parallel sessions (theme branch), updated operations/concept/theme guide
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:50:35 +02:00
Lars StommerandClaude Opus 5.5 70a8c5072b Minimum stay exceptions (gap filled, ends on changeover day, offers, absolute minimum); copy seasons aligned to a weekday
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:38:27 +02:00
Lars StommerandClaude Opus 5.5 20235b9139 Front controller: remove the internal release prefix Strato puts into REQUEST_URI (signed links)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:28:43 +02:00
Lars StommerandClaude Opus 5.5 565eee4325 Fix signed links behind the Strato release rewrite (base URL), mail redirect for test environments
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:24:31 +02:00
Lars StommerandClaude Opus 5.5 fd744edf8c Prices & offers page (seasons, special offers/promo codes, extras) and photos in the simple admin mode
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 22:19:08 +02:00
Lars StommerandClaude Opus 5.5 7a6ee316cd Admin: show the offer link (e.g. to share it, or on staging where mails go to the log)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:46:34 +02:00
Lars StommerandClaude Opus 5.5 6690beafe6 Strip photo metadata with GD (Imagick keeps EXIF), --force option, stricter test
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:43:54 +02:00
Lars StommerandClaude Opus 5.5 4f69b426a4 Booking path 1 (offer + guest acceptance), 2FA for all, privacy hardening, brand graphics in theme
- Offer workflow: "Angebot senden" in the admin (dates, guests, promo code, manual price adjustment,
  validity from the property's hold time, message, guest data for the contract) with live price;
  contract draft PDF; signed, versioned offer page for the guest to accept (acceptance record without
  IP) or decline; expiry job, landlord notifications, editable offer texts, wording on the website.
- 2FA is mandatory for every admin account.
- Privacy: complete anonymisation (notes, attribution, review names, offer messages), shorter
  periods for unbinding requests, portal mail excerpts and attribution (configurable proposals),
  iCal summary not stored, known e-mail no longer overwrites guest data, security headers, bearer
  tokens for automations, metadata stripped from photo originals, review link throttled.
- Daily database backup (backup:database) and scripts/backup-pull.sh for the NAS.
- Theme: brand mark in header/footer, favicon/touch icon, wave divider, icons, illustration as
  image placeholder; navy follows the text colour for dark appearances.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:38:22 +02:00
Lars StommerandClaude Opus 5.5 82698f8eda Admin accounts with simple/expert mode, blocked periods list, brand assets, decisions
- Per-user admin mode (simple: bookings/contracts, blocked periods, guests, portal tasks,
  reviews; expert: everything the role allows), user menu switch, FollowsAdminMode on all
  resources/pages (guarded by a test); roles keep deciding permissions.
- Users list shows mode and 2FA; admins can reset another user's 2FA.
- New "Sperrzeiten" list for all apartments (manual blocks editable, portal blocks read-only).
- styles/final: clean hand-built SVG mark, logo, favicon (dark-mode aware), 4 icons, wave
  divider, plus PNG/WebP for mail/PDF/touch icon; colours via --brand-* variables.
- Decisions recorded in KONZEPT §6a/6b (booking path 1 via offer + guest acceptance, direct
  booking later; tourist tax by Ferienservice Balu); agent documents added and marked as
  analysis with assumptions; styles excluded from the deploy package.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 21:08:09 +02:00
Lars StommerandClaude Opus 5.5 7d0bc93abc Offers by their own rules, seasonal photos per section, theme authoring tooling
- Special offers: kinds (rule, fixed dates, gap filler), package price, priority, highlight;
  GapFinder detects calendar gaps (optionally waiving the minimum stay); OfferShowcase decides
  what the website advertises and prices fixed dates/gaps with PriceCalculator; offers section
  shows them side by side, as a list or rotating; hero can show the top offer. Appearances no
  longer carry a featured offer.
- Sections get stable ids; appearances set photos per section ("Bilder je Baustein") and
  sections can be limited to appearances. Photo pickers show thumbnails everywhere.
- Themes: themes:make (scaffold, never overwrites), themes:check (contract, build, markup,
  colours, external resources, WCAG contrast), themes:preview (signed links per page and
  appearance), signed ?theme= preview and preview action in the site form, inherited colour
  tokens in the admin. Base CSS split into theme.css + reusable theme-base.css.
- docs/THEME-ERSTELLUNG.md: binding guide for building additional themes elsewhere.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 18:51:38 +02:00
Lars StommerandClaude Opus 5.5 bc77b64ea7 Photo import from a manifest (category + alt text per file, idempotent); curated list of the WordPress photos
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:23:40 +02:00
Lars StommerandClaude Opus 5.5 7355466231 Deploy: keep only the active release on Strato (file quota), release history as Git tags in Gitea
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:16:32 +02:00
Lars StommerandClaude Opus 5.5 669fb45731 Deploy: prune vendor translations/tests/docs to stay within Strato's file quota
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:06:04 +02:00
Lars StommerandClaude Opus 5.5 33dde2027b Docs: webspace quota note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 17:01:29 +02:00
Lars StommerandClaude Opus 5.5 13760f2c02 Admin two-factor authentication (mandatory for admins), users:create command, operations handbook
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:52:44 +02:00
Lars StommerandClaude Opus 5.5 dea1029225 Docs: wording
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:43:49 +02:00
Lars StommerandClaude Opus 5.5 b544adac62 Docs: staging on stommer.info, OPcache-safe release switching
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:43:37 +02:00
Lars StommerandClaude Opus 5.5 83427aec13 Deploy: fix escaped dot in .htaccess block rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:41:10 +02:00
Lars StommerandClaude Opus 5.5 fbfc9eeb95 Deploy: serve the web from the concrete release folder to avoid stale OPcache via the current symlink
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:38:13 +02:00
Lars StommerandClaude Opus 5.5 f031b3c854 Pin URL root to APP_URL outside local/testing (base-folder hosting on Strato)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:32:40 +02:00
Lars StommerandClaude Opus 5.5 92c796de2e Deployment: .htaccess-Weiterleitung für Strato (kein Symlink-Ziel), Web-PHP pro Ordner, erstes Deployment ohne Gesundheitscheck
Erfolgreich getestet auf Strato (test.fewo-stommer.de).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:22:27 +02:00
Lars StommerandClaude Opus 5.5 cb1e4cbc63 Theme: noindex außerhalb der Produktion (Testbetrieb nicht in Suchmaschinen)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 16:05:22 +02:00
Lars StommerandClaude Opus 5.5 769e6b7e6e Deployment: paketspezifischer Strato-SSH-Server, Tilde im Schlüsselpfad
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:57:25 +02:00
Lars StommerandClaude Opus 5.5 c7186e768e MariaDB 11.8 als Zieldatenbank (Vorlage, Doku) und zusätzlicher CI-Testlauf gegen MariaDB
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:40:48 +02:00
Lars StommerandClaude Opus 5.5 a6adab64bb Deployment-Doku (Strato-Einrichtung, SSH vs. SFTP, Gitea Actions)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:32:40 +02:00
Lars StommerandClaude Opus 5.5 8d904660b9 Automatisches Deployment nach Strato (atomare Releases, Rollback, Gitea Actions)
- scripts/deploy.sh: Build aus Git-Stand (Composer ohne Dev, Vite), Upload per SSH, Migration, Caches, atomarer Umschalter current -> releases/<zeit>, Gesundheitscheck mit automatischem Rollback; Befehle setup/deploy/rollback/releases/artisan; lokaler Testmodus
- .gitea/workflows/deploy.yml: Tests bei jedem Push, Deployment bei Tags v* oder per Knopfdruck
- Vorlagen scripts/deploy.example.env und .env.production.example (Strato MySQL, SMTP, IMAP)
- Scheduler-Endpunkt /automation/scheduler als Ausweich für fehlende Cronjobs
- ProductionSeeder für die Ersteinrichtung ohne Testdaten

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:28:00 +02:00
Lars StommerandClaude Opus 5.5 66e82d61f5 Theme-System mit Basis-Theme Ostsee-Licht, Bausteinen und saisonalen Erscheinungsbildern
- Sites (Domain, Theme, Farben; mehrfähig für weitere Vermieter), Seiten aus Bausteinen mit Menüs, Erscheinungsbilder mit jährlichem Zeitplan, Priorität und signierter Vorschau
- Theme-Kern (app/Themes): Manifest, Registry, Vererbung (Child-Themes), Token-Farben als CSS-Variablen, Bausteinkatalog als Registry (config/themes.php)
- 15 Bausteine: Titelbereich mit Suche, Eckdaten, Text mit Bildern, Galerie, Ausstattung, Lage, Preise, Angebote, Kalender & Anfrage, Bewertungen, Gastgeber, FAQ, Abschluss, Kontakt, Fließtext
- Theme Ostsee-Licht: Layout, Kopf/Fuß, Banner, mobile Buchungsleiste, Lightbox, selbst gehostete Schriften, Reduced Motion
- Seiten Start, Wohnung, Kühlungsborn, Preise & Buchung, Kontakt, Impressum, Datenschutz; Sitemap, robots.txt, JSON-LD
- Admin: Seiten-Baukasten, Erscheinungsbilder, Websites
- Dokumentation docs/THEMES.md inkl. Übergabe für die Design-Sitzung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 15:04:21 +02:00
Lars StommerandClaude Opus 5.5 f2c48013ad Konzept: Entscheidungen zum Theme- und Vorlagensystem
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 14:25:41 +02:00
Lars StommerandClaude Opus 5.5 99e0ba4040 Dashboard: Kennzahlen und nächste Aufenthalte
- Offene Anfragen, Anreisen 14 Tage, offene/überfällige Zahlungen, Auslastung, Portal-Status
- Tabelle der Aufenthalte der nächsten 30 Tage mit offenen Beträgen und Anreiseinfo-Status
- Nur für Rollen Administrator und Vermietung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:31:05 +02:00
Lars StommerandClaude Opus 5.5 0bf302fcf9 Phase 3: Zahlungen, Mietvertrag, Erinnerungen, Anreiseinformationen
- Zahlungen erfassen (inkl. Erstattungen), Status automatisch: Bestätigt → Anzahlung erhalten → Bezahlt → Abgeschlossen
- Anzahlungsfrist bei Bestätigung; kurzfristige Buchungen: Gesamtbetrag sofort
- Mietvertrag als PDF (dompdf, Font-Subsetting), bei Bestätigung gespeichert und angehängt; Texte im Admin (Muster)
- Täglich: Zahlungserinnerungen (Anzahlung/Rest überfällig, Kopie an Vermieter), Zahlungsaufforderung Rest 7 Tage vorher, Anreiseinfos 7 Tage vorher, Abschluss nach Abreise
- Admin: Zahlungen je Buchung, offene Beträge, Vertrag herunterladen/neu erzeugen

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 13:29:41 +02:00
Lars StommerandClaude Opus 5.5 e5f9e0762f Schnellerkennung von Portalbuchungen per E-Mail
- IMAP-Abruf jede Minute (webklex/php-imap, ohne PHP-imap-Erweiterung) oder signierter Push von n8n
- Parser für Buchungs-, Storno- und Anfrage-Mails (de/en), Buchungsnummer, An-/Abreise
- Erkannte Buchungen werden sofort gesperrt und an handgepflegte Portale weitergegeben; Kalender-Abgleich übernimmt bzw. ersetzt Mail-Sperren
- Unklare Mails: Prüf-Mail + Admin-Liste Portal-E-Mails mit Aktion Sperre anlegen
- Überwachung des Postfachs in Monitor und /health/sync

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:29:26 +02:00
Lars StommerandClaude Opus 5.5 0b7205e050 Portal-Synchronisation: unser System führt
- Connector-System (app/Channels, config/channels.php) mit iCal-Connector, robustem Parser und Export-Feed je Portal (ohne eigene Belegungen, ohne Gästedaten)
- Abgleich alle 5 Min. mit Protokoll, Echo-Erkennung, Konflikt-Mail bei möglicher Doppelbuchung
- Überwachung: Störungs-Mail, Status-Endpunkt /health/sync für n8n
- Portal-Aufgaben für Sofortbuchungsportale (FeWo-direkt): automatisch aus Buchungen/Sperren/anderen Portalen, Mail + Erinnerung, Abhaken im Admin
- Optionaler signierter Automatisierungs-Webhook mit Rückmeldung
- Herkunftsmessung: Abfrage im Formular + UTM-Parameter
- Portal-Analyse: AGB-Prüfung Automatisierung, Umsetzungsbeschreibung

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:13:55 +02:00
Lars StommerandClaude Opus 5.5 a8e72715ab Portal-Analyse: Channel-Manager-Bewertung, Eigenbau, Sofortbuchungsrisiko
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 11:01:33 +02:00
Lars StommerandClaude Opus 5.5 02acda8602 Portal-Analyse: Kalender-Abgleich, Buchungshoheit, Empfehlung
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-22 10:52:27 +02:00
740 changed files with 42907 additions and 945 deletions

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
{
"permissions": {
"allow": [
"Bash(git merge *)"
]
}
}
+11
View File
@@ -73,3 +73,14 @@ FEWO_BANK_BIC=
FEWO_BANK_NAME=
FEWO_REVIEW_REQUEST_AFTER_DAYS=2
FEWO_GUEST_RETENTION_YEARS=10
FEWO_CHANNEL_STALE_AFTER_MINUTES=60
FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120
FEWO_HEALTH_TOKEN=
FEWO_AUTOMATION_WEBHOOK_URL=
FEWO_AUTOMATION_SECRET=
FEWO_MAILBOX_HOST=
FEWO_MAILBOX_PORT=993
FEWO_MAILBOX_ENCRYPTION=ssl
FEWO_MAILBOX_USERNAME=
FEWO_MAILBOX_PASSWORD=
FEWO_MAILBOX_FOLDER=INBOX
+65
View File
@@ -0,0 +1,65 @@
# Production settings – copy to <DEPLOY_PATH>/shared/.env on the server and fill in.
# Generate APP_KEY locally once: php artisan key:generate --show
APP_NAME="Ferienwohnung Stommer"
APP_ENV=production
APP_KEY=
APP_DEBUG=false
APP_URL=https://www.fewo-stommer.de
APP_TIMEZONE=Europe/Berlin
APP_LOCALE=de
APP_FALLBACK_LOCALE=de
APP_FAKER_LOCALE=de_DE
APP_MAINTENANCE_DRIVER=file
LOG_CHANNEL=daily
LOG_LEVEL=warning
# Strato MariaDB 11.8 (Kundenlogin › Datenbanken und Webspace › Datenbanken verwalten)
DB_CONNECTION=mariadb
DB_HOST=
DB_PORT=3306
DB_DATABASE=
DB_USERNAME=
DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_SECURE_COOKIE=true
CACHE_STORE=database
QUEUE_CONNECTION=sync
FILESYSTEM_DISK=local
# Strato mailbox fewo@stommer.de
MAIL_MAILER=smtp
MAIL_HOST=smtp.strato.de
MAIL_PORT=465
MAIL_SCHEME=smtps
MAIL_USERNAME=info@fewo-stommer.de
MAIL_PASSWORD=
MAIL_FROM_ADDRESS="info@fewo-stommer.de"
MAIL_FROM_NAME="${APP_NAME}"
FEWO_OWNER_NAME="Brigitte Stommer"
FEWO_OWNER_EMAIL=fewo@stommer.de
FEWO_NOTIFICATION_EMAIL=fewo@stommer.de
# Harte Umleitung aller E-Mails (gilt immer). Normal leer lassen – Testbetrieb/Scharfschalten: Admin › System › Betrieb
FEWO_MAIL_REDIRECT_TO=
FEWO_BANK_ACCOUNT_HOLDER=
FEWO_BANK_IBAN=
FEWO_BANK_BIC=
FEWO_BANK_NAME=
# Portal booking e-mails (fast path)
FEWO_MAILBOX_HOST=imap.strato.de
FEWO_MAILBOX_PORT=993
FEWO_MAILBOX_ENCRYPTION=ssl
FEWO_MAILBOX_USERNAME=fewo@stommer.de
FEWO_MAILBOX_PASSWORD=
FEWO_MAILBOX_FOLDER=INBOX
# Monitoring / automation (long random values, e.g. php -r "echo bin2hex(random_bytes(24));")
FEWO_HEALTH_TOKEN=
FEWO_SCHEDULER_TOKEN=
FEWO_AUTOMATION_SECRET=
FEWO_AUTOMATION_WEBHOOK_URL=
+63
View File
@@ -0,0 +1,63 @@
name: Deploy FeWo mit PipelineManager
on:
push:
branches: [develop, main]
workflow_dispatch:
jobs:
deploy:
# Raspi5-Paperless: existing host runner; all PHP/Node work happens inside the image.
runs-on: ubuntu-latest
env:
PIPELINE_IMAGE: pipeline-manager:0.1.1
PIPELINE_HOME: /home/lars/docker/pipeline-manager
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Anwendung im Manager-Container vorbereiten und testen
id: build
run: |
set -eu
case "$GITHUB_REF" in
refs/heads/develop) TARGET=staging ;;
refs/heads/main) TARGET=production ;;
*) echo 'Unzulässiger Branch'; exit 1 ;;
esac
docker image inspect "$PIPELINE_IMAGE" >/dev/null
STATUS=0
docker run --rm --user "$(id -u):$(id -g)" \
-v "$(pwd -P):/workspace:ro" "$PIPELINE_IMAGE" \
pipeline-manager check --environment "$TARGET" || STATUS=$?
if [ "$STATUS" = 3 ]; then
echo 'enabled=false' >> "$GITHUB_OUTPUT"
exit 0
fi
test "$STATUS" = 0
umask 077
mkdir -p "$PIPELINE_HOME/cache/composer" "$PIPELINE_HOME/cache/npm" "$PIPELINE_HOME/backups" .pipeline
docker run --rm --user "$(id -u):$(id -g)" --cpus=2 --memory=2g --pids-limit=512 \
-e HOME=/tmp \
-v "$(pwd -P):/workspace" \
-v "$PIPELINE_HOME/cache:/cache" "$PIPELINE_IMAGE" \
pipeline-manager prepare
echo "target=$TARGET" >> "$GITHUB_OUTPUT"
echo 'enabled=true' >> "$GITHUB_OUTPUT"
- name: Sichern und nach Strato übertragen
if: steps.build.outputs.enabled == 'true'
env:
TARGET: ${{ steps.build.outputs.target }}
DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }}
DEPLOY_USER: ${{ secrets.DEPLOY_USER }}
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
run: |
set -eu
docker run --rm --user "$(id -u):$(id -g)" --cpus=1 --memory=512m --pids-limit=128 \
-e GITHUB_REF -e GITHUB_SHA -e DEPLOY_HOST -e DEPLOY_USER -e DEPLOY_SSH_KEY -e DEPLOY_KNOWN_HOSTS \
-v /etc/passwd:/etc/passwd:ro \
-v "$(pwd -P):/workspace:ro" \
-v "$PIPELINE_HOME/backups:/backups" "$PIPELINE_IMAGE" \
pipeline-manager deploy --environment "$TARGET" --backup-root /backups
+6
View File
@@ -24,7 +24,13 @@
/storage/*.key
/storage/pail
/vendor
/.pipeline/
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
# Deployment settings with access data
/scripts/deploy.*.env
!/scripts/deploy.example.env
storage/app/private/exports/
+11 -4
View File
@@ -1,8 +1,8 @@
# Ferienwohnung Stommer
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`.
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches and file ownership; `develop` deploys staging, a merge from `develop` to `main` deploys production once enabled).
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally.
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – CI builds assets in the versioned PipelineManager image on the Pi, independently of the development machine.
- UI and all user-facing texts are German; code, identifiers and PHPDoc are English.
- Money is stored as integer euro cents; edit via `App\Filament\Forms\Components\EuroInput`, display via `->money('EUR', divideBy: 100, locale: 'de')`.
- Season periods are half-open: a night belongs to a season when `starts_on <= night < ends_on`.
@@ -10,10 +10,17 @@ # Ferienwohnung Stommer
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- Deployment: `.gitea/workflows/deploy.yml` runs the separate PipelineManager image using this project's `pipeline.toml`: push `develop` -> staging; merge commit `develop` -> `main` -> production, currently disabled. Manager source and agent instructions: `C:\dev\pipelinemanager`, https://gitea.stommer.de/Lars/PipelineManager. No permanent API service or new container image per application deployment; the runner starts containers from an existing released image. Secrets stay in Gitea Secrets. Strato retains only the active release; the workflow commit and server `REVISION` identify deployments. Legacy maintenance fallback: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (its manual deploy creates Git tags). Read docs/DEPLOYMENT.md before use. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Internal addresses are admin settings too: send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly); contact/reply-to (`fewo.owner.email`) and sender (`mail.from`) are overridden at boot by `Settings::applyAddressOverrides()`. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`; development/integration branch `develop`, production branch `main`.
<laravel-boost-guidelines>
=== foundation rules ===
+9 -2
View File
@@ -1,6 +1,6 @@
# Ferienwohnung Stommer
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`.
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches, file ownership, deploy only from an up-to-date `main`).
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally.
- UI and all user-facing texts are German; code, identifiers and PHPDoc are English.
@@ -10,7 +10,14 @@ # Ferienwohnung Stommer
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
+27 -48
View File
@@ -1,58 +1,37 @@
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
# Ferienwohnung Stommer – Webseite und Vermietungsverwaltung
<p align="center">
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
</p>
Webseite mit Buchungsanfrage und eine Verwaltung (Admin) für die Ferienwohnung Stommer, Strandstraße 15, 18225 Kühlungsborn. Ersetzt die bisherige WordPress-Seite www.fewo-stommer.de. Laravel 13, Filament 5, Livewire 4, Tailwind 4; Hosting bei Strato (Shared Webhosting, Hosting Pro).
## About Laravel
**Testbetrieb:** https://stommer.info · Verwaltung: https://stommer.info/admin (Konto + Zwei-Faktor-Anmeldung, siehe docs/BETRIEB.md §7)
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
## Wo steht was?
- [Simple, fast routing engine](https://laravel.com/docs/routing).
- [Powerful dependency injection container](https://laravel.com/docs/container).
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
- [Robust background job processing](https://laravel.com/docs/queues).
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
| Dokument | Inhalt |
|---|---|
| [docs/STATUS.md](docs/STATUS.md) | **Aktueller Stand**: was fertig ist, was offen ist, nächste Schritte – hier anfangen |
| [docs/ZUSAMMENARBEIT.md](docs/ZUSAMMENARBEIT.md) | Regeln für parallele Arbeit (z. B. Theme-Entwicklung auf einem anderen Rechner) – Branches, Dateibereiche, Ausliefern |
| [docs/KONZEPT.md](docs/KONZEPT.md) | Fachliches Konzept und alle Entscheidungen (Buchungswege §6a, Festlegungen §6b) |
| [docs/BETRIEB.md](docs/BETRIEB.md) | Server, Zugänge, Konfiguration, Konten/2FA, Backups, Löschfristen, bekannte Eigenheiten |
| [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | Auslieferung auf Strato (Skript, Versionen, Gitea Actions) |
| [docs/THEMES.md](docs/THEMES.md) | Theme-System: Architektur, Bausteine und ihre Daten (Vorlagen-Vertrag) |
| [docs/THEME-ERSTELLUNG.md](docs/THEME-ERSTELLUNG.md) | **Verbindliche Anleitung für ein neues Theme** (Design-Sitzung) |
| [docs/PORTALE.md](docs/PORTALE.md) | Buchungsportale, Kalenderabgleich, Portal-E-Mails |
| [styles/README.md](styles/README.md) | Markenelemente (Logo, Favicon, Symbole, Wellenband) |
| docs/DATENSCHUTZ-*, GAP-DELTA, GO-LIVE-CHECKLISTE, LOESCHKONZEPT, BUCHUNGSPROZESS, DATENMODELL-KONZEPT | Analyse eines Datenschutz-Agenten (Annahmen markiert; maßgeblich ist KONZEPT.md) |
| [CLAUDE.md](CLAUDE.md) / [AGENTS.md](AGENTS.md) | Technische Leitplanken für KI-Assistenten (identisch) |
Laravel is accessible, powerful, and provides tools required for large, robust applications.
## Learning Laravel
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
In addition, [Laracasts](https://laracasts.com) contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
You can also watch bite-sized lessons with real-world projects on [Laravel Learn](https://laravel.com/learn), where you will be guided through building a Laravel application from scratch while learning PHP fundamentals.
## Agentic Development
Laravel's predictable structure and conventions make it ideal for AI coding agents like Claude Code, Cursor, and GitHub Copilot. Install [Laravel Boost](https://laravel.com/docs/ai) to supercharge your AI workflow:
## Lokal starten
```bash
composer require laravel/boost --dev
php artisan boost:install
composer install && npm ci
cp .env.example .env && php artisan key:generate
touch database/database.sqlite # PowerShell: New-Item database/database.sqlite
php artisan migrate:fresh --seed # Testdaten: Wohnung, Preise 2026, Seiten, Erscheinungsbilder
npm run build # oder npm run dev
php artisan serve # http://localhost:8000 · /admin: admin@example.com / password (2FA beim ersten Login)
php artisan test --compact # alle Tests müssen grün sein
```
Boost provides your agent 15+ tools and skills that help agents build Laravel applications while following best practices.
## Ausliefern
## Contributing
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
## Code of Conduct
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
## Security Vulnerabilities
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
## License
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
`bash scripts/deploy.sh staging deploy` – baut den **letzten Commit** und spielt ihn auf stommer.info (Details und Regeln: docs/DEPLOYMENT.md, docs/ZUSAMMENARBEIT.md).
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\OfferAnswered;
use App\Models\Booking;
use App\Support\Content;
use App\Support\Settings;
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).
*/
class AcceptOffer
{
public function __construct(private ConfirmBooking $confirm) {}
/**
* @throws ReservationException
*/
public function handle(Booking $booking, int $offerVersion): void
{
$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);
try {
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
} catch (Throwable $exception) {
report($exception);
}
}
/**
* @throws ReservationException
*/
public function ensureAcceptable(Booking $booking, int $offerVersion): void
{
if ($offerVersion !== $booking->offer_version) {
throw ReservationException::offerOutdated();
}
if ($booking->status !== BookingStatus::OfferSent) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'angenommen');
}
if (! $booking->hold_expires_at?->isFuture()) {
throw ReservationException::offerExpired();
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Actions;
use App\Channels\ChannelSyncException;
use App\Channels\ICal\ICalAnalysis;
use App\Channels\ICal\ICalConnector;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
class AnalyzeChannelCalendar
{
public function handle(Channel $channel): Channel
{
if ($channel->connector !== 'ical' || blank($channel->setting('import_url')) || ! $channel->servesItsLandlord()) {
throw new ChannelSyncException('Für die Analyse eine iCal-Importadresse hinterlegen und den Kalenderdienst freischalten.');
}
$url = $channel->setting('import_url');
$analysis = app(ICalAnalysis::class)->summarize(app(ICalConnector::class)->fetchDocument($channel));
return DB::transaction(function () use ($channel, $url, $analysis): Channel {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
if ($locked->setting('import_url') !== $url) {
throw new ChannelSyncException('Die Importadresse wurde während der Analyse geändert. Bitte erneut analysieren.');
}
$locked->forceFill(['ical_analysis' => $analysis, 'ical_analyzed_at' => now()])->save();
return $locked;
});
}
}
+34 -3
View File
@@ -2,10 +2,15 @@
namespace App\Actions;
use App\Models\Booking;
use App\Models\Guest;
use App\Models\PortalEmail;
/**
* Anonymises guests whose last stay ended longer ago than the retention period (GDPR storage limitation).
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
* guests who only ever sent requests/offers that never became binding (shorter period), and removes
* operational extras that are no longer needed (portal e-mail excerpts, marketing attribution).
* Booking records (dates, prices, payments) stay as accounting documents.
*/
class AnonymizeGuests
{
@@ -17,10 +22,36 @@ public function handle(): int
->whereNull('anonymized_at')
->whereDate('created_at', '<', $cutoff)
->whereDoesntHave('bookings', fn ($query) => $query->whereDate('departure', '>=', $cutoff))
->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed()->whereDate('ends_on', '>=', $cutoff))
->get();
$guests->each->anonymize();
$inquiryCutoff = now()->subMonths(config('fewo.retention.inquiry_months'));
$inquiriesOnly = Guest::query()
->whereNull('anonymized_at')
->whereDoesntHave('bookings', fn ($query) => $query->whereNotNull('confirmed_at'))
->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed())
->whereDoesntHave('bookings', fn ($query) => $query->where('updated_at', '>=', $inquiryCutoff))
->where('updated_at', '<', $inquiryCutoff)
->get();
return $guests->count();
$all = $guests->merge($inquiriesOnly)->unique('id');
$all->each->anonymize();
$this->purgeOperationalData();
return $all->count();
}
private function purgeOperationalData(): void
{
PortalEmail::query()
->whereNotNull('excerpt')
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
->update(['excerpt' => null]);
Booking::query()
->where('created_at', '<', now()->subMonths(config('fewo.retention.attribution_months')))
->where(fn ($query) => $query->whereNotNull('referral_source')->orWhereNotNull('utm_source')->orWhereNotNull('utm_medium')->orWhereNotNull('utm_campaign'))
->update(['referral_source' => null, 'utm_source' => null, 'utm_medium' => null, 'utm_campaign' => null]);
}
}
+92
View File
@@ -0,0 +1,92 @@
<?php
namespace App\Actions;
use App\Channels\ICal\ICalRuleEngine;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ApplyChannelRules
{
public function attributes(Channel $channel, ?BlockedPeriod $block, array $properties): array
{
$result = app(ICalRuleEngine::class)->evaluate($channel, $properties);
$attributes = ['ical_interpretation' => $result, 'ical_event_type' => $result['event_type'],
'leading_priority' => $result['representation'] === 'leading_candidate' ? max(1, 10001 - $result['priority']) : 0];
$previousOrigin = $block?->ical_interpretation['origin_channel_id'] ?? null;
if ($block === null || ($block->occupation_kind === null && $block->reviewed_at === null && ($block->origin_channel_id === null || $block->origin_channel_id === $previousOrigin))) {
$attributes['origin_channel_id'] = $result['origin_channel_id'];
}
return $attributes;
}
public function store(BlockedPeriod $block, array $attributes): void
{
foreach ($attributes as $field => $value) {
if ($block->getAttribute($field) !== $value) {
$block->forceFill([$field => $value]);
}
}
if ($block->isDirty()) {
$block->saveQuietly();
}
}
/** @return array{classified: int, missing_raw: int} */
public function handle(Channel $channel): array
{
return DB::transaction(function () use ($channel): array {
$channel = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
app(ICalRuleEngine::class)->validate($channel, $channel->ical_rules ?? []);
$channel->forceFill(['ical_active_rules' => $channel->ical_rules ?? []])->save();
Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail();
$events = collect($channel->ical_analysis['events'] ?? [])->keyBy('uid');
$counts = ['classified' => 0, 'missing_raw' => 0];
foreach ($channel->blockedPeriods()->where('source', 'channel')->lockForUpdate()->get() as $block) {
$event = $events->get($block->external_uid);
if ($event && $block->ical_raw !== null && $channel->ical_analyzed_at !== null
&& $block->updated_at->greaterThan($channel->ical_analyzed_at) && $block->ical_raw !== $event['raw']) {
if (! $this->hasEquivalentTimestampUpdate($channel, $block, $event)) {
throw ValidationException::withMessages(['rules' => 'Der Importbestand hat sich seit der Vorschau geändert. Den Kalender erneut analysieren und die Vorschau prüfen.']);
}
$event = [...$event, 'properties' => $block->ical_properties, 'raw' => $block->ical_raw];
}
$properties = $event['properties'] ?? $block->ical_properties;
if ($properties === null) {
$counts['missing_raw']++;
continue;
}
$attributes = $this->attributes($channel, $block, $properties);
if ($event && $event['starts_on'] !== null && ($block->starts_on->toDateString() !== $event['starts_on'] || $block->ends_on->toDateString() !== $event['ends_on'])) {
$attributes = [...$attributes, 'needs_review' => true, 'review_note' => 'Die Analyse meldet einen anderen Zeitraum. Die Klassifikation ändert keine Termine; Kalenderabgleich und Zuordnung prüfen.'];
}
$this->store($block, [...$attributes, 'ical_properties' => $properties, 'ical_raw' => $event['raw'] ?? $block->ical_raw]);
$counts['classified']++;
}
app(ReconcileChannelRepresentations::class)->handle($channel->property);
return $counts;
});
}
private function hasEquivalentTimestampUpdate(Channel $channel, BlockedPeriod $block, array $event): bool
{
if ($block->ical_properties === null) {
return false;
}
$withoutTimestamps = fn (string $raw): string => preg_replace('/^(?:DTSTAMP|LAST-MODIFIED)(?:;[^:\r\n]*)?:[^\r\n]*(?:\r\n|\n|$)/mi', '', $raw);
if ($withoutTimestamps($block->ical_raw) !== $withoutTimestamps($event['raw'])) {
return false;
}
$engine = app(ICalRuleEngine::class);
return $engine->evaluate($channel, $block->ical_properties) === $engine->evaluate($channel, $event['properties']);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Actions;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class AssignOccupationGuest
{
/** @param array{first_name?: string, last_name?: ?string, email?: ?string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string, notes?: ?string, tags?: ?array} $details */
public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $details = []): Guest
{
Gate::authorize('update', $occupation);
return DB::transaction(function () use ($occupation, $guestId, $details): Guest {
$record = $occupation->newQuery()->whereKey($occupation->id)->lockForUpdate()->firstOrFail();
if ($record instanceof BlockedPeriod && ($record->occupationKind() !== OccupationKind::Reservation || $record->is_representation)) {
throw ValidationException::withMessages(['guest_id' => 'Zuerst als eigenständige Portalreservierung einordnen. Darstellungen werden an der führenden Buchung gepflegt.']);
}
if ($guestId !== null) {
$guest = Guest::query()->where('tenant_id', $record->tenant_id)->whereNull('anonymized_at')->findOrFail($guestId);
Gate::authorize('view', $guest);
} else {
Gate::authorize('create', Guest::class);
$data = Validator::make($details, [
'first_name' => ['required', 'string', 'max:255'],
'last_name' => ['nullable', 'string', 'max:255'],
'email' => ['nullable', 'email', 'max:255'],
'phone' => ['nullable', 'string', 'max:50'],
'street' => ['nullable', 'string', 'max:255'],
'postal_code' => ['nullable', 'string', 'max:20'],
'city' => ['nullable', 'string', 'max:255'],
'country' => ['nullable', 'string', 'size:2', 'regex:/^[A-Z]{2}$/'],
'notes' => ['nullable', 'string'],
'tags' => ['nullable', 'array'],
'tags.*' => ['string', 'max:255'],
])->validate();
$guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null, 'country' => $data['country'] ?? 'DE']);
$guest->forceFill(['tenant_id' => $record->tenant_id])->save();
}
$record->forceFill(['guest_id' => $guest->id])->save();
return $guest;
});
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Actions;
use App\Enums\BlockedPeriodPurpose;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class ClassifyPortalOccupation
{
/** @param array{block_purpose?: BlockedPeriodPurpose|string|null, block_note?: string|null, is_private?: bool} $details */
public function handle(BlockedPeriod $occupation, OccupationKind $kind, ?int $originId = null, array $details = []): void
{
Gate::authorize('update', $occupation);
if (($details['block_purpose'] ?? null) instanceof BlockedPeriodPurpose) {
$details['block_purpose'] = $details['block_purpose']->value;
}
$details = Validator::make($details, [
'block_purpose' => ['nullable', Rule::enum(BlockedPeriodPurpose::class)],
'block_note' => ['nullable', 'string', 'max:255'],
'is_private' => ['sometimes', 'boolean'],
])->validate();
if (($details['is_private'] ?? false) && $originId !== null) {
throw ValidationException::withMessages(['origin_channel_id' => 'Privat und ein externer Buchungskanal können nicht gleichzeitig gewählt werden.']);
}
DB::transaction(function () use ($occupation, $kind, $originId, $details): void {
Property::query()->whereKey($occupation->property_id)->lockForUpdate()->firstOrFail();
$record = BlockedPeriod::query()->whereKey($occupation->id)->lockForUpdate()->firstOrFail();
if (! in_array($record->source, ['channel', 'email'], true) || $record->is_representation) {
throw ValidationException::withMessages(['occupation_kind' => 'Nur eigenständige Portalereignisse können hier eingeordnet werden.']);
}
if ($originId !== null && ! Channel::query()->where('property_id', $record->property_id)->whereKey($originId)->exists()) {
throw ValidationException::withMessages(['origin_channel_id' => 'Der Ursprungskanal muss zur selben Wohnung gehören.']);
}
$record->forceFill([
'occupation_kind' => $kind,
'origin_channel_id' => $originId,
'is_private' => $details['is_private'] ?? false,
'block_purpose' => $kind === OccupationKind::Block ? (array_key_exists('block_purpose', $details) ? $details['block_purpose'] : $record->block_purpose) : null,
'block_note' => $kind === OccupationKind::Block ? (array_key_exists('block_note', $details) ? $details['block_note'] : $record->block_note) : null,
])->save();
app(ReconcileChannelRepresentations::class)->handle($record->property);
});
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
namespace App\Actions;
use App\Channels\ICal\ICalFeed;
use App\Channels\ICal\ICalParser;
use App\Enums\ChannelStatus;
use App\Models\Channel;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ConfigureChannel
{
/** @param array<string, mixed> $data */
public function handle(Property $property, array $data, ?Channel $channel = null): Channel
{
return DB::transaction(function () use ($property, $data, $channel): Channel {
$stored = $channel ? $property->channels()->whereKey($channel->id)->lockForUpdate()->firstOrFail() : null;
$candidate = $stored ? clone $stored : new Channel;
$candidate->fill($data);
$candidate->property_id = $property->id;
$candidate->tenant_id = $property->tenant_id;
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url')) {
$candidate->forceFill(['ical_analysis' => null, 'ical_analyzed_at' => null]);
}
if ($stored) {
$candidate->is_active = $candidate->status === ChannelStatus::Active;
}
if ($candidate->import_enabled && blank($candidate->setting('import_url'))) {
throw ValidationException::withMessages(['settings.import_url' => 'Für einen aktivierten Import ist eine Kalenderadresse erforderlich.']);
}
if ($stored && $stored->setting('import_url') !== $candidate->setting('import_url') && $stored->blockedPeriods()->withTrashed()->exists()) {
throw ValidationException::withMessages(['settings.import_url' => 'Bei bestehendem Importbestand die Quelladresse nicht ungeprüft ersetzen. Einen neuen Kanal anlegen oder die Bestandsumstellung gesondert freigeben.']);
}
if ($stored && $stored->exportsOccupations() && ! $candidate->exportsOccupations() && $stored->export_snapshot === null) {
$body = app(ICalFeed::class)->build($stored);
app(ICalParser::class)->parse($body);
$candidate->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
}
if ($stored && $stored->importsOccupations() !== $candidate->importsOccupations()) {
$stored->blockedPeriods()->where('source', 'channel')->update(['missing_imports' => 0]);
}
$candidate->save();
return $candidate->refresh();
});
}
}
+30
View File
@@ -0,0 +1,30 @@
<?php
namespace App\Actions;
use App\Channels\ICal\ICalExportFields;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
class ConfigureChannelExport
{
public function handle(Channel $channel, array $mapping, bool $allowNames): Channel
{
Validator::make(['export_mapping' => $mapping], [
'export_mapping' => ['array', 'max:3'],
'export_mapping.*.field' => ['required', 'distinct', Rule::in(array_keys(ICalExportFields::ICAL_FIELDS))],
'export_mapping.*.items' => ['required', 'array', 'min:1'],
'export_mapping.*.items.*' => ['required', Rule::in(array_keys(ICalExportFields::FIELDS))],
'export_mapping.*.separator' => ['nullable', 'string', 'max:30'],
])->validate();
return DB::transaction(function () use ($channel, $mapping, $allowNames): Channel {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
$locked->forceFill(['ical_export_mapping' => array_values($mapping), 'ical_export_names' => $allowNames])->save();
return $locked;
});
}
}
+16 -3
View File
@@ -3,6 +3,7 @@
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\BookingConfirmed;
@@ -11,18 +12,27 @@
use Illuminate\Support\Facades\Mail;
/**
* The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free.
* 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.
*/
class ConfirmBooking
{
public function __construct(private AvailabilityChecker $availability) {}
public function __construct(
private AvailabilityChecker $availability,
private RentalContract $contract,
) {}
/**
* @throws ReservationException
*/
public function handle(Booking $booking, bool $notifyGuest = true): void
{
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
}
@@ -35,9 +45,12 @@ public function handle(Booking $booking, bool $notifyGuest = true): void
'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));
}
+35 -6
View File
@@ -3,26 +3,40 @@
namespace App\Actions;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* Copies all seasons starting in a given year to the following year with the same calendar dates,
* so a new price year only needs adjusting instead of re-entering.
* Copies all seasons starting in a given year to the following year, so a new price year only needs adjusting
* instead of re-entering. Optionally every season start is moved to the nearest given weekday (e.g. Saturday
* as changeover day); seasons that were adjacent stay adjacent.
*/
class CopySeasonsToNextYear
{
/**
* @param int|null $alignToWeekday ISO weekday (1 = Monday … 7 = Sunday) or null for the same calendar dates
* @return array{created: int, skipped: int}
*/
public function handle(Property $property, int $year): array
public function handle(Property $property, int $year, ?int $alignToWeekday = null): array
{
$created = 0;
$skipped = 0;
$seasons = $property->seasons()->whereYear('starts_on', $year)->get();
$seasons = $property->seasons()->whereYear('starts_on', $year)->orderBy('starts_on')->get();
// New start per old start date; an end that equals another season's start follows that start.
$moved = [];
foreach ($seasons as $season) {
$moved[$season->starts_on->toDateString()] = $this->shift($season->starts_on, $alignToWeekday);
}
foreach ($seasons as $season) {
$startsOn = $season->starts_on->addYearNoOverflow();
$endsOn = $season->ends_on->addYearNoOverflow();
$startsOn = $moved[$season->starts_on->toDateString()];
$endsOn = $moved[$season->ends_on->toDateString()] ?? $this->shift($season->ends_on, $alignToWeekday);
if ($endsOn->lessThanOrEqualTo($startsOn)) {
$skipped++;
continue;
}
if ($property->seasons()->overlapping($startsOn, $endsOn)->exists()) {
$skipped++;
@@ -40,4 +54,19 @@ public function handle(Property $property, int $year): array
return ['created' => $created, 'skipped' => $skipped];
}
/**
* One year later; with a weekday, moved to the nearest such day (at most 3 days earlier or later).
*/
private function shift(CarbonImmutable $date, ?int $weekday): CarbonImmutable
{
$next = $date->addYearNoOverflow();
if ($weekday === null) {
return $next;
}
$difference = ($weekday - $next->isoWeekday() + 7) % 7;
return $difference <= 3 ? $next->addDays($difference) : $next->subDays(7 - $difference);
}
}
+155
View File
@@ -0,0 +1,155 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Enums\ChannelExportMode;
use App\Enums\ChannelTaskAction;
use App\Enums\ChannelTaskStatus;
use App\Mail\ChannelTasksNotification;
use App\Models\Channel;
use App\Models\ChannelTask;
use App\Models\Property;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
use Throwable;
/**
* Creates blocking/unblocking tasks for every portal that must be maintained by hand
* (e.g. instant booking portals whose calendar import is too slow), notifies the landlord
* and hands the task to an optional external automation.
*/
class CreateChannelTasks
{
/**
* @return list<ChannelTask>
*/
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null, ?int $originChannelId = null, bool $external = false): array
{
if ($endsOn->lessThanOrEqualTo(today())) {
return [];
}
$channels = $property->channels()->active()
->where('requires_manual_blocking', true)
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
->when($originChannelId, fn ($query) => $query->whereKeyNot($originChannelId))
->get()->filter(fn (Channel $channel): bool => $channel->exportsOccupations()
&& (! ($external || $exceptChannelId !== null || $originChannelId !== null) || $channel->export_mode === ChannelExportMode::Regular));
$tasks = [];
foreach ($channels as $channel) {
$segments = $action === ChannelTaskAction::Unblock ? $this->freeSegments($property, $startsOn, $endsOn) : [[$startsOn, $endsOn]];
foreach ($segments as [$start, $end]) {
$task = $channel->tasks()->where('action', $action)->where('status', ChannelTaskStatus::Open)
->whereDate('starts_on', $start)->whereDate('ends_on', $end)->first()
?? $channel->tasks()->create([
'action' => $action, 'starts_on' => $start->toDateString(), 'ends_on' => $end->toDateString(),
'status' => ChannelTaskStatus::Open, 'reason' => $reason,
]);
if ($task->wasRecentlyCreated) {
$tasks[] = $task;
}
}
}
if ($tasks === []) {
return [];
}
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks)));
foreach ($tasks as $task) {
$this->sendToAutomation($task);
}
return $tasks;
}
/**
* POSTs the task to the automation webhook, signed with HMAC-SHA256 (header X-Signature).
* The automation confirms via the signed callback URL contained in the payload.
*/
public function sendToAutomation(ChannelTask $task): void
{
$task->refresh();
if ($task->status !== ChannelTaskStatus::Open) {
return;
}
if (! $task->channel->exportsOccupations()) {
$task->update(['automation_error' => 'Kanalexport ist pausiert; keine automatische Portaländerung.']);
return;
}
if ($task->action === ChannelTaskAction::Unblock && ! app(AvailabilityChecker::class)->isAvailable($task->channel->property, $task->starts_on, $task->ends_on)) {
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Zeitraum ist inzwischen wieder belegt; nicht entsperren.']);
return;
}
if ($task->action === ChannelTaskAction::Block) {
$occupied = app(AvailabilityChecker::class)->occupiedNights($task->channel->property, $task->starts_on, $task->ends_on);
for ($night = $task->starts_on; $night->lessThan($task->ends_on); $night = $night->addDay()) {
if (! isset($occupied[$night->toDateString()])) {
$task->update(['status' => ChannelTaskStatus::Dismissed, 'automation_error' => 'Sperraufgabe ist durch eine Belegungsänderung überholt; aktuellen Zeitraum prüfen.']);
return;
}
}
}
$url = config('fewo.automation.webhook_url');
$secret = config('fewo.automation.secret');
if (blank($url) || blank($secret)) {
return;
}
$body = json_encode([
'task_id' => $task->id,
'channel' => $task->channel->name,
'connector' => $task->channel->connector,
'action' => $task->action->value,
'starts_on' => $task->starts_on->toDateString(),
'ends_on' => $task->ends_on->toDateString(),
'manage_url' => $task->channel->manage_url,
'callback_url' => URL::route('channel-tasks.complete', $task),
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
try {
Http::timeout(10)
->withHeaders(['X-Signature' => hash_hmac('sha256', $body, $secret)])
->withBody($body, 'application/json')
->post($url)
->throw();
$task->update(['automation_sent_at' => now(), 'automation_error' => null]);
} catch (Throwable $exception) {
$task->update(['automation_error' => $exception->getMessage()]);
}
}
/** @return list<array{CarbonImmutable, CarbonImmutable}> */
private function freeSegments(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn): array
{
$start = CarbonImmutable::instance($startsOn);
$end = CarbonImmutable::instance($endsOn);
$occupied = app(AvailabilityChecker::class)->occupiedNights($property, $start, $end);
$segments = [];
$segmentStart = null;
for ($night = $start; $night->lessThan($end); $night = $night->addDay()) {
if (! isset($occupied[$night->toDateString()])) {
$segmentStart ??= $night;
} elseif ($segmentStart !== null) {
$segments[] = [$segmentStart, $night];
$segmentStart = null;
}
}
if ($segmentStart !== null) {
$segments[] = [$segmentStart, $end];
}
return $segments;
}
}
+69 -5
View File
@@ -13,6 +13,10 @@
use App\Pricing\PriceCalculator;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use App\Support\Settings;
use App\Tenancy\TenantContext;
use App\Tenancy\TenantContextMissing;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Throwable;
@@ -30,13 +34,32 @@ public function __construct(
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking {
$tenant = $property->tenant;
if ($tenant === null) {
throw new TenantContextMissing(Property::class);
}
return app(TenantContext::class)->run(
$tenant,
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
);
}
/**
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
*/
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
{
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
Property::whereKey($property->getKey())->lockForUpdate()->first();
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
@@ -45,13 +68,13 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
$quote = $this->calculator->calculate($property, $stay);
$guest = Guest::firstOrNew(['email' => mb_strtolower($guestData['email'])]);
$guest->fill($guestData)->fill(['email' => mb_strtolower($guestData['email'])])->save();
[$guest, $differences] = $this->guestFor($guestData);
return $property->bookings()->create([
'guest_id' => $guest->id,
'status' => BookingStatus::Reserved,
'source' => $source,
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
'arrival' => $stay->arrival->toDateString(),
'departure' => $stay->departure->toDateString(),
'guests' => $stay->guests,
@@ -63,6 +86,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => now()->addHours($property->hold_hours),
'message' => $message,
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
]);
});
@@ -73,6 +97,46 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
return $booking;
}
/**
* The guest record for the request. A known e-mail address never overwrites existing master data
* (anybody can type somebody else's address); empty fields are completed, differing values are
* returned so the landlord sees them with the request and can take them over in the offer.
*
* @param array<string, ?string> $guestData
* @return array{0: Guest, 1: list<string>}
*/
private function guestFor(array $guestData): array
{
$email = mb_strtolower($guestData['email']);
$guest = Guest::query()->where('email', $email)->first();
if ($guest === null) {
return [Guest::create([
...$guestData,
'email' => $email,
'tenant_id' => app(TenantContext::class)->id(),
]), []];
}
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
$differences = [];
foreach ($labels as $field => $label) {
$value = trim((string) ($guestData[$field] ?? ''));
if ($value === '') {
continue;
}
if (blank($guest->{$field})) {
$guest->{$field} = $value;
} elseif (mb_strtolower((string) $guest->{$field}) !== mb_strtolower($value)) {
$differences[] = "{$label}: {$value} (Kartei: {$guest->{$field}})";
}
}
$guest->save();
return [$guest, $differences];
}
/**
* A failing mail server must not lose the reservation; failures are reported and visible in the log.
*/
@@ -80,7 +144,7 @@ private function sendMails(Booking $booking): void
{
try {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
Mail::to(config('fewo.notification_email'))->send(new NewReservation($booking));
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking));
} catch (Throwable $exception) {
report($exception);
}
+5 -1
View File
@@ -15,7 +15,11 @@ class DeclineBooking
*/
public function handle(Booking $booking, bool $notifyGuest = true): void
{
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
if ($notifyGuest && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
}
+3 -2
View File
@@ -5,6 +5,7 @@
use App\Enums\BookingStatus;
use App\Mail\ReservationExpired;
use App\Models\Booking;
use App\Support\Settings;
use Illuminate\Support\Facades\Mail;
/**
@@ -16,7 +17,7 @@ class ExpireReservations
public function handle(): int
{
$expired = Booking::query()
->where('status', BookingStatus::Reserved)
->whereIn('status', BookingStatus::holding())
->where('hold_expires_at', '<=', now())
->with(['guest', 'property'])
->get();
@@ -24,7 +25,7 @@ public function handle(): int
foreach ($expired as $booking) {
$booking->update(['status' => BookingStatus::Expired]);
Mail::to(config('fewo.notification_email'))->send(new ReservationExpired($booking));
Mail::to(Settings::notificationRecipients())->send(new ReservationExpired($booking));
}
return $expired->count();
+64
View File
@@ -0,0 +1,64 @@
<?php
namespace App\Actions;
use App\Channels\Mail\MailboxReader;
use App\Mail\ChannelSyncAlert;
use App\Mail\MailboxAlert;
use App\Models\Channel;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
/**
* Alerts the landlord once per incident when a portal import or the mailbox fast path fails
* or has not succeeded for too long. The alert is reset by the next success.
*/
class MonitorChannels
{
private const MAILBOX_ALERTED_KEY = 'mailbox:alerted';
public function handle(): int
{
$channels = Channel::query()->active()->whereNull('alerted_at')->get()
->filter(fn (Channel $channel): bool => $channel->isStale());
foreach ($channels as $channel) {
Mail::to(Settings::notificationRecipients())->send(new ChannelSyncAlert($channel));
$channel->forceFill(['alerted_at' => now()])->save();
}
return $channels->count() + $this->monitorMailbox();
}
public static function mailboxIsStale(): bool
{
if (! MailboxReader::isConfigured()) {
return false;
}
$lastSuccess = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
return $lastSuccess === null
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
}
private function monitorMailbox(): int
{
if (! self::mailboxIsStale()) {
Cache::forget(self::MAILBOX_ALERTED_KEY);
return 0;
}
if (Cache::has(self::MAILBOX_ALERTED_KEY)) {
return 0;
}
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))));
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
return 1;
}
}
+188
View File
@@ -0,0 +1,188 @@
<?php
namespace App\Actions;
use App\Channels\ConflictDetector;
use App\Channels\Mail\ParsedPortalMail;
use App\Channels\Mail\PortalMail;
use App\Channels\Mail\PortalMailParser;
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Enums\TenantServiceKey;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/**
* Fast path for portal bookings: the notification e-mail usually arrives within a minute, long before
* the portal's calendar export is read. A recognised booking is blocked immediately; the later calendar
* sync confirms the block. Anything not recognised with confidence is flagged for review – never guessed.
*/
class ProcessPortalMail
{
public function __construct(
private PortalMailParser $parser,
private ConflictDetector $conflictDetector,
) {}
public function handle(PortalMail $mail): ?PortalEmail
{
if (PortalEmail::where('message_id', $mail->messageId)->exists()) {
return null;
}
$channel = $this->channelFor($mail->from);
if ($channel === null) {
return null;
}
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
return null;
}
$parsed = $this->parser->parse($mail->subject, $mail->text);
$conflicts = [];
$record = DB::transaction(function () use ($mail, $channel, $parsed, &$conflicts): PortalEmail {
[$status, $block, $note] = match ($parsed->type) {
PortalEmailType::Booking => $this->block($channel, $parsed, $conflicts),
PortalEmailType::Cancellation => $this->release($channel, $parsed),
PortalEmailType::Inquiry => [PortalEmailStatus::Ignored, null, 'Anfrage – keine Sperre nötig.'],
PortalEmailType::Unknown => [PortalEmailStatus::NeedsReview, null, 'Inhalt nicht erkannt.'],
};
return PortalEmail::create([
'channel_id' => $channel->id,
'message_id' => $mail->messageId,
'from' => mb_substr($mail->from, 0, 255),
'subject' => mb_substr($mail->subject, 0, 255),
'received_at' => $mail->receivedAt,
'type' => $parsed->type,
'status' => $status,
'starts_on' => $parsed->startsOn?->toDateString(),
'ends_on' => $parsed->endsOn?->toDateString(),
'reference' => $parsed->reference,
'blocked_period_id' => $block?->id,
'excerpt' => mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags($mail->text))), 0, 500),
'note' => $note,
]);
});
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
}
if ($conflicts !== []) {
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
}
return $record;
}
/**
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
*/
public function channelFor(string $from): ?Channel
{
$from = mb_strtolower($from);
$matches = Channel::query()->active()->get()->filter(function (Channel $channel) use ($from): bool {
foreach ($this->senders($channel) as $sender) {
if (str_contains($from, $sender)) {
return true;
}
}
return false;
});
if ($matches->count() > 1) {
foreach ($matches as $channel) {
$channel->forceFill(['sync_warnings' => array_values(array_unique([
...($channel->sync_warnings ?? []), 'Portal-Mail-Absender passt zu mehreren Kanälen. Keine automatische Wohnungszuordnung vorgenommen.',
]))])->saveQuietly();
}
}
return $matches->count() === 1 ? $matches->first() : null;
}
/**
* @return list<string>
*/
public function senders(Channel $channel): array
{
return array_values(array_filter(array_map(
fn (string $sender): string => mb_strtolower(trim($sender)),
explode(',', (string) $channel->setting('email_senders')),
)));
}
/**
* @param array<string, CarbonInterface> $conflicts description => first night
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
{
if (! $parsed->hasPeriod()) {
return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.'];
}
$known = $parsed->reference === null ? null : $channel->blockedPeriods()
->whereIn('external_uid', ['email:'.$parsed->reference, $parsed->reference])->first();
if ($known) {
if ($known->source === 'email') {
$known->update(['starts_on' => $parsed->startsOn->toDateString(), 'ends_on' => $parsed->endsOn->toDateString()]);
}
return [PortalEmailStatus::AlreadyKnown, $known, null];
}
$block = $channel->blockedPeriods()->create([
'property_id' => $channel->property_id,
'starts_on' => $parsed->startsOn->toDateString(),
'ends_on' => $parsed->endsOn->toDateString(),
'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''),
'source' => 'email',
'external_uid' => 'email:'.($parsed->reference ?? bin2hex(random_bytes(16))),
]);
if ($channel->blockedPeriods()->whereKeyNot($block->id)->overlapping($block->starts_on, $block->ends_on)->exists()) {
$block->forceFill(['needs_review' => true, 'review_note' => 'Überlappende Portalrepräsentationen ohne gemeinsame Kennung persönlich prüfen.'])->saveQuietly();
}
$conflicts = array_fill_keys($this->conflictDetector->conflictsFor($block), $block->starts_on);
return [PortalEmailStatus::Blocked, $block, null];
}
/**
* Only blocks created from e-mails are released here; calendar blocks disappear with the next sync.
*
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function release(Channel $channel, ParsedPortalMail $parsed): array
{
$emailBlocks = $channel->blockedPeriods()->where('source', 'email');
$block = match (true) {
$parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(),
default => null,
};
if ($block) {
$block->delete();
return [PortalEmailStatus::Released, null, 'Sperre aus E-Mail aufgehoben.'];
}
return [PortalEmailStatus::NeedsReview, null, 'Stornierung erkannt – bitte prüfen; Kalender-Sperren verschwinden mit dem nächsten Abgleich.'];
}
}
@@ -0,0 +1,113 @@
<?php
namespace App\Actions;
use App\Enums\ChannelEchoBehavior;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
class ReconcileChannelRepresentations
{
public const OVERLAP_NOTE = 'Mehrere Belegungsrepräsentationen oder Überschneidungen prüfen; keine automatische Zusammenführung anhand von Terminen.';
private const LINK_NOTE = 'Automatisch als Kalenderspiegelung einer eindeutig passenden führenden Portalreservierung zugeordnet.';
private const RECHECK_NOTE = 'Automatische Kalenderspiegelung nicht mehr eindeutig. Quellen, Termine und mögliche Stornierung prüfen; der weiterhin gemeldete Zeitraum bleibt belegt.';
/** @return array{linked: int, unlinked: int} */
public function handle(Property $property): array
{
return DB::transaction(function () use ($property): array {
$property = Property::query()->whereKey($property->id)->lockForUpdate()->firstOrFail();
$blocks = $property->blockedPeriods()->with('channel')->withCount('channelRepresentations')->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$independent = $blocks->filter(fn (BlockedPeriod $block): bool => ! $block->is_representation || $block->representation_automatic);
$mirrors = $independent->filter(fn (BlockedPeriod $block): bool => $this->isMirror($block));
$leaders = $independent->filter(fn (BlockedPeriod $block): bool => $this->isLeader($block));
$bookings = $property->bookings()->occupying()->get(['id', 'arrival', 'departure']);
$targets = [];
foreach ($mirrors as $mirror) {
$matches = $leaders->filter(fn (BlockedPeriod $leader): bool => $leader->channel_id !== $mirror->channel_id && $this->sameDates($leader, $mirror));
if ($matches->count() !== 1) {
continue;
}
$leader = $matches->sole();
$contradiction = $independent->contains(fn (BlockedPeriod $other): bool => $other->id !== $mirror->id && $other->id !== $leader->id
&& $other->starts_on->lessThan($leader->ends_on) && $other->ends_on->greaterThan($leader->starts_on)
&& ! ($mirrors->has($other->id) && $this->sameDates($other, $leader)));
if ($contradiction || $bookings->contains(fn ($booking): bool => $booking->arrival->lessThan($leader->ends_on) && $booking->departure->greaterThan($leader->starts_on))) {
continue;
}
$targets[$mirror->id] = $leader;
}
$counts = ['linked' => 0, 'unlinked' => 0];
foreach ($blocks as $block) {
$leader = $targets[$block->id] ?? null;
if ($leader === null) {
if ($block->representation_automatic) {
$block->forceFill(['representation_automatic' => false, 'is_representation' => false, 'canonical_block_id' => null, 'export_approved' => false,
'needs_review' => true, 'review_note' => self::RECHECK_NOTE])->save();
$counts['unlinked']++;
}
continue;
}
$newLink = ! $block->is_representation || $block->canonical_block_id !== $leader->id;
$block->forceFill(['representation_automatic' => true, 'is_representation' => true, 'canonical_block_id' => $leader->id,
'needs_review' => false, 'review_note' => self::LINK_NOTE]);
if ($block->isDirty()) {
$block->save();
}
$counts['linked'] += (int) $newLink;
if ($leader->reviewed_at === null) {
if ($leader->channel?->echo_behavior !== ChannelEchoBehavior::Reexports) {
$leader->forceFill(['export_approved' => true]);
}
if ($leader->review_note === self::OVERLAP_NOTE) {
$leader->forceFill(['needs_review' => false, 'review_note' => null]);
}
if ($leader->isDirty()) {
$leader->save();
}
}
}
return $counts;
});
}
private function isMirror(BlockedPeriod $block): bool
{
$interpretation = $block->ical_interpretation ?? [];
return $block->source === 'channel' && $block->channel_id !== null && $block->missing_imports === 0
&& $block->occupation_kind === null && $block->guest_id === null && ! $block->is_private
&& $block->block_purpose === null && blank($block->block_note) && $block->reviewed_at === null
&& $block->origin_channel_id === null && $block->linked_booking_id === null && $block->channel_representations_count === 0
&& $block->ical_event_type === 'block' && ($interpretation['matched'] ?? false)
&& ($interpretation['representation'] ?? null) === 'additional_block' && ($interpretation['origin_channel_id'] ?? null) === null
&& blank($interpretation['fields']['booking_reference'] ?? null) && blank($interpretation['fields']['guest_full_name'] ?? null)
&& blank($interpretation['fields']['guest_first_name'] ?? null) && $this->hasCompatibleReview($block);
}
private function isLeader(BlockedPeriod $block): bool
{
return $block->source === 'channel' && $block->channel_id !== null && ! $block->is_representation
&& $block->occupationKind() === OccupationKind::Reservation && $block->ical_event_type === 'portal_reservation'
&& $block->missing_imports === 0 && ! $block->is_private && $block->leading_priority > 0
&& $block->origin_channel_id === $block->channel_id && ($block->ical_interpretation['matched'] ?? false)
&& ($block->ical_interpretation['representation'] ?? null) === 'leading_candidate' && $this->hasCompatibleReview($block);
}
private function hasCompatibleReview(BlockedPeriod $block): bool
{
return ! $block->needs_review || in_array($block->review_note, [self::OVERLAP_NOTE, self::LINK_NOTE, self::RECHECK_NOTE], true);
}
private function sameDates(BlockedPeriod $first, BlockedPeriod $second): bool
{
return $first->starts_on->equalTo($second->starts_on) && $first->ends_on->equalTo($second->ends_on);
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Enums\PaymentMethod;
use App\Models\Booking;
use App\Models\Payment;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
/**
* Records a received payment (or a refund with a negative amount) and moves the booking along:
* Bestätigt → Anzahlung erhalten → Bezahlt.
*/
class RecordPayment
{
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
{
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
$payment = $booking->payments()->create([
'amount' => $amount,
'paid_on' => $paidOn->toDateString(),
'method' => $method,
'note' => $note,
'recorded_by' => $recordedBy,
]);
$booking->unsetRelation('payments');
$this->updateStatus($booking);
return $payment;
});
}
public function updateStatus(Booking $booking): void
{
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid];
if (! in_array($booking->status, $paymentStatuses, true)) {
return;
}
$paid = $booking->paidAmount();
$status = match (true) {
$paid >= $booking->total => BookingStatus::Paid,
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
default => BookingStatus::Confirmed,
};
if ($status !== $booking->status) {
$booking->update(['status' => $status]);
}
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Exceptions\ReservationException;
use App\Mail\OfferAnswered;
use App\Models\Booking;
use App\Support\Settings;
use Illuminate\Support\Facades\Mail;
use Throwable;
/**
* The guest declines the offer on the offer page: the dates are released and the landlord is informed.
*/
class RejectOffer
{
/**
* @throws ReservationException
*/
public function handle(Booking $booking, int $offerVersion): void
{
if ($offerVersion !== $booking->offer_version) {
throw ReservationException::offerOutdated();
}
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));
} catch (Throwable $exception) {
report($exception);
}
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Actions;
use App\Mail\ChannelTasksNotification;
use App\Models\ChannelTask;
use App\Support\Settings;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Mail;
/**
* Reminds the landlord about blocking tasks that are still open after the reminder time, and again after
* the landlord's reminder interval while they stay open (Settings::reminderIntervalDays(), 0 = only once).
*/
class RemindChannelTasks
{
public function handle(): int
{
$interval = Settings::reminderIntervalDays();
$tasks = ChannelTask::query()
->open()
->where(fn (Builder $query) => $query
->whereNull('reminded_at')
->when($interval > 0, fn (Builder $query) => $query->orWhere('reminded_at', '<=', now()->subDays($interval))))
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
->with('channel')
->get();
if ($tasks->isEmpty()) {
return 0;
}
Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks->all(), reminder: true));
ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]);
return $tasks->count();
}
}
+54
View File
@@ -0,0 +1,54 @@
<?php
namespace App\Actions;
use App\Enums\InboxMessageKind;
use App\Filament\Pages\OccupancyCalendar;
use App\Mail\ChannelConflict;
use App\Models\Channel;
use App\Support\Inbox;
use App\Support\Settings;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Mail;
/**
* Reports possible double bookings found while importing portal occupations (calendar sync or portal
* e-mail). Every conflict lands in the admin inbox once; only conflicts not reported before are e-mailed,
* so a lasting overlap does not trigger a mail on every sync. Unread ones are repeated after the landlord's
* reminder interval while the overlap persists (App\Support\Inbox).
*/
class ReportChannelConflicts
{
public function __construct(private Inbox $inbox) {}
/**
* @param array<string, CarbonInterface> $conflicts description => first night of the portal occupation
* @return list<string> the conflicts e-mailed now (new ones and due reminders)
*/
public function handle(Channel $channel, array $conflicts): array
{
$new = [];
$reminders = [];
foreach ($conflicts as $description => $startsOn) {
$message = $this->inbox->post(
InboxMessageKind::ChannelConflict,
$channel->id.':'.sha1($description),
'Mögliche Doppelbuchung über '.$channel->name,
$description,
$channel,
OccupancyCalendar::getUrl(['monat' => $startsOn->format('Y-m'), 'wohnung' => $channel->property_id]),
);
if ($message?->wasRecentlyCreated) {
$new[] = $description;
} elseif ($message) {
$reminders[] = $description;
}
}
if ($new !== [] || $reminders !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new, $reminders)));
}
return [...$new, ...$reminders];
}
}
+1 -1
View File
@@ -23,7 +23,7 @@ public function handle(): int
->whereDate('departure', '<=', $latestDeparture)
->whereDate('departure', '>', $latestDeparture->copy()->subDays(30))
->whereDoesntHave('review')
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at'))
->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->with('guest')
->get();
+53
View File
@@ -0,0 +1,53 @@
<?php
namespace App\Actions;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\Property;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\ValidationException;
class ResolveChannelOccupation
{
public function handle(BlockedPeriod $block, string $resolution, ?int $targetId = null, ?int $originId = null): BlockedPeriod
{
return DB::transaction(function () use ($block, $resolution, $targetId, $originId): BlockedPeriod {
Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail();
$block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail();
if (! in_array($block->source, ['channel', 'email'], true)) {
throw ValidationException::withMessages(['resolution' => 'Nur importierte Portalereignisse benötigen diese Zuordnung.']);
}
if (! in_array($resolution, ['independent', 'block', 'booking'], true)) {
throw ValidationException::withMessages(['resolution' => 'Bitte eine gültige Klärung wählen.']);
}
if ($originId !== null && ! Channel::query()->whereKey($originId)->where('property_id', $block->property_id)->exists()) {
throw ValidationException::withMessages(['origin_channel_id' => 'Der Ursprungskanal muss zur selben Wohnung gehören.']);
}
$attributes = ['is_representation' => false, 'canonical_block_id' => null, 'linked_booking_id' => null,
'origin_channel_id' => $originId, 'is_private' => $originId === null && $block->is_private, 'export_approved' => true, 'needs_review' => false,
'reviewed_at' => now(), 'review_note' => 'Als eigenständige Belegung persönlich bestätigt.'];
if ($resolution !== 'independent') {
$query = $resolution === 'booking' ? Booking::query()->occupying() : BlockedPeriod::query()->occupying()->whereKeyNot($block->id);
$target = $query->where('property_id', $block->property_id)->whereKey($targetId)->lockForUpdate()->first();
$start = $resolution === 'booking' ? $target?->arrival : $target?->starts_on;
$end = $resolution === 'booking' ? $target?->departure : $target?->ends_on;
if ($target === null || ! $block->starts_on->equalTo($start) || ! $block->ends_on->equalTo($end)) {
throw ValidationException::withMessages(['target_id' => 'Eine belegende Buchung oder führende Sperre derselben Wohnung mit genau diesem Zeitraum wählen.']);
}
if (BlockedPeriod::query()->where('canonical_block_id', $block->id)->exists()) {
throw ValidationException::withMessages(['target_id' => 'Diese Sperre führt bereits andere Kalenderdarstellungen. Die Zuordnung an der untergeordneten Darstellung ändern.']);
}
$attributes = [...$attributes, 'is_representation' => true, 'export_approved' => false,
'canonical_block_id' => $resolution === 'block' ? $target->id : null,
'linked_booking_id' => $resolution === 'booking' ? $target->id : null,
'review_note' => 'Persönlich zugeordnet; nur die führende Belegung steuert Verfügbarkeit und Export.'];
}
$block->forceFill(['representation_automatic' => false])->fill($attributes)->save();
app(ReconcileChannelRepresentations::class)->handle($block->property);
return $block->refresh();
});
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Actions;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class RotateChannelToken
{
public function handle(Channel $channel, int $graceHours = 168): Channel
{
return DB::transaction(function () use ($channel, $graceHours): Channel {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
if ($graceHours < 24 || $graceHours > 720 || $locked->previous_export_token_expires_at?->isFuture()) {
throw ValidationException::withMessages(['grace_hours' => '24 bis 720 Stunden wählen; eine laufende Token-Übergangsphase muss zuerst ablaufen.']);
}
$locked->forceFill([
'previous_export_token' => $locked->export_token,
'previous_export_token_expires_at' => now()->addHours($graceHours),
'export_token' => Str::random(48),
])->save();
return $locked->refresh();
});
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Actions;
use App\Channels\ICal\ICalRuleEngine;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
class SaveChannelRules
{
public function handle(Channel $channel, array $rules): Channel
{
return DB::transaction(function () use ($channel, $rules): Channel {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
$validated = app(ICalRuleEngine::class)->validate($locked, $rules);
$locked->forceFill(['ical_rules' => $validated])->save();
return $locked;
});
}
}
+100
View File
@@ -0,0 +1,100 @@
<?php
namespace App\Actions;
use App\Enums\BookingStatus;
use App\Mail\ArrivalInformation;
use App\Mail\PaymentReminder;
use App\Models\Booking;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Mail;
/**
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
* Every message is sent at most once per booking.
*/
class SendBookingReminders
{
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
/**
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
*/
public function handle(): array
{
$today = today();
$unpaid = [BookingStatus::Confirmed, BookingStatus::DepositPaid];
$depositOverdue = $this->bookings(fn (Builder $query) => $query
->where('status', BookingStatus::Confirmed)
->whereNull('deposit_reminded_at')
->whereDate('deposit_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
$balanceRequest = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
->whereNull('balance_requested_at')
->whereDate('balance_due_on', '>=', $today)
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
->whereIn('status', $unpaid)
->whereNull('balance_reminded_at')
->whereDate('balance_due_on', '<', $today))
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
$arrivals = $this->bookings(fn (Builder $query) => $query
->whereIn('status', BookingStatus::occupying())
->whereNull('arrival_info_sent_at')
->whereDate('arrival', '>=', $today)
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
foreach ($arrivals as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
$booking->update(['arrival_info_sent_at' => now()]);
}
$completed = Booking::query()
->where('status', BookingStatus::Paid)
->whereDate('departure', '<', $today)
->get();
$completed->each->update(['status' => BookingStatus::Completed]);
return [
'deposit_overdue' => $depositOverdue->count(),
'balance_request' => $balanceRequest->count(),
'balance_overdue' => $balanceOverdue->count(),
'arrival_info' => $arrivals->count(),
'completed' => $completed->count(),
];
}
/**
* @param callable(Builder<Booking>): Builder<Booking> $constraints
* @return Collection<int, Booking>
*/
private function bookings(callable $constraints): Collection
{
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
->get()
->toBase();
}
/**
* @param Collection<int, Booking> $bookings
*/
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
{
foreach ($bookings as $booking) {
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
$booking->update([$sentAtColumn => now()]);
}
}
}
+67
View File
@@ -0,0 +1,67 @@
<?php
namespace App\Actions;
use App\Enums\DigestSection;
use App\Mail\Digest;
use App\Models\Tenant;
use App\Support\DigestReport;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Mail;
/**
* Sends the landlord's daily and/or weekly summary once the chosen hour has come (System › Betrieb ›
* Benachrichtigungen). On the weekly day only the weekly summary goes out, never both. Runs per landlord
* from the scheduler; the sent dates on the landlord make every summary go out at most once a day.
*/
class SendDigests
{
public function __construct(private DigestReport $report) {}
/**
* @return 'daily'|'weekly'|null which summary was due (also when it was skipped for being empty)
*/
public function handle(Tenant $tenant): ?string
{
$now = CarbonImmutable::now();
$today = $now->startOfDay();
if ($now->hour < $tenant->digest_hour) {
return null;
}
$weekly = $tenant->digest_weekly && $today->isoWeekday() === $tenant->digest_weekday && ! $tenant->digest_weekly_sent_on?->isSameDay($today);
$daily = $tenant->digest_daily && ! $tenant->digest_daily_sent_on?->isSameDay($today);
if (! $weekly && ! $daily) {
return null;
}
$this->send($tenant, $weekly);
$tenant->forceFill([
'digest_daily_sent_on' => $today->toDateString(),
...($weekly ? ['digest_weekly_sent_on' => $today->toDateString()] : []),
])->save();
return $weekly ? 'weekly' : 'daily';
}
/**
* Builds and mails one summary. Without anything to report it is skipped unless the landlord wants it
* anyway or $force is set (button „Zusammenfassung jetzt senden“).
*
* @return bool whether a mail was sent
*/
public function send(Tenant $tenant, bool $weekly, bool $force = false): bool
{
$since = CarbonImmutable::now()->sub($weekly ? '7 days' : '1 day');
$sections = $this->report->build(DigestSection::chosen($tenant->digest_sections), $weekly, $since);
if ($sections === [] && ! $tenant->digest_when_empty && ! $force) {
return false;
}
Mail::to(Settings::notificationRecipients())->send(new Digest($weekly, $sections));
return true;
}
}
+127
View File
@@ -0,0 +1,127 @@
<?php
namespace App\Actions;
use App\Availability\AvailabilityChecker;
use App\Documents\RentalContract;
use App\Enums\BookingStatus;
use App\Enums\QuoteLineType;
use App\Exceptions\ReservationException;
use App\Mail\OfferMade;
use App\Models\Booking;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\QuoteLine;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\URL;
/**
* Booking path 1 (docs/KONZEPT.md §6a): the landlord turns a request into an offer. Dates, guests, promo
* code, a manual price adjustment and the guest's contact data can be changed; the price is calculated again,
* the contract draft is generated and the guest receives it with a signed link to accept or decline.
* Sending again replaces the previous offer (links of older versions stop working).
*/
class SendOffer
{
public function __construct(
private PriceCalculator $calculator,
private AvailabilityChecker $availability,
private RentalContract $contract,
) {}
/**
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, guest?: array<string, ?string>} $changes
*
* @throws QuoteException
* @throws ReservationException
*/
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
{
if ($sendMail && blank($booking->guest?->email)) {
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
}
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
}
DB::transaction(function () use ($booking, $changes): void {
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
throw ReservationException::notAvailable();
}
$promoCode = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
$quote = $this->quoteWithAdjustment($booking, $stay, $adjustment, $adjustmentLabel);
if (filled($changes['guest'] ?? null)) {
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
}
$booking->update([
'status' => BookingStatus::OfferSent,
'arrival' => $arrival->toDateString(),
'departure' => $departure->toDateString(),
'guests' => $stay->guests,
'promo_code' => $quote->promoCodeApplied ? $promoCode : null,
'price_adjustment' => $adjustment !== 0 ? $adjustment : null,
'price_adjustment_label' => $adjustment !== 0 ? $adjustmentLabel : null,
'quote' => $quote->toArray(),
'total' => $quote->total(),
'deposit' => $quote->deposit(),
'balance_due_on' => $quote->balanceDueOn->toDateString(),
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->property->hold_hours),
'offer_version' => $booking->offer_version + 1,
'offer_sent_at' => now(),
'offer_message' => $changes['offer_message'] ?? null,
]);
});
$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)));
}
return $booking;
}
/**
* The guest's link to the offer page; valid while the offer is valid and only for this offer version.
*/
public function offerUrl(Booking $booking): string
{
$parameters = ['booking' => $booking, 'v' => $booking->offer_version];
return $booking->website()?->temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters)
?? URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters);
}
/**
* Price for the (possibly changed) stay plus the manual adjustment; a reduction never makes the stay negative.
*
* @throws QuoteException
*/
private function quoteWithAdjustment(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
{
$quote = $this->calculator->calculate($booking->property, $stay);
if ($adjustment === 0) {
return $quote;
}
$adjustment = max($adjustment, -$quote->rent());
return $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $adjustment, $adjustment));
}
}
+2 -1
View File
@@ -7,6 +7,7 @@
use App\Mail\NewReview;
use App\Models\Booking;
use App\Models\Review;
use App\Support\Settings;
use Illuminate\Support\Facades\Mail;
use RuntimeException;
@@ -32,7 +33,7 @@ public function handle(Booking $booking, array $data): Review
'stayed_on' => $booking->arrival,
]);
Mail::to(config('fewo.notification_email'))->send(new NewReview($review));
Mail::to(Settings::notificationRecipients())->send(new NewReview($review));
return $review;
}
+151
View File
@@ -0,0 +1,151 @@
<?php
namespace App\Actions;
use App\Channels\ChannelSyncException;
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Enums\ChannelEchoBehavior;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
class SyncChannel
{
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
public function handle(Channel $channel): ChannelSyncLog
{
$startedAt = microtime(true);
$lock = Cache::lock("channel-sync:{$channel->tenant_id}:{$channel->id}", 120);
if (! $lock->get()) {
return $channel->syncLogs()->create(['successful' => false, 'message' => 'Für diesen Kanal läuft bereits ein Abgleich.']);
}
try {
$channel->refresh();
if (! $channel->importsOccupations()) {
return $channel->syncLogs()->create(['successful' => false, 'message' => 'Import ist pausiert oder noch nicht eingerichtet.']);
}
$importUrl = $channel->setting('import_url');
$periods = $channel->connector()->fetchOccupations($channel);
$suffix = config('channels.uid_suffix');
if (! is_string($suffix) || $suffix === '') {
throw new ChannelSyncException('Der UID-Echofilter ist nicht eingerichtet.');
}
$today = CarbonImmutable::today();
$periods = array_values(array_filter($periods, fn (ExternalPeriod $period): bool => $period->endsOn->greaterThan($today) && ! str_ends_with($period->uid, $suffix)));
$counts = ['added' => 0, 'changed' => 0, 'removed' => 0];
$warnings = [];
$conflicts = [];
DB::transaction(function () use ($channel, $periods, $importUrl, $today, &$counts, &$warnings, &$conflicts): void {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
if (! $locked->importsOccupations() || $locked->setting('import_url') !== $importUrl) {
throw new ChannelSyncException('Die Kanalkonfiguration wurde während des Abrufs geändert.');
}
Property::query()->whereKey($channel->property_id)->lockForUpdate()->firstOrFail();
$rows = $channel->blockedPeriods()->withTrashed()->where('source', 'channel')->get();
if ($rows->groupBy('external_uid')->contains(fn ($group): bool => $group->count() > 1) || $rows->contains(fn (BlockedPeriod $block): bool => blank($block->external_uid))) {
throw new ChannelSyncException('Vorhandene Kalender-Dubletten oder fehlende UIDs benötigen eine manuelle Prüfung. Der Bestand bleibt erhalten.');
}
$existing = $rows->keyBy('external_uid');
$emails = $channel->blockedPeriods()->where('source', 'email')->get();
$seen = [];
foreach ($periods as $period) {
$seen[$period->uid] = true;
$block = $existing->get($period->uid);
$matchedMail = $block ? null : $emails->firstWhere('external_uid', 'email:'.$period->uid);
$attributes = ['property_id' => $channel->property_id, 'starts_on' => $period->startsOn->toDateString(),
'ends_on' => $period->endsOn->toDateString(), 'reason' => $channel->name, 'source' => 'channel',
'external_uid' => $period->uid, 'missing_imports' => 0];
$interpretation = $period->properties !== [] ? app(ApplyChannelRules::class)->attributes($locked, $block ?? $matchedMail, $period->properties) : [];
if ($matchedMail) {
$block = $matchedMail;
$block->update($attributes);
$emails = $emails->reject(fn (BlockedPeriod $mail): bool => $mail->is($block));
$counts['changed']++;
} elseif ($block) {
if ($block->trashed()) {
$block->fill($attributes)->restore();
$counts['added']++;
} elseif (! $block->starts_on->equalTo($period->startsOn) || ! $block->ends_on->equalTo($period->endsOn)) {
$block->update($attributes);
$counts['changed']++;
} elseif ($block->missing_imports !== 0) {
$block->forceFill(['missing_imports' => 0])->saveQuietly();
}
} else {
$overlap = $channel->property->blockedPeriods()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists()
|| $channel->property->bookings()->occupying()->overlapping($period->startsOn, $period->endsOn)->exists();
$attributes['export_approved'] = ! $overlap && $locked->echo_behavior !== ChannelEchoBehavior::Reexports;
$block = new BlockedPeriod($attributes);
$block->forceFill($interpretation);
$channel->blockedPeriods()->save($block);
$counts['added']++;
}
if ($period->properties !== []) {
app(ApplyChannelRules::class)->store($block, [...$interpretation, 'ical_properties' => $period->properties, 'ical_raw' => $period->raw]);
}
$existing->put($period->uid, $block);
}
$missing = $rows->filter(fn (BlockedPeriod $block): bool => ! $block->trashed() && ! isset($seen[$block->external_uid]) && $block->ends_on->greaterThan($today));
if ($missing->count() > config('channels.max_automatic_removals', 5)) {
$warnings[] = 'Ungewöhnlich viele Ereignisse fehlen. Keine automatische Entfernung; Portalkalender persönlich prüfen.';
foreach ($missing as $block) {
$block->forceFill(['needs_review' => true, 'review_note' => end($warnings)])->saveQuietly();
}
} else {
foreach ($missing as $block) {
$block->increment('missing_imports');
if ($block->missing_imports >= config('channels.removal_confirmation_runs', 2)) {
$block->delete();
$counts['removed']++;
} else {
$warnings[] = 'Fehlende Ereignisse bleiben bis zum nächsten bestätigenden Kalenderstand gesperrt.';
}
}
}
app(ReconcileChannelRepresentations::class)->handle($channel->property);
foreach ($channel->blockedPeriods()->with(['canonicalBlock', 'linkedBooking'])->where('source', 'channel')->whereIn('external_uid', array_keys($seen))->get() as $block) {
$overlap = $channel->blockedPeriods()->occupying()->overlapping($block->starts_on, $block->ends_on)->whereKeyNot($block->id)->exists();
$foundConflicts = $block->is_representation ? [] : $this->conflictDetector->conflictsFor($block);
$linked = $block->canonicalBlock ?? $block->linkedBooking;
$linkedStart = $linked instanceof Booking ? $linked->arrival : $linked?->starts_on;
$linkedEnd = $linked instanceof Booking ? $linked->departure : $linked?->ends_on;
$representationChanged = $block->is_representation && ($linked === null || ! $block->starts_on->equalTo($linkedStart) || ! $block->ends_on->equalTo($linkedEnd));
if ($representationChanged || (! $block->is_representation && $block->reviewed_at === null && ($overlap || $emails->isNotEmpty() || $foundConflicts !== [] || ! $block->export_approved))) {
$note = ReconcileChannelRepresentations::OVERLAP_NOTE;
$block->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly();
foreach ($emails as $mailBlock) {
$mailBlock->forceFill(['needs_review' => true, 'review_note' => $note])->saveQuietly();
}
$warnings[] = $note;
}
foreach ($foundConflicts as $conflict) {
$conflicts[$conflict] ??= $block->starts_on;
}
}
$warnings = array_values(array_unique($warnings));
$locked->forceFill(['last_synced_at' => now(), 'last_success_at' => now(), 'last_error' => null,
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
});
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
'conflicts' => count($conflicts), 'warnings' => $warnings,
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
} catch (ChannelSyncException $exception) {
$channel->forceFill(['last_synced_at' => now(), 'last_error_at' => now(), 'last_error' => $exception->getMessage()])->save();
return $channel->syncLogs()->create(['successful' => false, 'message' => $exception->getMessage(),
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
} finally {
$lock->release();
}
}
}
+2 -2
View File
@@ -21,7 +21,7 @@ public function isAvailable(Property $property, CarbonImmutable $from, CarbonImm
->when($ignore, fn ($query) => $query->whereKeyNot($ignore->getKey()))
->exists();
return ! $bookingConflict && ! $property->blockedPeriods()->overlapping($from, $until)->exists();
return ! $bookingConflict && ! $property->blockedPeriods()->occupying()->overlapping($from, $until)->exists();
}
/**
@@ -33,7 +33,7 @@ public function occupiedNights(Property $property, CarbonImmutable $from, Carbon
{
$periods = $property->bookings()->occupying()->overlapping($from, $until)->get(['arrival', 'departure'])
->map(fn (Booking $booking): array => [$booking->arrival, $booking->departure])
->concat($property->blockedPeriods()->overlapping($from, $until)->get(['starts_on', 'ends_on'])
->concat($property->blockedPeriods()->occupying()->overlapping($from, $until)->get(['starts_on', 'ends_on'])
->map(fn (BlockedPeriod $period): array => [$period->starts_on, $period->ends_on]));
$nights = [];
+87
View File
@@ -0,0 +1,87 @@
<?php
namespace App\Availability;
use App\Models\Property;
use Carbon\CarbonImmutable;
/**
* Free gaps in the calendar: runs of free nights with an occupied night (booking or block) directly
* before and after. Open-ended free periods (nothing booked behind them yet) are not gaps.
*/
class GapFinder
{
/** How far around a stay we look for the neighbouring occupations. */
private const LOOKAROUND_NIGHTS = 60;
public function __construct(private AvailabilityChecker $availability = new AvailabilityChecker) {}
/**
* Length in nights of the gap that contains the whole stay, or null if the stay is not inside a gap
* (because a night is occupied or the free period is not closed on both sides).
*/
public function gapContaining(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): ?int
{
$from = $arrival->subDays(self::LOOKAROUND_NIGHTS);
$until = $departure->addDays(self::LOOKAROUND_NIGHTS);
$occupied = $this->availability->occupiedNights($property, $from, $until);
for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) {
if (isset($occupied[$night->toDateString()])) {
return null;
}
}
$start = $arrival;
while (! isset($occupied[$start->subDay()->toDateString()])) {
$start = $start->subDay();
if ($start->lessThanOrEqualTo($from)) {
return null;
}
}
$end = $departure;
while (! isset($occupied[$end->toDateString()])) {
$end = $end->addDay();
if ($end->greaterThanOrEqualTo($until)) {
return null;
}
}
return (int) $start->diffInDays($end);
}
/**
* Gaps of 1 … $maxNights nights starting within [$from, $until), as [arrival, departure] pairs.
*
* @return list<array{0: CarbonImmutable, 1: CarbonImmutable}>
*/
public function gaps(Property $property, CarbonImmutable $from, CarbonImmutable $until, int $maxNights): array
{
$occupied = $this->availability->occupiedNights($property, $from->subDay(), $until->addDays($maxNights + 1));
$gaps = [];
$night = $from;
while ($night->lessThan($until)) {
$isGapStart = ! isset($occupied[$night->toDateString()]) && isset($occupied[$night->subDay()->toDateString()]);
if (! $isGapStart) {
$night = $night->addDay();
continue;
}
$end = $night;
while (! isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
$end = $end->addDay();
}
if (isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
$gaps[] = [$night, $end];
}
$night = $end->addDay();
}
return $gaps;
}
}
+103
View File
@@ -0,0 +1,103 @@
<?php
namespace App\Availability;
use App\Models\Property;
use App\Pricing\PriceCalculator;
use App\Pricing\PriceQuote;
use App\Pricing\QuoteException;
use App\Pricing\StayRequest;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
/**
* The next bookable stays from tomorrow on, for the "next free dates" in the hero section: free nights
* that the PriceCalculator accepts (minimum stay, offers applied), at least $nights long, not overlapping.
* Cached briefly per apartment because each candidate is a full price calculation (dates as strings: the cache
* does not unserialize objects).
*/
class NextFreeStays
{
public const HORIZON_DAYS = 120;
public const MAX_NIGHTS = 7;
public function __construct(
private AvailabilityChecker $availability,
private PriceCalculator $calculator,
) {}
/**
* @return list<array{arrival: CarbonImmutable, departure: CarbonImmutable, nights: int, total: int, url: string}>
*/
public function for(Property $property, int $count = 3, int $nights = 3, int $guests = 2): array
{
$key = "next-free-stays:{$property->id}:{$count}:{$nights}:{$guests}:".today()->toDateString();
$stays = Cache::remember($key, now()->addMinutes(10), fn (): array => $this->find($property, $count, $nights, min($guests, $property->max_guests)));
return array_map(fn (array $stay): array => [
...$stay,
'arrival' => CarbonImmutable::parse($stay['arrival']),
'departure' => CarbonImmutable::parse($stay['departure']),
], $stays);
}
/**
* @return list<array{arrival: string, departure: string, nights: int, total: int, url: string}>
*/
private function find(Property $property, int $count, int $nights, int $guests): array
{
$from = CarbonImmutable::tomorrow();
$until = $from->addDays(self::HORIZON_DAYS + self::MAX_NIGHTS);
$occupied = $this->availability->occupiedNights($property, $from, $until);
$stays = [];
for ($arrival = $from; count($stays) < $count && $arrival->lessThan($from->addDays(self::HORIZON_DAYS)); $arrival = $arrival->addDay()) {
if (isset($occupied[$arrival->toDateString()])) {
continue;
}
$quote = $this->firstPricedStay($property, $arrival, $nights, $guests, $occupied);
if ($quote === null) {
continue;
}
$stays[] = [
'arrival' => $quote->arrival->toDateString(),
'departure' => $quote->departure->toDateString(),
'nights' => $quote->nights(),
'total' => $quote->total(),
'url' => route('booking.create', ['anreise' => $quote->arrival->toDateString(), 'abreise' => $quote->departure->toDateString(), 'personen' => $guests]),
];
$arrival = $quote->departure->subDay();
}
return $stays;
}
/**
* The shortest stay of at least $nights from $arrival that is free and priceable, if any.
*
* @param array<string, true> $occupied
*/
private function firstPricedStay(Property $property, CarbonImmutable $arrival, int $nights, int $guests, array $occupied): ?PriceQuote
{
for ($length = 1; $length <= self::MAX_NIGHTS; $length++) {
if (isset($occupied[$arrival->addDays($length - 1)->toDateString()])) {
return null;
}
if ($length < $nights) {
continue;
}
try {
return $this->calculator->calculate($property, new StayRequest($arrival, $arrival->addDays($length), $guests));
} catch (QuoteException) {
continue;
}
}
return null;
}
}
+105
View File
@@ -0,0 +1,105 @@
<?php
namespace App\Availability;
use App\Enums\BookingStatus;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Guests\GuestResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Property;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
class OccupancyOverview
{
/**
* One read model over local booking workflows and their external calendar counterparts.
* Source records retain their identities; linked representations never become a second stay.
*
* @return Collection<int|string, array<string, mixed>>
*/
public function records(?int $propertyId = null, ?int $guestId = null, bool $includeBlocks = false, ?CarbonImmutable $from = null, ?CarbonImmutable $until = null): Collection
{
Gate::authorize('viewAny', Booking::class);
$representations = ['channelRepresentations' => fn ($query) => $query->select(['id', 'channel_id', 'canonical_block_id', 'linked_booking_id'])->with('channel:id,name')];
$bookings = Booking::query()->with(['guest', 'property', 'originChannel', 'importChannel'])->with($representations)->withCount('channelRepresentations')
->when($propertyId, fn ($query) => $query->where('property_id', $propertyId))
->when($guestId, fn ($query) => $query->where('guest_id', $guestId))
->when($from, fn ($query) => $query->whereDate('departure', '>=', $from))
->when($until, fn ($query) => $query->whereDate('arrival', '<', $until))
->get();
$records = collect();
foreach ($bookings as $booking) {
$records->put($booking->id, [
'record_type' => 'booking', 'record_id' => $booking->id, 'reference' => $booking->reference,
'kind' => 'booking', 'kind_label' => 'Anfrage / Buchung',
'property_id' => $booking->property_id, 'property' => $booking->property->name,
'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(),
'nights' => $booking->nights(), 'persons' => $booking->guests, 'total' => $booking->total,
'guest_id' => $booking->guest_id, 'guest' => $booking->guest?->full_name ?? 'Gastzuordnung offen',
'guest_email' => $booking->guest?->email, 'guest_assigned' => $booking->guest_id !== null,
'source' => $booking->bookingChannelLabel(), 'status' => $booking->status->getLabel(),
'status_key' => $booking->status->value, 'color' => $booking->status->getColor(),
'occupies' => in_array($booking->status, BookingStatus::occupying(), true) || $booking->isHoldActive(),
'needs_review' => false, 'review_note' => null, 'reason' => null, 'archived' => false,
'representations' => $booking->channel_representations_count,
'mirrored_channels' => $booking->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
'url' => BookingResource::getUrl('view', ['record' => $booking->id]),
'guest_url' => $booking->guest_id ? GuestResource::getUrl('edit', ['record' => $booking->guest_id]) : null,
]);
}
$blocks = BlockedPeriod::query()->select(['id', 'tenant_id', 'property_id', 'guest_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'occupation_kind', 'block_purpose', 'block_note', 'is_private', 'ical_event_type', 'ical_interpretation', 'is_representation', 'needs_review', 'review_note', 'deleted_at'])->withTrashed()->occupying()->with(['guest', 'property', 'channel', 'originChannel'])->with($representations)->withCount('channelRepresentations')
->when(! $includeBlocks, fn ($query) => $query->reservations())
->when($propertyId, fn ($query) => $query->where('property_id', $propertyId))
->when($guestId, fn ($query) => $query->where('guest_id', $guestId)->reservations())
->when($from, fn ($query) => $query->whereDate('ends_on', '>=', $from))
->when($until, fn ($query) => $query->whereDate('starts_on', '<', $until))
->get();
foreach ($blocks as $block) {
$kind = $block->occupationKind();
$records->put('portal-'.$block->id, [
'record_type' => 'portal', 'record_id' => $block->id,
'reference' => $block->ical_interpretation['fields']['booking_reference'] ?? 'Kalender-'.$block->id,
'kind' => $kind->value, 'kind_label' => $kind->getLabel(),
'property_id' => $block->property_id, 'property' => $block->property->name,
'arrival' => $block->starts_on->toDateString(), 'departure' => $block->ends_on->toDateString(),
'nights' => (int) $block->starts_on->diffInDays($block->ends_on), 'persons' => null, 'total' => null,
'guest_id' => $block->guest_id, 'guest' => $block->guestName() ?? 'Gastzuordnung offen',
'guest_email' => $block->guest?->email, 'guest_assigned' => $block->guest_id !== null,
'source' => $block->bookingChannelLabel(),
'status' => $block->trashed() ? 'Nicht mehr im Kalenderfeed' : ($block->needs_review ? 'Klärung erforderlich' : 'Im Kalender geführt'),
'status_key' => $block->trashed() ? 'archived' : 'imported', 'color' => $block->needs_review ? 'warning' : $kind->getColor(),
'occupies' => ! $block->trashed(), 'needs_review' => $block->needs_review, 'review_note' => $block->review_note, 'reason' => $block->blockDescription(),
'archived' => $block->trashed(), 'representations' => $block->channel_representations_count,
'mirrored_channels' => $block->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]),
'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null,
]);
}
return $records;
}
/** @return array{month: CarbonImmutable, days: array, rows: Collection, free: int, occupied: int} */
public function calendar(Property $property, CarbonImmutable $month): array
{
$month = $month->startOfMonth();
$until = $month->addMonth();
$records = $this->records($property->id, includeBlocks: true, from: $month, until: $until);
$occupying = $records->where('occupies', true);
$days = [];
for ($date = $month; $date->lessThan($until); $date = $date->addDay()) {
$day = $date->toDateString();
$nights = $occupying->filter(fn (array $record): bool => $record['arrival'] <= $day && $day < $record['departure']);
$departures = $occupying->where('departure', $day);
$days[] = ['date' => $date, 'free' => $nights->isEmpty(), 'occupations' => $nights->values()->all(), 'departures' => $departures->values()->all(), 'overlap' => $nights->count() > 1];
}
$free = collect($days)->where('free', true)->count();
return ['month' => $month, 'days' => $days, 'rows' => $records->sortBy('arrival'), 'free' => $free, 'occupied' => count($days) - $free];
}
}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Channels;
use App\Channels\Contracts\ChannelConnector;
use InvalidArgumentException;
/**
* Resolves the connectors registered in config/channels.php.
*/
class ChannelRegistry
{
/**
* @return array<string, class-string<ChannelConnector>>
*/
public function connectors(): array
{
return collect(config('channels.connectors'))
->mapWithKeys(fn (string $class): array => [$class::key() => $class])
->all();
}
public function resolve(string $key): ChannelConnector
{
$class = $this->connectors()[$key] ?? throw new InvalidArgumentException("Unknown channel connector [{$key}].");
return app($class);
}
/**
* @return array<string, string>
*/
public function options(): array
{
return array_map(fn (string $class): string => $class::label(), $this->connectors());
}
}
+7
View File
@@ -0,0 +1,7 @@
<?php
namespace App\Channels;
use RuntimeException;
class ChannelSyncException extends RuntimeException {}
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Channels;
use App\Models\BlockedPeriod;
use App\Models\Booking;
/**
* Finds occupations from other sources that overlap a block reported by a portal
* (a possible double booking). Blocks of the same portal never conflict with each other.
*/
class ConflictDetector
{
/**
* @return list<string> human readable descriptions
*/
public function conflictsFor(BlockedPeriod $block): array
{
$property = $block->property;
$channelName = $block->channel->name ?? 'Sperre';
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
$blocks = $property->blockedPeriods()
->occupying()
->overlapping($block->starts_on, $block->ends_on)
->whereKeyNot($block->getKey())
->when($block->channel_id, fn ($query) => $query->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $block->channel_id)))
->with('channel')
->get()
->map(fn (BlockedPeriod $other): string => "{$channelName} meldet {$period}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})");
return [...$bookings->all(), ...$blocks->all()];
}
}
@@ -0,0 +1,42 @@
<?php
namespace App\Channels\Contracts;
use App\Channels\ChannelSyncException;
use App\Channels\ExternalPeriod;
use App\Models\Channel;
use Filament\Schemas\Components\Component;
/**
* Connects one kind of portal or channel manager. Register implementations in config/channels.php.
*/
interface ChannelConnector
{
/**
* Stable identifier stored on the channel, e.g. "ical".
*/
public static function key(): string;
public static function label(): string;
/**
* Admin form fields for the connector's settings; use state paths below "settings.".
*
* @return list<Component>
*/
public static function settingsSchema(): array;
/**
* Whether occupations can currently be imported (e.g. an import URL is configured).
*/
public function canImport(Channel $channel): bool;
/**
* All occupations the portal currently reports.
*
* @return list<ExternalPeriod>
*
* @throws ChannelSyncException
*/
public function fetchOccupations(Channel $channel): array;
}
+20
View File
@@ -0,0 +1,20 @@
<?php
namespace App\Channels;
use Carbon\CarbonImmutable;
/**
* An occupation reported by a portal: nights from startsOn up to (excluding) endsOn.
*/
final readonly class ExternalPeriod
{
public function __construct(
public string $uid,
public CarbonImmutable $startsOn,
public CarbonImmutable $endsOn,
public ?string $summary = null,
public array $properties = [],
public ?string $raw = null,
) {}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Channels\ICal;
class ICalAnalysis
{
/** @return array<string, mixed> */
public function summarize(array $document): array
{
$events = [];
$fields = [];
$engine = new ICalRuleEngine;
foreach ($document['events'] as $event) {
$period = $event['period'];
$events[] = ['uid' => $event['uid'], 'properties' => $event['properties'], 'raw' => $event['raw'],
'starts_on' => $period?->startsOn->toDateString(), 'ends_on' => $period?->endsOn->toDateString(), 'occupying' => $period !== null];
foreach (array_keys($event['properties']) as $field) {
$fields[$field] ??= ['count' => 0, 'values' => [], 'patterns' => []];
$fields[$field]['count']++;
foreach (array_unique($engine->values($event['properties'], $field)) as $value) {
$fields[$field]['values'][$value] = ($fields[$field]['values'][$value] ?? 0) + 1;
$pattern = $value;
foreach ([' - ', ': ', ' / '] as $delimiter) {
if (($position = mb_strpos($value, $delimiter)) !== false) {
$pattern = mb_substr($value, 0, $position + mb_strlen($delimiter)).'…';
break;
}
}
$fields[$field]['patterns'][$pattern] = ($fields[$field]['patterns'][$pattern] ?? 0) + 1;
}
}
}
ksort($fields);
foreach ($fields as &$field) {
arsort($field['values']);
arsort($field['patterns']);
$field['values'] = array_slice($field['values'], 0, 10, true);
$field['patterns'] = array_slice($field['patterns'], 0, 10, true);
}
return ['count' => count($events), 'events' => $events, 'fields' => $fields, 'calendar' => $document['calendar']];
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Channels\ICal;
use App\Channels\ChannelSyncException;
use App\Channels\Contracts\ChannelConnector;
use App\Models\Channel;
use Filament\Forms\Components\TextInput;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\RequestException;
use Illuminate\Support\Facades\Http;
/**
* Generic calendar connection that works with almost every portal: we read the portal's iCal export
* and the portal reads our feed for this channel.
*/
class ICalConnector implements ChannelConnector
{
public function __construct(private ICalParser $parser) {}
public static function key(): string
{
return 'ical';
}
public static function label(): string
{
return 'Kalender-Abgleich (iCal)';
}
public static function settingsSchema(): array
{
return [
TextInput::make('settings.import_url')
->label('Importadresse: iCal-Export des externen Portals')
->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.')
->url()
->password()
->revealable()
->maxLength(2048),
];
}
public function canImport(Channel $channel): bool
{
return filled($channel->setting('import_url'));
}
public function fetchOccupations(Channel $channel): array
{
return $this->parser->parse($this->fetchCalendar($channel));
}
/** @return array{events: list<array>, calendar: array} */
public function fetchDocument(Channel $channel): array
{
return $this->parser->parseDocument($this->fetchCalendar($channel));
}
private function fetchCalendar(Channel $channel): string
{
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
try {
$response = Http::timeout(20)
->retry(2, 1000)
->withHeaders(['Accept' => 'text/calendar'])
->get($url)
->throw();
} catch (ConnectionException|RequestException $exception) {
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden. Netzwerkverbindung und Portaladresse prüfen.', previous: $exception);
}
return $response->body();
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Channels\ICal;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
class ICalExport
{
public function __construct(private ICalFeed $feed, private ICalParser $parser) {}
public function build(Channel $channel, string $method = 'GET', ?string $userAgent = null): ?string
{
$requestedAt = now();
return DB::transaction(function () use ($channel, $method, $userAgent, $requestedAt): ?string {
$locked = Channel::query()->whereKey($channel->id)->lockForUpdate()->firstOrFail();
if ($locked->exportsOccupations()) {
$body = $this->feed->build($locked);
$this->parser->parse($body);
$locked->forceFill(['export_snapshot' => $body, 'export_snapshot_at' => now()]);
}
$lastRequest = $locked->last_export_requested_at;
$locked->forceFill(['last_export_requested_at' => $lastRequest?->greaterThan($requestedAt) ? $lastRequest : $requestedAt])->saveQuietly();
$userAgent = str_replace(array_filter([$locked->export_token, $locked->previous_export_token]), '[Token entfernt]', $userAgent ?? '');
$locked->exportRequests()->create([
'requested_at' => $requestedAt,
'method' => $method,
'user_agent' => filled($userAgent) ? mb_substr(str_replace(["\r", "\n"], ' ', $userAgent), 0, 512) : null,
'response_status' => $locked->export_snapshot === null ? 503 : 200,
'export_state' => $locked->export_snapshot === null ? 'unavailable' : ($locked->exportsOccupations() ? 'live' : 'frozen'),
]);
$expired = $locked->exportRequests()->skip(max(1, (int) config('channels.export_request_history_limit', 100)))->take(1000)->pluck('id');
if ($expired->isNotEmpty()) {
$locked->exportRequests()->whereIn('id', $expired)->delete();
}
return $locked->export_snapshot;
});
}
}
+62
View File
@@ -0,0 +1,62 @@
<?php
namespace App\Channels\ICal;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
class ICalExportFields
{
public const FIELDS = ['occupation_label' => 'Belegungsbeschreibung', 'guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'note' => 'Zusätzliche Textinformation', 'property_name' => 'Wohnungsname', 'channel_name' => 'Bekannter Ursprung / Importkanal', 'arrival' => 'Anreise', 'departure' => 'Abreise', 'nights' => 'Anzahl Nächte'];
public const ICAL_FIELDS = ['SUMMARY' => 'SUMMARY – Bezeichnung', 'DESCRIPTION' => 'DESCRIPTION – Beschreibung', 'LOCATION' => 'LOCATION – Ort / Wohnung'];
/** @return array<string, string> */
public function properties(Channel $channel, Booking|BlockedPeriod $occupation): array
{
$context = $this->context($occupation);
if (! $channel->ical_export_names) {
unset($context['guest_first_name'], $context['guest_full_name']);
}
$properties = ['SUMMARY' => 'Belegt'];
foreach ($channel->ical_export_mapping ?? [] as $mapping) {
if (! isset(self::ICAL_FIELDS[$mapping['field'] ?? ''])) {
continue;
}
$parts = [];
foreach ($mapping['items'] ?? [] as $item) {
if (isset(self::FIELDS[$item]) && filled($context[$item] ?? null)) {
$parts[] = $context[$item];
}
}
if ($parts !== []) {
$properties[$mapping['field']] = implode($mapping['separator'] ?? ' – ', $parts);
}
}
return $properties;
}
/** @return array<string, string|null> */
public function context(Booking|BlockedPeriod $occupation): array
{
$booking = $occupation instanceof Booking;
$start = $booking ? $occupation->arrival : $occupation->starts_on;
$end = $booking ? $occupation->departure : $occupation->ends_on;
$context = ['occupation_label' => $booking ? 'Buchung' : (ICalRuleEngine::TYPES[$occupation->ical_event_type] ?? 'Belegt'),
'property_name' => $occupation->property->name, 'arrival' => $start->format('d.m.Y'), 'departure' => $end->format('d.m.Y'),
'nights' => (string) (int) $start->diffInDays($end),
'channel_name' => $booking ? null : ($occupation->originChannel?->name ?? $occupation->channel?->name)];
if ($booking) {
return [...$context, 'guest_first_name' => $occupation->guest?->first_name, 'guest_full_name' => $occupation->guest?->full_name, 'booking_reference' => $occupation->reference];
}
$fields = array_intersect_key($occupation->ical_interpretation['fields'] ?? [], self::FIELDS);
if ($occupation->guest !== null) {
$fields['guest_first_name'] = $occupation->guest->anonymized_at === null ? $occupation->guest->first_name : null;
$fields['guest_full_name'] = $occupation->guest->anonymized_at === null && filled($occupation->guest->last_name) ? $occupation->guest->full_name : null;
}
return [...$context, ...$fields];
}
}
+99
View File
@@ -0,0 +1,99 @@
<?php
namespace App\Channels\ICal;
use App\Enums\ChannelExportMode;
use App\Models\Booking;
use App\Models\Channel;
use Carbon\CarbonImmutable;
use Carbon\CarbonInterface;
/**
* The calendar a portal imports from us: every occupation of the property except the ones that
* came from this very portal (otherwise the portal would block its own bookings twice).
* Events carry no guest data.
*/
class ICalFeed
{
public function build(Channel $channel): string
{
$property = $channel->property;
$from = CarbonImmutable::today()->subDays(30);
$until = CarbonImmutable::today()->addYears(2);
$suffix = config('channels.uid_suffix');
$events = [];
$bookings = $property->bookings()->occupying()->overlapping($from, $until);
if ($channel->export_mode === ChannelExportMode::Test) {
$bookings->whereNull('import_channel_id')->whereNull('origin_channel_id')->whereIn('source', Booking::DIRECT_SOURCES);
} else {
$bookings->where(fn ($query) => $query->whereNull('import_channel_id')->orWhere('import_channel_id', '!=', $channel->id))
->where(fn ($query) => $query->whereNull('origin_channel_id')->orWhere('origin_channel_id', '!=', $channel->id));
}
foreach ($bookings->with(['guest', 'property'])->orderBy('id')->get() as $booking) {
/** @var Booking $booking */
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at, (new ICalExportFields)->properties($channel, $booking));
}
$blocks = $property->blockedPeriods()
->occupying()->where('export_approved', true)
->overlapping($from, $until)
->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $channel->id))
->where(fn ($query) => $query->whereNull('origin_channel_id')->orWhere('origin_channel_id', '!=', $channel->id));
if ($channel->export_mode === ChannelExportMode::Test) {
$blocks->whereNull('channel_id')->whereNull('origin_channel_id')->where('source', 'manual');
}
foreach ($blocks->with(['property', 'channel', 'originChannel', 'guest'])->orderBy('id')->get() as $block) {
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at, (new ICalExportFields)->properties($channel, $block));
}
$lines = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//Ferienwohnung Stommer//Belegung//DE',
'CALSCALE:GREGORIAN',
'METHOD:PUBLISH',
'X-WR-CALNAME:'.$this->escape($property->name),
...$events,
'END:VCALENDAR',
];
return implode("\r\n", array_map(fn (string $line): string => $this->fold($line), explode("\r\n", implode("\r\n", $lines))))."\r\n";
}
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified, array $properties): string
{
return implode("\r\n", [
'BEGIN:VEVENT',
"UID:{$uid}",
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
...array_map(fn (string $field, string $value): string => $field.':'.$this->escape($value), array_keys($properties), array_values($properties)),
'TRANSP:OPAQUE',
'END:VEVENT',
]);
}
private function escape(string $text): string
{
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], str_replace(["\r\n", "\r"], "\n", $text));
}
private function fold(string $line): string
{
$parts = [];
$limit = 75;
while (strlen($line) > $limit) {
$part = mb_strcut($line, 0, $limit, 'UTF-8');
$parts[] = $part;
$line = substr($line, strlen($part));
$limit = 74;
}
$parts[] = $line;
return implode("\r\n ", $parts);
}
}
+244
View File
@@ -0,0 +1,244 @@
<?php
namespace App\Channels\ICal;
use App\Channels\ChannelSyncException;
use App\Channels\ExternalPeriod;
use Carbon\CarbonImmutable;
use Throwable;
/** Complete non-recurring availability snapshots; damaged feeds never become deletions. */
class ICalParser
{
/** @return list<ExternalPeriod> */
public function parse(string $ics): array
{
return array_values(array_filter(array_column($this->parseDocument($ics)['events'], 'period')));
}
/** @return array{events: list<array>, calendar: array} */
public function parseDocument(string $ics): array
{
if (str_starts_with($ics, "\xEF\xBB\xBF")) {
$ics = substr($ics, 3);
}
$ics = preg_replace("/\r?\n[ \t]/", '', $ics);
if (! mb_check_encoding($ics, 'UTF-8') || str_contains($ics, "\0")) {
throw new ChannelSyncException('Kalender enthält ungültige Zeichen.');
}
$lines = explode("\n", str_replace("\r\n", "\n", $ics));
$stack = [];
$calendar = [];
$event = [];
$periods = [];
$properties = [];
$eventLines = [];
$identities = [];
$propertyIdentities = [];
$started = false;
$closed = false;
foreach ($lines as $line) {
$line = rtrim($line, "\r");
if (in_array('VEVENT', $stack, true)) {
$eventLines[] = $line;
}
if ($line === '' && $stack === []) {
continue;
}
if ($closed || ! preg_match('/^((?:[^:"]|"[^"]*")*):(.*)$/D', $line, $match)) {
throw new ChannelSyncException('Kalender ist unvollständig oder enthält ungültige Inhaltszeilen.');
}
$parts = preg_split('/;(?=(?:[^"]*"[^"]*")*[^"]*$)/', $match[1]);
$name = strtoupper(array_shift($parts));
$value = $match[2];
if (! preg_match('/^[A-Z0-9-]+$/D', $name)) {
throw new ChannelSyncException('Ungültige Kalendereigenschaft.');
}
if ($name === 'BEGIN') {
$component = strtoupper($value);
if ($stack === []) {
if ($started || $component !== 'VCALENDAR') {
throw new ChannelSyncException('Die Antwort ist kein vollständiger iCal-Kalender.');
}
$started = true;
} elseif ($component === 'VCALENDAR' || ($component === 'VEVENT' && $stack !== ['VCALENDAR'])) {
throw new ChannelSyncException('Ungültig verschachtelte Kalenderkomponente.');
}
if ($stack === ['VCALENDAR'] && ! in_array($component, ['VEVENT', 'VTIMEZONE'], true)) {
throw new ChannelSyncException('Nicht unterstützte Kalenderkomponente im Belegungsfeed.');
}
if ($component === 'VEVENT') {
$event = [];
$properties = [];
$eventLines = [$line];
}
$stack[] = $component;
continue;
}
if ($name === 'END') {
if ($stack === [] || end($stack) !== strtoupper($value)) {
throw new ChannelSyncException('Kalenderkomponente ist nicht vollständig geschlossen.');
}
if (end($stack) === 'VEVENT') {
$uid = trim($event['UID']['value'] ?? '');
if ($uid === '') {
throw new ChannelSyncException('Ein Kalenderereignis hat keine eindeutige UID.');
}
$period = $this->toPeriod($event);
$identity = $period ? $period->startsOn->toDateString().'|'.$period->endsOn->toDateString() : 'not-occupying';
if (isset($identities[$uid]) && $identities[$uid] !== $identity) {
throw new ChannelSyncException('Eine UID enthält widersprüchliche Ereignisse; bitte den Portalkalender prüfen.');
}
$normalized = $properties;
ksort($normalized);
if (isset($propertyIdentities[$uid]) && $propertyIdentities[$uid] !== $normalized) {
throw new ChannelSyncException('Eine UID enthält widersprüchliche Originalangaben; bitte den Kalender prüfen.');
}
$propertyIdentities[$uid] = $normalized;
if (! isset($identities[$uid])) {
$raw = implode("\r\n", $eventLines)."\r\n";
$enriched = $period === null ? null : new ExternalPeriod($period->uid, $period->startsOn, $period->endsOn, $period->summary, $properties, $raw);
$periods[] = ['uid' => $uid, 'properties' => $properties, 'raw' => $raw, 'period' => $enriched];
}
$identities[$uid] = $identity;
}
array_pop($stack);
if ($stack === []) {
$closed = true;
}
continue;
}
if ($stack === []) {
throw new ChannelSyncException('Inhalt außerhalb des Kalenders.');
}
$property = ['value' => $value, 'params' => $parts];
if ($stack === ['VCALENDAR']) {
if (isset($calendar[$name]) && in_array($name, ['VERSION', 'PRODID', 'METHOD'], true)) {
throw new ChannelSyncException('Doppelte Kalender-Kopfdaten.');
}
$calendar[$name] = $property;
} elseif ($stack === ['VCALENDAR', 'VEVENT']) {
if (isset($event[$name]) && in_array($name, ['UID', 'DTSTART', 'DTEND', 'DTSTAMP', 'LAST-MODIFIED', 'STATUS'], true)) {
throw new ChannelSyncException('Doppelte Identitäts- oder Datumsangaben im Kalenderereignis.');
}
$event[$name] = $property;
}
if (in_array('VEVENT', $stack, true)) {
$prefix = count($stack) > 2 ? implode('.', array_slice($stack, 2)).'.' : '';
$properties[$prefix.$name][] = $property;
}
}
if (! $closed || $stack !== [] || ($calendar['VERSION']['value'] ?? '') !== '2.0' || blank($calendar['PRODID']['value'] ?? null)) {
throw new ChannelSyncException('Kalender ist unvollständig; VERSION, PRODID und geschlossene Komponenten sind erforderlich.');
}
if (isset($calendar['METHOD']) && strtoupper($calendar['METHOD']['value']) !== 'PUBLISH') {
throw new ChannelSyncException('Erwartet wird ein vollständiger Kalenderstand, keine einzelne Kalendernachricht.');
}
return ['events' => $periods, 'calendar' => $calendar];
}
public static function text(string $value): string
{
return preg_replace_callback('/\\\\([nN,;\\\\])/', fn (array $match): string => in_array($match[1], ['n', 'N'], true) ? "\n" : $match[1], $value);
}
/**
* Availability feeds may omit DTSTAMP. Validate event-level LAST-MODIFIED in its place,
* retaining the actual original properties and rejecting an invalid present DTSTAMP.
*
* @param array<string, array{value: string, params: list<string>}> $event
*/
private function toPeriod(array $event): ?ExternalPeriod
{
$stamp = $event['DTSTAMP']['value'] ?? $event['LAST-MODIFIED']['value'] ?? '';
try {
if (! preg_match('/^\d{8}T\d{6}Z$/D', $stamp) || CarbonImmutable::createFromFormat('!Ymd\THis\Z', $stamp, 'UTC')->format('Ymd\THis\Z') !== $stamp) {
throw new \RuntimeException;
}
} catch (Throwable) {
throw new ChannelSyncException('Ein Ereignis benötigt einen gültigen UTC-Zeitstempel (DTSTAMP oder ersatzweise LAST-MODIFIED).');
}
foreach (['RRULE', 'RDATE', 'EXDATE', 'RECURRENCE-ID', 'DURATION'] as $unsupported) {
if (isset($event[$unsupported])) {
throw new ChannelSyncException('Serien oder Dauerangaben werden für diesen Belegungskalender nicht unterstützt.');
}
}
if (strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
return null;
}
if (! isset($event['DTSTART'])) {
throw new ChannelSyncException('Einem Kalenderereignis fehlt die Anreise.');
}
$start = $this->toDate($event['DTSTART']);
if (! isset($event['DTEND']) && ! preg_match('/^\d{8}$/D', $event['DTSTART']['value'])) {
throw new ChannelSyncException('Zeitgebundene Ereignisse benötigen eine ausdrückliche Abreise.');
}
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start->addDay();
if (isset($event['DTEND']) && preg_match('/^\d{8}$/D', $event['DTSTART']['value']) !== preg_match('/^\d{8}$/D', $event['DTEND']['value'])) {
throw new ChannelSyncException('An- und Abreise verwenden verschiedene Datumstypen.');
}
if ($end->lessThanOrEqualTo($start)) {
throw new ChannelSyncException('Ein Kalenderereignis hat keinen positiven Übernachtungszeitraum.');
}
if (strtoupper($event['TRANSP']['value'] ?? '') === 'TRANSPARENT') {
return null;
}
$summary = $event['SUMMARY']['value'] ?? null;
return new ExternalPeriod($event['UID']['value'], $start, $end, $summary === null ? null : self::text($summary));
}
/** @param array{value: string, params: list<string>} $property */
private function toDate(array $property): CarbonImmutable
{
$value = trim($property['value']);
foreach ($property['params'] as $param) {
if (str_starts_with(strtoupper($param), 'VALUE=')) {
$type = strtoupper(trim(substr($param, 6), '"'));
if (! in_array($type, ['DATE', 'DATE-TIME'], true) || ($type === 'DATE') !== (preg_match('/^\d{8}$/D', $value) === 1)) {
throw new ChannelSyncException('Ungültiger Datumswerttyp.');
}
}
if (str_starts_with(strtoupper($param), 'TZID=') && (preg_match('/^\d{8}$/D', $value) || str_ends_with($value, 'Z'))) {
throw new ChannelSyncException('Unzulässige Kombination von Datum und Zeitzone.');
}
}
try {
if (preg_match('/^\d{8}$/D', $value)) {
$date = CarbonImmutable::createFromFormat('!Ymd', $value);
if ($date->format('Ymd') === $value) {
return $date;
}
} elseif (preg_match('/^(\d{8})T(\d{6})(Z?)$/D', $value, $match)) {
$zone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
$date = CarbonImmutable::createFromFormat('!YmdHis', $match[1].$match[2], $zone);
if ($date->format('YmdHis') === $match[1].$match[2]) {
return $date->setTimezone(config('app.timezone'))->startOfDay();
}
}
} catch (Throwable) {
throw new ChannelSyncException('Ungültiges Kalenderdatum oder unbekannte Zeitzone.');
}
throw new ChannelSyncException('Ungültiges Kalenderdatum.');
}
/** @param list<string> $params */
private function timezone(array $params): string
{
foreach ($params as $param) {
if (str_starts_with(strtoupper($param), 'TZID=')) {
$zone = trim(substr($param, 5), '"');
if (! in_array($zone, timezone_identifiers_list(), true)) {
throw new ChannelSyncException('Unbekannte Kalenderzeitzone.');
}
return $zone;
}
}
return config('app.timezone');
}
}
+149
View File
@@ -0,0 +1,149 @@
<?php
namespace App\Channels\ICal;
use App\Models\Channel;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
class ICalRuleEngine
{
public const OPERATORS = ['equals' => 'Ist gleich', 'not_equals' => 'Ist nicht gleich', 'starts_with' => 'Beginnt mit', 'ends_with' => 'Endet mit', 'contains' => 'Enthält', 'exists' => 'Ist vorhanden', 'empty' => 'Ist leer'];
public const TYPES = ['unknown' => 'Nicht erkannt', 'portal_reservation' => 'Portalreservierung', 'block' => 'Allgemeine Sperre'];
public const REPRESENTATIONS = ['unspecified' => 'Unbestimmt', 'leading_candidate' => 'Kandidat für führende Belegung', 'additional_block' => 'Zusätzliche Sperre'];
public const TARGETS = ['guest_first_name' => 'Gastvorname / Namensbestandteil', 'guest_full_name' => 'Vollständiger Gastname', 'booking_reference' => 'Buchungsreferenz', 'occupation_label' => 'Belegungsbeschreibung', 'note' => 'Zusätzliche Textinformation'];
public const EXTRACTIONS = ['whole' => 'Gesamter Text', 'after' => 'Text nach', 'before' => 'Text vor', 'between' => 'Text zwischen'];
/** @return list<string> */
public function values(array $properties, string $field): array
{
return array_map(fn (array $property): string => ICalParser::text($property['value']), $properties[$field] ?? []);
}
/** @return array<string, mixed> */
public function evaluate(Channel $channel, array $properties, ?array $rules = null): array
{
$rules = collect($rules ?? $channel->ical_active_rules ?? [])->values()
->map(fn (array $rule, int $index): array => [...$rule, '_index' => $index])
->sortBy(fn (array $rule): array => [(int) ($rule['priority'] ?? 100), $rule['_index']]);
foreach ($rules as $rule) {
if (! ($rule['enabled'] ?? true) || empty($rule['conditions'])) {
continue;
}
$matches = array_map(fn (array $condition): bool => $this->matches($properties, $condition, (bool) ($rule['case_sensitive'] ?? false)), array_values($rule['conditions']));
if (($rule['match'] ?? 'all') === 'any' ? ! in_array(true, $matches, true) : in_array(false, $matches, true)) {
continue;
}
$fields = [];
foreach ($rule['extractions'] ?? [] as $extraction) {
$value = $this->extract($this->values($properties, $extraction['field'] ?? '')[0] ?? '', $extraction);
if (isset(self::TARGETS[$extraction['target'] ?? '']) && filled($value)) {
$fields[$extraction['target']] = $value;
}
}
$origin = $rule['origin'] ?? 'unknown';
return ['matched' => true, 'rule' => $rule['name'] ?? 'Unbenannte Regel', 'rule_index' => $rule['_index'],
'event_type' => $rule['event_type'] ?? 'unknown', 'representation' => $rule['representation'] ?? 'unspecified',
'priority' => (int) ($rule['priority'] ?? 100),
'origin_channel_id' => $origin === 'current' ? $channel->id : (str_starts_with($origin, 'channel:') ? (int) substr($origin, 8) : null), 'fields' => $fields];
}
return ['matched' => false, 'rule' => null, 'event_type' => 'unknown', 'representation' => 'unspecified', 'origin_channel_id' => null, 'priority' => 0, 'fields' => []];
}
private function matches(array $properties, array $condition, bool $caseSensitive): bool
{
$field = $condition['field'] ?? '';
if ($field === '') {
return false;
}
$values = $this->values($properties, $field);
$operator = $condition['operator'] ?? 'equals';
if ($operator === 'exists') {
return array_key_exists($field, $properties);
}
if ($operator === 'empty') {
return $values === [] || collect($values)->every(fn (string $value): bool => trim($value) === '');
}
$expected = (string) ($condition['value'] ?? '');
if (! $caseSensitive) {
$expected = mb_strtolower($expected);
$values = array_map(mb_strtolower(...), $values);
}
if ($operator === 'not_equals') {
return $values !== [] && ! in_array($expected, $values, true);
}
return collect($values)->contains(fn (string $value): bool => match ($operator) {
'equals' => $value === $expected,
'starts_with' => str_starts_with($value, $expected),
'ends_with' => str_ends_with($value, $expected),
'contains' => str_contains($value, $expected),
default => false,
});
}
private function extract(string $text, array $extraction): ?string
{
$method = $extraction['method'] ?? 'whole';
if (in_array($method, ['after', 'between'], true)) {
$start = (string) ($extraction['start'] ?? '');
$position = $start === '' ? false : mb_strpos($text, $start);
if ($position === false) {
return null;
}
$text = mb_substr($text, $position + mb_strlen($start));
}
if (in_array($method, ['before', 'between'], true)) {
$end = (string) ($extraction['end'] ?? '');
$position = $end === '' ? false : mb_strpos($text, $end);
if ($position === false) {
return null;
}
$text = mb_substr($text, 0, $position);
}
return trim($text);
}
/** @return list<array<string, mixed>> */
public function validate(Channel $channel, array $rules): array
{
$fields = array_keys($channel->ical_analysis['fields'] ?? []);
$origins = ['unknown', 'current', ...$channel->property->channels()->pluck('id')->map(fn ($id): string => 'channel:'.$id)->all()];
Validator::make(['rules' => $rules], [
'rules' => ['array'], 'rules.*.name' => ['required', 'string', 'max:120'],
'rules.*.enabled' => ['boolean'], 'rules.*.priority' => ['required', 'integer', 'min:0', 'max:10000'],
'rules.*.match' => ['required', Rule::in(['all', 'any'])], 'rules.*.case_sensitive' => ['boolean'],
'rules.*.conditions' => ['required', 'array', 'min:1', 'max:30'],
'rules.*.conditions.*.field' => ['required', Rule::in($fields)],
'rules.*.conditions.*.operator' => ['required', Rule::in(array_keys(self::OPERATORS))],
'rules.*.conditions.*.value' => ['nullable', 'string', 'max:2000'],
'rules.*.event_type' => ['required', Rule::in(array_keys(self::TYPES))],
'rules.*.origin' => ['required', Rule::in($origins)],
'rules.*.representation' => ['required', Rule::in(array_keys(self::REPRESENTATIONS))],
'rules.*.extractions' => ['array', 'max:20'],
'rules.*.extractions.*.field' => ['required', Rule::in($fields)],
'rules.*.extractions.*.target' => ['required', Rule::in(array_keys(self::TARGETS))],
'rules.*.extractions.*.method' => ['required', Rule::in(array_keys(self::EXTRACTIONS))],
'rules.*.extractions.*.start' => ['nullable', 'string', 'max:500'],
'rules.*.extractions.*.end' => ['nullable', 'string', 'max:500'],
])->validate();
foreach ($rules as $index => $rule) {
foreach ($rule['extractions'] ?? [] as $extraction) {
if ((in_array($extraction['method'], ['after', 'between'], true) && blank($extraction['start'] ?? null))
|| (in_array($extraction['method'], ['before', 'between'], true) && blank($extraction['end'] ?? null))) {
throw ValidationException::withMessages(['rules.'.$index.'.extractions' => 'Für die Textextraktion die benötigten Anfangs- und Endtexte angeben.']);
}
}
}
return array_values($rules);
}
}
+119
View File
@@ -0,0 +1,119 @@
<?php
namespace App\Channels\Mail;
use App\Channels\ChannelSyncException;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Throwable;
use Webklex\PHPIMAP\ClientManager;
use Webklex\PHPIMAP\Message;
/**
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
* Works without the PHP imap extension.
*/
class MailboxReader
{
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
/**
* The state of one landlord's mailbox. Without the landlord in the key, two landlords would report
* each other's last success and alerts would be raised for the wrong one.
*/
public static function key(string $base): string
{
return $base.':'.(Settings::tenant()?->id ?? 0);
}
public const LAST_ERROR_KEY = 'mailbox:last_error';
/**
* The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path
* is off for them.
*
* @return array<string, mixed>|null
*/
public static function configuration(): ?array
{
return Settings::tenant()?->mailbox();
}
public static function isConfigured(): bool
{
return self::configuration() !== null;
}
/**
* @param list<string> $senders addresses or domains
* @return list<PortalMail>
*
* @throws ChannelSyncException
*/
public function fetch(array $senders): array
{
$config = self::configuration();
if ($config === null) {
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
}
try {
$client = (new ClientManager)->make([
'host' => $config['host'],
'port' => $config['port'],
'encryption' => $config['encryption'],
'validate_cert' => true,
'username' => $config['username'],
'password' => $config['password'],
'protocol' => 'imap',
]);
$client->connect();
$folder = $client->getFolderByPath($config['folder']);
$mails = [];
foreach ($senders as $sender) {
$messages = $folder->query()
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
->whereFrom($sender)
->leaveUnread()
->get();
foreach ($messages as $message) {
$mails[] = $this->toPortalMail($message);
}
}
$client->disconnect();
} catch (Throwable $exception) {
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
}
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
Cache::forget(self::key(self::LAST_ERROR_KEY));
return $mails;
}
private function toPortalMail(Message $message): PortalMail
{
$text = $message->getTextBody();
if (trim($text) === '') {
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
}
$from = $message->getFrom()->first();
$date = $message->getDate()->first();
return new PortalMail(
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
from: (string) ($from->mail ?? ''),
subject: (string) $message->getSubject()->first(),
text: $text,
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
);
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
final readonly class ParsedPortalMail
{
public function __construct(
public PortalEmailType $type,
public ?CarbonImmutable $startsOn = null,
public ?CarbonImmutable $endsOn = null,
public ?string $reference = null,
) {}
public function hasPeriod(): bool
{
return $this->startsOn !== null && $this->endsOn !== null;
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Channels\Mail;
use Carbon\CarbonImmutable;
/**
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
*/
final readonly class PortalMail
{
public function __construct(
public string $messageId,
public string $from,
public string $subject,
public string $text,
public CarbonImmutable $receivedAt,
) {}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
namespace App\Channels\Mail;
use App\Enums\PortalEmailType;
use Carbon\CarbonImmutable;
/**
* Reads booking notifications of portals (German and English). It only extracts what it can find
* with confidence; everything else is left empty so that the e-mail is flagged for review.
*/
class PortalMailParser
{
private const CANCELLATION = ['storniert', 'stornierung', 'cancelled', 'canceled', 'cancellation', 'abgesagt'];
private const BOOKING = ['neue buchung', 'buchung bestätigt', 'buchungsbestätigung', 'reservierung bestätigt', 'sofortbuchung', 'hat gebucht', 'ist gebucht', 'new booking', 'booking confirmed', 'reservation confirmed', 'instant booking', 'you have a new reservation', 'neue reservierung'];
/** Checked before bookings: "Neue Buchungsanfrage" is not a confirmed booking. */
private const INQUIRY = ['buchungsanfrage', 'booking request', 'reservation request', 'anfrage', 'inquiry', 'enquiry'];
private const MONTHS = [
'jan' => 1, 'januar' => 1, 'january' => 1,
'feb' => 2, 'februar' => 2, 'february' => 2,
'mär' => 3, 'märz' => 3, 'mrz' => 3, 'mar' => 3, 'march' => 3,
'apr' => 4, 'april' => 4,
'mai' => 5, 'may' => 5,
'jun' => 6, 'juni' => 6, 'june' => 6,
'jul' => 7, 'juli' => 7, 'july' => 7,
'aug' => 8, 'august' => 8,
'sep' => 9, 'sept' => 9, 'september' => 9,
'okt' => 10, 'oktober' => 10, 'oct' => 10, 'october' => 10,
'nov' => 11, 'november' => 11,
'dez' => 12, 'dezember' => 12, 'dec' => 12, 'december' => 12,
];
public function parse(string $subject, string $text): ParsedPortalMail
{
$content = $this->normalize($subject."\n".$text);
$type = $this->type(mb_strtolower($subject))
?? $this->type(mb_strtolower($this->normalize($text)))
?? PortalEmailType::Unknown;
[$startsOn, $endsOn] = $this->period($content);
return new ParsedPortalMail($type, $startsOn, $endsOn, $this->reference($content));
}
/**
* The subject decides first; the body only when the subject is not conclusive.
*/
private function type(string $text): ?PortalEmailType
{
return match (true) {
$this->containsAny($text, self::CANCELLATION) => PortalEmailType::Cancellation,
$this->containsAny($text, self::INQUIRY) => PortalEmailType::Inquiry,
$this->containsAny($text, self::BOOKING) => PortalEmailType::Booking,
default => null,
};
}
/**
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function period(string $content): array
{
$dates = $this->dates($content);
$arrival = $this->dateAfterLabel($content, $dates, '/\b(anreise|ankunft|check-?in|arrival)\b/iu');
$departure = $this->dateAfterLabel($content, $dates, '/\b(abreise|check-?out|departure)\b/iu');
if ($arrival === null || $departure === null) {
[$arrival, $departure] = $this->firstPlausiblePair($dates);
}
if ($arrival === null || $departure === null || ! $this->isPlausible($arrival, $departure)) {
return [null, null];
}
return [$arrival, $departure];
}
/**
* All dates in the text with their offsets, in order of appearance.
*
* @return list<array{offset: int, date: CarbonImmutable}>
*/
private function dates(string $content): array
{
$monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS)));
$patterns = [
'/\b(?<d>\d{1,2})\.(?<m>\d{1,2})\.(?<y>\d{4}|\d{2})\b/u',
'/\b(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})\b/u',
'/\b(?<d>\d{1,2})\.?\s+(?<mn>'.$monthNames.')\.?\s+(?<y>\d{4})\b/iu',
'/\b(?<mn>'.$monthNames.')\.?\s+(?<d>\d{1,2}),?\s+(?<y>\d{4})\b/iu',
];
$dates = [];
foreach ($patterns as $pattern) {
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
foreach ($matches as $match) {
$month = isset($match['mn']) && $match['mn'][0] !== '' ? self::MONTHS[mb_strtolower($match['mn'][0])] ?? null : (int) $match['m'][0];
$year = (int) $match['y'][0];
$year = $year < 100 ? 2000 + $year : $year;
if ($month !== null && checkdate($month, (int) $match['d'][0], $year)) {
$dates[] = ['offset' => $match[0][1], 'date' => CarbonImmutable::create($year, $month, (int) $match['d'][0])];
}
}
}
usort($dates, fn (array $a, array $b): int => $a['offset'] <=> $b['offset']);
return $dates;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
*/
private function dateAfterLabel(string $content, array $dates, string $labelPattern): ?CarbonImmutable
{
if (! preg_match($labelPattern, $content, $label, PREG_OFFSET_CAPTURE)) {
return null;
}
$labelEnd = $label[0][1] + strlen($label[0][0]);
foreach ($dates as $date) {
if ($date['offset'] >= $labelEnd && $date['offset'] - $labelEnd <= 80) {
return $date['date'];
}
}
return null;
}
/**
* @param list<array{offset: int, date: CarbonImmutable}> $dates
* @return array{?CarbonImmutable, ?CarbonImmutable}
*/
private function firstPlausiblePair(array $dates): array
{
foreach ($dates as $index => $first) {
foreach (array_slice($dates, $index + 1) as $second) {
if ($this->isPlausible($first['date'], $second['date'])) {
return [$first['date'], $second['date']];
}
}
}
return [null, null];
}
private function isPlausible(CarbonImmutable $arrival, CarbonImmutable $departure): bool
{
return $departure->greaterThan($arrival)
&& $arrival->diffInDays($departure) <= 90
&& $arrival->greaterThanOrEqualTo(CarbonImmutable::today()->subDays(2))
&& $arrival->lessThanOrEqualTo(CarbonImmutable::today()->addYears(3));
}
private function reference(string $content): ?string
{
if (preg_match('/\b(HA-[A-Z0-9]{5,})\b/', $content, $match)) {
return $match[1];
}
if (preg_match('/(?:buchungsnummer|buchungs-nr\.?|reservierungsnummer|reservation id|reservation number|booking id|booking number)\s*[:#]?\s*([A-Z0-9][A-Z0-9-]{4,})/iu', $content, $match)) {
return $match[1];
}
return null;
}
private function normalize(string $text): string
{
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
return preg_replace('/[ \t\x{00A0}\x{202F}]+/u', ' ', $text);
}
/**
* @param list<string> $needles
*/
private function containsAny(string $haystack, array $needles): bool
{
foreach ($needles as $needle) {
if (str_contains($haystack, $needle)) {
return true;
}
}
return false;
}
}
+117
View File
@@ -0,0 +1,117 @@
<?php
namespace App\Console\Commands;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Throwable;
#[Signature('backup:database {--keep= : Anzahl aufbewahrter Sicherungen}')]
#[Description('Write a compressed SQL dump of the database to storage/app/private/backups and keep the newest ones')]
class BackupDatabase extends Command
{
public const DIRECTORY = 'backups';
/** Tables without lasting value; their content is not dumped (structure only). */
private const SKIP_DATA = ['sessions', 'cache', 'cache_locks', 'jobs', 'job_batches', 'failed_jobs'];
/**
* Execute the console command.
*/
public function handle(): int
{
$keep = (int) ($this->option('keep') ?? config('fewo.backup.keep', 14));
$file = self::DIRECTORY.'/fewo-'.now()->format('Ymd-His').'.sql.gz';
$temp = tempnam(sys_get_temp_dir(), 'fewo-backup');
$out = gzopen($temp, 'wb6');
try {
gzwrite($out, '-- FeWo Stommer database backup '.now()->toIso8601String().' ('.DB::getDriverName().")\n");
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=0;\nSET NAMES utf8mb4;\n" : "PRAGMA foreign_keys=OFF;\n");
foreach ($this->tables() as $table) {
gzwrite($out, "\nDROP TABLE IF EXISTS ".$this->quoteName($table).";\n".$this->createStatement($table).";\n");
if (! in_array($table, self::SKIP_DATA, true)) {
$this->dumpRows($out, $table);
}
}
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=1;\n" : "PRAGMA foreign_keys=ON;\n");
gzclose($out);
Storage::disk('local')->put($file, (string) file_get_contents($temp));
} catch (Throwable $exception) {
report($exception);
$this->error('Sicherung fehlgeschlagen: '.$exception->getMessage());
return self::FAILURE;
} finally {
@unlink($temp);
}
$this->prune($keep);
$this->info("Sicherung erstellt: storage/app/private/{$file} (".round(Storage::disk('local')->size($file) / 1024).' KB)');
return self::SUCCESS;
}
private function isMysql(): bool
{
return in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
}
/**
* @return list<string>
*/
private function tables(): array
{
return $this->isMysql()
? array_map(fn (object $row): string => (string) array_values((array) $row)[0], DB::select('SHOW TABLES'))
: array_map(fn (object $row): string => $row->name, DB::select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"));
}
private function createStatement(string $table): string
{
if ($this->isMysql()) {
return (string) array_values((array) DB::selectOne('SHOW CREATE TABLE '.$this->quoteName($table)))[1];
}
return (string) DB::selectOne("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", [$table])->sql;
}
/**
* @param resource $out
*/
private function dumpRows($out, string $table): void
{
$pdo = DB::connection()->getPdo();
$offset = 0;
do {
$rows = DB::table($table)->offset($offset)->limit(500)->get();
foreach ($rows as $row) {
$values = array_map(fn ($value): string => $value === null ? 'NULL' : (is_int($value) || is_float($value) ? (string) $value : $pdo->quote((string) $value)), (array) $row);
gzwrite($out, 'INSERT INTO '.$this->quoteName($table).' ('.implode(', ', array_map($this->quoteName(...), array_keys((array) $row))).') VALUES ('.implode(', ', $values).");\n");
}
$offset += 500;
} while ($rows->count() === 500);
}
private function quoteName(string $name): string
{
return $this->isMysql() ? '`'.str_replace('`', '``', $name).'`' : '"'.str_replace('"', '""', $name).'"';
}
private function prune(int $keep): void
{
collect(Storage::disk('local')->files(self::DIRECTORY))
->filter(fn (string $path): bool => str_ends_with($path, '.sql.gz'))
->sort()
->reverse()
->slice(max(1, $keep))
->each(fn (string $path) => Storage::disk('local')->delete($path));
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Console\Commands;
use App\ImageWorlds\ImageWorldManifest;
use App\ImageWorlds\ImageWorldRegistry;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('image-worlds:check')]
#[Description('Check every picture world: does each slot in the manifest have its SVG file?')]
class CheckImageWorlds extends Command
{
/**
* A slot without a file is not an error at runtime – templates simply get no decoration. That makes it
* easy to miss, so it is reported here instead of silently leaving a page bare.
*/
public function handle(ImageWorldRegistry $registry): int
{
$worlds = $registry->all();
if ($worlds === []) {
$this->warn('Keine Bildwelt gefunden.');
return self::SUCCESS;
}
$incomplete = 0;
foreach ($worlds as $world) {
$missing = $world->missingFiles();
if ($missing === []) {
$this->info(sprintf('✓ %s (%s): %d Plätze', $world->name, $world->key, count($world->slots)));
continue;
}
$incomplete++;
$this->error(sprintf('✗ %s (%s): ohne Datei – %s', $world->name, $world->key, implode(', ', $missing)));
}
$this->newLine();
$this->line($this->slotOverview($worlds));
return $incomplete === 0 ? self::SUCCESS : self::FAILURE;
}
/**
* Which slot is filled by which world – so a template author sees what they may rely on.
*
* @param array<string, ImageWorldManifest> $worlds
*/
private function slotOverview(array $worlds): string
{
$slots = [];
foreach ($worlds as $world) {
foreach (array_keys($world->slots) as $slot) {
$slots[$slot][] = $world->key;
}
}
ksort($slots);
return collect($slots)
->map(fn (array $keys, string $slot): string => sprintf(' %-18s %s', $slot, implode(', ', $keys)))
->implode(PHP_EOL);
}
}
+52
View File
@@ -0,0 +1,52 @@
<?php
namespace App\Console\Commands;
use App\Themes\ThemeChecker;
use App\Themes\ThemeRegistry;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('themes:check {theme? : Key des Themes (leer = alle)}')]
#[Description('Check themes against the theme contract (docs/THEME-ERSTELLUNG.md): manifest, build, required markup, colours, contrast')]
class CheckTheme extends Command
{
/**
* Execute the console command.
*/
public function handle(ThemeRegistry $registry, ThemeChecker $checker): int
{
$key = $this->argument('theme');
if ($key !== null && ! isset($registry->all()[$key])) {
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
return self::FAILURE;
}
$themes = $key !== null ? [$registry->all()[$key]] : array_values($registry->all());
$failed = false;
foreach ($themes as $theme) {
['errors' => $errors, 'warnings' => $warnings] = $checker->check($theme);
$this->line('');
$this->line("<options=bold>{$theme->name}</> ({$theme->key} {$theme->version}".($theme->parent ? ", Eltern-Theme {$theme->parent}" : '').')');
foreach ($errors as $error) {
$this->line(" <fg=red>✗</> {$error}");
}
foreach ($warnings as $warning) {
$this->line(" <fg=yellow>!</> {$warning}");
}
if ($errors === [] && $warnings === []) {
$this->line(' <fg=green>✓</> Alles in Ordnung.');
}
$failed = $failed || $errors !== [];
}
$this->line('');
return $failed ? self::FAILURE : self::SUCCESS;
}
}
+106
View File
@@ -0,0 +1,106 @@
<?php
namespace App\Console\Commands;
use App\Enums\UserRole;
use App\Models\Tenant;
use App\Models\User;
use App\Tenancy\TenantContext;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Validation\Rules\Password;
use function Laravel\Prompts\password;
use function Laravel\Prompts\select;
use function Laravel\Prompts\text;
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content} {--tenant= : Kurzname des Mandanten}')]
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
class CreateUser extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$tenant = $this->resolveTenant();
if ($tenant === false) {
return self::FAILURE;
}
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
$email = mb_strtolower(trim($email));
if (User::where('email', $email)->exists()) {
$this->error("Es gibt bereits einen Benutzer mit {$email}.");
return self::FAILURE;
}
$name = $this->option('name') ?? text('Name', required: true);
$role = $this->option('role') !== null
? UserRole::tryFrom($this->option('role'))
: UserRole::from(select('Rolle', collect(UserRole::cases())->mapWithKeys(fn (UserRole $role): array => [$role->value => "{$role->getLabel()} – {$role->getDescription()}"])->all(), default: UserRole::Admin->value));
if ($role === null) {
$this->error('Unbekannte Rolle. Erlaubt: '.implode(', ', array_column(UserRole::cases(), 'value')));
return self::FAILURE;
}
$password = password('Passwort (mind. 12 Zeichen)', required: true, validate: ['password' => Password::min(12)]);
if (password('Passwort wiederholen', required: true) !== $password) {
$this->error('Die Passwörter stimmen nicht überein.');
return self::FAILURE;
}
$user = User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
if ($tenant instanceof Tenant) {
app(TenantContext::class)->set($tenant);
$user->attachCurrentRole($tenant);
}
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
return self::SUCCESS;
}
/**
* One landlord is used automatically. Several landlords need --tenant. None is allowed:
* the account exists and is attached later.
*/
private function resolveTenant(): Tenant|false|null
{
$slug = $this->option('tenant');
if (is_string($slug) && $slug !== '') {
$tenant = Tenant::query()->where('slug', $slug)->first();
if ($tenant === null) {
$this->error("Kein Mandant mit dem Kurznamen {$slug}.");
return false;
}
return $tenant;
}
$count = Tenant::query()->count();
if ($count > 1) {
$this->error('Es gibt mehrere Mandanten. Bitte --tenant=kurzname angeben.');
return false;
}
return $count === 1 ? Tenant::query()->first() : null;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use App\Models\Tenant;
use App\Tenancy\TenantArchive;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use function Laravel\Prompts\confirm;
#[Signature('tenants:delete {slug : Kurzname des Mandanten} {--keep-export : Nicht vorher exportieren} {--force : Ohne Rückfrage}')]
#[Description('Export a landlord and then remove them with all their data and files')]
class DeleteTenant extends Command
{
/**
* Exports first, unless told otherwise: a deletion that cannot be undone should leave something behind.
*/
public function handle(TenantArchive $archive): int
{
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
if ($tenant === null) {
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
return self::FAILURE;
}
if (! $this->option('keep-export')) {
$path = $archive->export($tenant, storage_path('app/private/exports'));
$this->info('Export geschrieben: '.$path);
}
if (! $this->option('force') && ! confirm('Mandant '.$tenant->name.' mit allen Daten und Dateien endgültig löschen?', default: false)) {
$this->line('Abgebrochen.');
return self::SUCCESS;
}
$removed = $archive->delete($tenant);
foreach ($removed as $table => $count) {
$this->line(sprintf(' %-22s %d', $table, $count));
}
$this->info('Mandant '.$tenant->name.' gelöscht.');
return self::SUCCESS;
}
}
@@ -3,22 +3,26 @@
namespace App\Console\Commands;
use App\Actions\ExpireReservations;
use App\Models\Tenant;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('bookings:expire-holds')]
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord')]
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord – once per landlord')]
class ExpireReservationHolds extends Command
{
/**
* Execute the console command.
*/
public function handle(ExpireReservations $expireReservations): int
public function handle(ExpireReservations $expireReservations, TenantRunner $runner): int
{
$count = $expireReservations->handle();
$runner->each(function (Tenant $tenant) use ($expireReservations): void {
$count = $expireReservations->handle();
$this->info("{$count} Vormerkung(en) abgelaufen.");
$this->info("{$tenant->name}: {$count} Vormerkung(en) abgelaufen.");
});
return self::SUCCESS;
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Console\Commands;
use App\Models\Tenant;
use App\Tenancy\TenantArchive;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('tenants:export {slug : Kurzname des Mandanten} {--to= : Zielordner, sonst storage/app/private/exports}')]
#[Description('Write all data and files of one landlord into a zip archive')]
class ExportTenant extends Command
{
public function handle(TenantArchive $archive): int
{
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
if ($tenant === null) {
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
return self::FAILURE;
}
$path = $archive->export($tenant, (string) ($this->option('to') ?: storage_path('app/private/exports')));
$this->info('Export von '.$tenant->name.': '.$path.' ('.$this->size($path).')');
return self::SUCCESS;
}
private function size(string $path): string
{
$bytes = (int) (filesize($path) ?: 0);
return $bytes > 1048576
? round($bytes / 1048576, 1).' MB'
: round($bytes / 1024).' KB';
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace App\Console\Commands;
use App\Actions\ProcessPortalMail;
use App\Channels\ChannelSyncException;
use App\Channels\Mail\MailboxReader;
use App\Enums\TenantServiceKey;
use App\Models\Channel;
use App\Models\Tenant;
use App\Tenancy\TenantFeatures;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:fetch-mail')]
#[Description('Read booking notifications of the portals from each landlord\'s mailbox and block recognised bookings immediately')]
class FetchPortalMail extends Command
{
/**
* Execute the console command. Every landlord has their own mailbox, so every landlord gets their own
* run – one landlord's credentials are never used to read another one's mail.
*/
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail, TenantRunner $runner): int
{
$runner->each(fn (Tenant $tenant) => $this->fetchForCurrentLandlord($reader, $processPortalMail, $tenant));
return self::SUCCESS;
}
private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMail $processPortalMail, Tenant $tenant): void
{
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $tenant)) {
return;
}
if (! MailboxReader::isConfigured()) {
$this->line("{$tenant->name}: kein Postfach hinterlegt.");
return;
}
$senders = Channel::query()->active()->get()
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
->unique()
->values()
->all();
if ($senders === []) {
$this->line("{$tenant->name}: für kein Portal sind Absender hinterlegt.");
return;
}
try {
$mails = $reader->fetch($senders);
} catch (ChannelSyncException $exception) {
$this->error("{$tenant->name}: {$exception->getMessage()}");
return;
}
foreach ($mails as $mail) {
if ($record = $processPortalMail->handle($mail)) {
$this->info("{$tenant->name} – {$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
}
}
}
}
+87 -17
View File
@@ -8,41 +8,111 @@
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area}')]
#[Description('Import all images of a folder as website photos (e.g. when migrating from the old website)')]
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area} {--manifest= : CSV "file;category;alt_text" with paths relative to the folder (chooses and describes the photos)}')]
#[Description('Import images as website photos (e.g. when migrating from the old website); the source files are only read')]
class ImportPhotos extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$directory = rtrim((string) $this->argument('directory'), '/\\');
$entries = $this->option('manifest') !== null
? $this->manifestEntries((string) $this->option('manifest'), $directory)
: $this->folderEntries($directory);
if ($entries === null) {
return self::FAILURE;
}
$propertyId = Property::query()->value('id');
$sort = (int) Photo::max('sort_order');
$imported = 0;
foreach ($entries as ['file' => $file, 'category' => $category, 'alt_text' => $altText]) {
$source = str_replace('\\', '/', substr($file, strlen($directory) + 1));
if (! is_file($file)) {
$this->warn("Fehlt: {$source}");
continue;
}
if (Media::query()->where('collection_name', Photo::COLLECTION)->where('custom_properties->source', $source)->exists()) {
$this->line("– bereits vorhanden: {$source}");
continue;
}
$photo = Photo::create([
'property_id' => $category === PhotoCategory::Area ? null : $propertyId,
'category' => $category,
'alt_text' => $altText,
'sort_order' => ++$sort,
]);
$photo->addMedia($file)
->preservingOriginal()
->withCustomProperties(['source' => $source])
->toMediaCollection(Photo::COLLECTION);
$imported++;
$this->line("✓ {$photo->alt_text}");
}
$this->info("{$imported} Bilder importiert.");
return self::SUCCESS;
}
/**
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
*/
private function folderEntries(string $directory): ?array
{
$category = PhotoCategory::tryFrom((string) $this->option('category'));
if ($category === null) {
$this->error('Unbekannte Kategorie. Erlaubt: '.implode(', ', array_column(PhotoCategory::cases(), 'value')));
return self::FAILURE;
return null;
}
$files = glob(rtrim((string) $this->argument('directory'), '/\\').'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
$propertyId = $category === PhotoCategory::Area ? null : Property::query()->value('id');
$sort = (int) Photo::max('sort_order');
$files = glob($directory.'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
foreach ($files as $file) {
$photo = Photo::create([
'property_id' => $propertyId,
'category' => $category,
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
'sort_order' => ++$sort,
]);
$photo->addMedia($file)->preservingOriginal()->toMediaCollection(Photo::COLLECTION);
return array_map(fn (string $file): array => [
'file' => $file,
'category' => $category,
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
], $files);
}
$this->line("✓ {$photo->alt_text}");
/**
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
*/
private function manifestEntries(string $manifest, string $directory): ?array
{
if (! is_file($manifest)) {
$this->error("Liste nicht gefunden: {$manifest}");
return null;
}
$this->info(count($files).' Bilder importiert.');
$entries = [];
foreach (array_slice(file($manifest, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [], 1) as $number => $line) {
[$file, $category, $altText] = array_pad(str_getcsv($line, ';', '"', ''), 3, '');
$category = PhotoCategory::tryFrom(trim($category));
return self::SUCCESS;
if ($category === null || trim($file) === '' || trim($altText) === '') {
$this->error('Ungültige Zeile '.($number + 2).": {$line}");
return null;
}
$entries[] = ['file' => $directory.'/'.ltrim(trim($file), '/'), 'category' => $category, 'alt_text' => trim($altText)];
}
return $entries;
}
}
+58
View File
@@ -0,0 +1,58 @@
<?php
namespace App\Console\Commands;
use App\Models\Site;
use App\Tenancy\TenantContext;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('sites:import-stommer-brand {site : ID der bestehenden Stommer-Website}')]
#[Description('Copy the legacy Stommer brand into its own website without replacing uploaded graphics')]
class ImportSiteBrand extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$site = Site::withoutGlobalScope('tenant')->with('tenant')->find($this->argument('site'));
if ($site === null || $site->tenant?->slug !== 'stommer') {
$this->error('Nur die bestehende Stommer-Website darf diese Marke übernehmen.');
return self::FAILURE;
}
$seebad = $site->theme === 'seebad';
$sources = [
Site::BRAND_LOGO => $seebad ? resource_path('themes/seebad/img/logo-bildmarke-720.webp') : public_path('brand/logo.svg'),
Site::BRAND_FAVICON => $seebad ? resource_path('themes/seebad/img/favicon.svg') : public_path('brand/favicon.svg'),
Site::BRAND_DOCUMENT_LOGO => public_path('brand/logo-600.png'),
];
foreach ($sources as $collection => $path) {
if (! $site->hasMedia($collection) && ! is_file($path)) {
$this->error('Markenquelle fehlt: '.$path);
return self::FAILURE;
}
}
app(TenantContext::class)->run($site->tenant, function () use ($site, $sources): void {
foreach ($sources as $collection => $path) {
if ($site->hasMedia($collection)) {
$this->line($collection.': vorhandene Grafik beibehalten.');
continue;
}
$site->addMedia($path)->preservingOriginal()->toMediaCollection($collection);
$this->info($collection.': übernommen.');
}
});
return self::SUCCESS;
}
}
+143
View File
@@ -0,0 +1,143 @@
<?php
namespace App\Console\Commands;
use App\Themes\ThemeManifest;
use App\Themes\ThemeRegistry;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
#[Signature('themes:make {key : Ordner/Key, z. B. ostsee-nacht} {--name= : Anzeigename} {--parent= : Eltern-Theme (Standard: Basis-Theme)} {--description= : Beschreibung für die Theme-Auswahl}')]
#[Description('Create a new theme next to the existing ones (never overwrites) – inherits everything until views are added')]
class MakeTheme extends Command
{
/**
* Execute the console command.
*/
public function handle(ThemeRegistry $registry): int
{
$key = (string) $this->argument('key');
$parent = (string) ($this->option('parent') ?: config('themes.base'));
$themesPath = rtrim((string) (config('themes.paths')[0] ?? resource_path('themes')), '/\\');
$path = "{$themesPath}/{$key}";
$folder = str_replace('\\', '/', ltrim(substr($path, strlen(base_path())), '/\\'));
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $key)) {
$this->error('Key: nur Kleinbuchstaben, Ziffern und Bindestriche, z. B. ostsee-nacht.');
return self::FAILURE;
}
if (File::exists($path) || isset($registry->all()[$key])) {
$this->error("Theme „{$key}“ gibt es schon – es wird nichts überschrieben.");
return self::FAILURE;
}
if (! isset($registry->all()[$parent])) {
$this->error("Eltern-Theme „{$parent}“ ist nicht installiert.");
return self::FAILURE;
}
$name = (string) ($this->option('name') ?: str($key)->replace('-', ' ')->title());
$manifest = [
'key' => $key,
'name' => $name,
'version' => '0.1.0',
'parent' => $parent,
'description' => (string) ($this->option('description') ?: "Neues Theme auf Basis von „{$registry->get($parent)->name}“."),
'assets' => ['css' => "{$folder}/theme.css", 'js' => "{$folder}/theme.js"],
'tokens' => $registry->tokens($parent),
];
File::ensureDirectoryExists("{$path}/views/sections");
File::ensureDirectoryExists("{$path}/views/partials");
File::put("{$path}/views/sections/.gitkeep", '');
File::put("{$path}/views/partials/.gitkeep", '');
File::put("{$path}/theme.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n");
File::put("{$path}/theme.css", $this->css($name, $parent, $path, $registry));
File::put("{$path}/theme.js", $this->js($name, ThemeManifest::relativePath($path, $registry->get($parent)->path).'/theme.js'));
File::put("{$path}/README.md", $this->readme($name, $key, $parent));
$this->info("Theme „{$name}“ angelegt: {$folder}");
$this->line('Es erbt zunächst alles von „'.$parent.'“. Vorlagen nach views/ kopieren und umgestalten – Anleitung: docs/THEME-ERSTELLUNG.md');
$this->line("Prüfen: php artisan themes:check {$key} · Bauen: npm run build · Auswählen: Admin › System › Websites › Theme (dort „Vorschau“).");
return self::SUCCESS;
}
/**
* Child theme CSS: Tailwind, the reusable styles of the nearest ancestor that has a theme-base.css,
* and the template sources of all ancestors, the booking forms and the theme itself.
*/
private function css(string $name, string $parent, string $path, ThemeRegistry $registry): string
{
$ancestors = $registry->chain($parent);
$base = collect($ancestors)->first(fn (ThemeManifest $theme): bool => is_file($theme->path.'/theme-base.css')) ?? $ancestors[0];
$import = ThemeManifest::relativePath($path, $base->path).'/theme-base.css';
$sources = collect($ancestors)
->map(fn (ThemeManifest $theme): string => "@source '".ThemeManifest::relativePath($path, $theme->viewsPath())."';")
->push("@source '".ThemeManifest::relativePath($path, resource_path('views/livewire'))."';")
->push("@source './views';")
->implode("\n");
return <<<CSS
/*
* Theme „{$name}“ – Child von „{$parent}“ (Anleitung: docs/THEME-ERSTELLUNG.md).
* theme-base.css des Eltern-Themes bringt Schriften, Token-Mapping und Basis-Klassen (.eyebrow,
* .heading-display, .btn-primary, .btn-accent, .prose-theme, .reveal). Hier nur Abweichungen ergänzen.
*/
@import 'tailwindcss';
@import '{$import}';
/* Eigene Schriften selbst hosten: npm install @fontsource/<schrift> und hier importieren, z. B.
@import '@fontsource/fraunces/400.css';
*/
/* Vorlagen, deren Klassen gebaut werden: geerbte, Buchungsformulare, eigene. */
{$sources}
@theme inline {
/* --font-display: 'Fraunces', Georgia, serif; */
/* --font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif; */
}
@layer components {
}
CSS;
}
private function js(string $name, string $import): string
{
return <<<JS
/**
* Theme „{$name}“: übernimmt Lightbox, Verfügbarkeitssuche und rollierende Angebote vom Eltern-Theme.
* Eigene Verbesserungen darunter – alles muss auch ohne JavaScript funktionieren.
*/
import '{$import}';
JS;
}
private function readme(string $name, string $key, string $parent): string
{
return <<<MD
# Theme „{$name}“ (`{$key}`)
Child-Theme von `{$parent}`. Vorlagen, die hier fehlen, kommen vom Eltern-Theme.
- Anleitung und Vorlagen-Vertrag: `docs/THEME-ERSTELLUNG.md`, `docs/THEMES.md` §5
- Prüfen: `php artisan themes:check {$key}`
- Ansehen ohne Umschalten: Admin › System › Websites › Theme „{$name}“ wählen › „Vorschau“ (erst danach speichern)
## Eigene Vorlagen
| Datei | Zweck |
|---|---|
| | |
MD;
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Console\Commands;
use App\Models\Page;
use App\Themes\ThemeFactory;
use App\Themes\ThemeRegistry;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\URL;
#[Signature('themes:preview {theme : Key des Themes} {--hours=24 : Gültigkeit der Links}')]
#[Description('Print signed preview links: every page of the site with the theme, in every appearance – without switching the site')]
class PreviewTheme extends Command
{
/**
* Execute the console command.
*/
public function handle(ThemeRegistry $registry, ThemeFactory $factory): int
{
$key = (string) $this->argument('theme');
if (! isset($registry->all()[$key])) {
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
return self::FAILURE;
}
$site = $factory->site();
$expires = now()->addHours((int) $this->option('hours'));
$pages = $site->exists ? $site->pages()->where('is_published', true)->orderBy('sort_order')->get() : collect();
$appearances = $site->exists ? $site->appearances()->orderByDesc('is_default')->orderBy('starts_md')->get() : collect();
$this->info("Vorschau „{$registry->get($key)->name}“ für {$site->name} (gültig bis {$expires->format('d.m.Y H:i')}):");
foreach ($pages as $page) {
$this->line('');
$this->line("<options=bold>{$page->title}</>");
$this->line(' heute: '.$this->url($page, ['theme' => $key], $expires));
foreach ($appearances as $appearance) {
$this->line(str_pad(" {$appearance->name}:", 16).$this->url($page, ['theme' => $key, 'vorschau' => $appearance->id], $expires));
}
}
return self::SUCCESS;
}
/**
* @param array<string, mixed> $parameters
*/
private function url(Page $page, array $parameters, \DateTimeInterface $expires): string
{
return $page->isHome()
? URL::temporarySignedRoute('home', $expires, $parameters)
: URL::temporarySignedRoute('page', $expires, ['slug' => $page->slug, ...$parameters]);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Console\Commands;
use App\Models\User;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('users:promote-operator {email : E-Mail-Adresse}')]
#[Description('Grant the operator flag. The account keeps its password, two-factor setup and any landlord role.')]
class PromoteOperator extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$email = mb_strtolower(trim((string) $this->argument('email')));
$user = User::query()->where('email', $email)->first();
if ($user === null) {
$this->error('Kein Benutzer mit dieser E-Mail.');
return self::FAILURE;
}
$user->forceFill(['is_operator' => true])->save();
$this->info("{$email} ist jetzt Betreiber. Eine bestehende Mandanten-Rolle bleibt.");
return self::SUCCESS;
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace App\Console\Commands;
use App\Support\Settings;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Mail;
use Throwable;
#[Signature('mail:test {to? : Empfänger (Standard: Benachrichtigungsadresse)}')]
#[Description('Send a test e-mail through the configured mailer and report delivery errors (e.g. SMTP login)')]
class SendTestMail extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$to = (string) ($this->argument('to') ?: Settings::notificationRecipients()[0] ?? config('fewo.owner.email'));
$mailer = (string) config('mail.default');
$redirect = Settings::mailRedirect();
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
if (filled($redirect)) {
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
}
if ($mailer === 'log') {
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
}
try {
Mail::raw("Testmail der Ferienwohnung Stommer\n\nGesendet am ".now()->format('d.m.Y H:i:s').' von '.config('app.url').".\nWenn diese Mail ankommt, funktioniert der Versand.", function ($message) use ($to): void {
$message->to($to)->subject('Testmail Ferienwohnung Stommer – '.now()->format('d.m.Y H:i'));
});
} catch (Throwable $exception) {
$this->error('Versand fehlgeschlagen: '.$exception->getMessage());
return self::FAILURE;
}
if ($mailer === 'log') {
$this->line('Mail erzeugt, aber nicht zugestellt (Versandweg "log").');
} else {
$this->info('Übergeben an den Mailserver – bitte Posteingang (und Spam-Ordner) prüfen.');
}
return self::SUCCESS;
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Console\Commands;
use App\Models\Photo;
use App\Support\StripImageMetadata;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Spatie\MediaLibrary\MediaCollections\Models\Media;
#[Signature('photos:strip-metadata {--force : Auch bereits bereinigte Fotos erneut bearbeiten}')]
#[Description('Remove metadata (GPS position, camera data) from all stored original photos – new uploads are cleaned automatically')]
class StripPhotoMetadata extends Command
{
/**
* Execute the console command.
*/
public function handle(): int
{
$cleaned = Media::query()->where('collection_name', Photo::COLLECTION)->get()
->filter(fn (Media $media): bool => StripImageMetadata::strip($media, (bool) $this->option('force')))
->count();
$this->info("{$cleaned} Original-Foto(s) bereinigt.");
return self::SUCCESS;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use App\Actions\SyncChannel;
use App\Models\Channel;
use App\Tenancy\TenantRunner;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('channels:sync {channel? : ID of a single channel}')]
#[Description('Import the occupations of all active portals (or one) and report conflicts – once per landlord')]
class SyncChannels extends Command
{
/**
* Execute the console command. Runs per landlord so that conflict mails carry the right sender and
* reach the right people.
*/
public function handle(SyncChannel $syncChannel, TenantRunner $runner): int
{
$runner->each(fn () => $this->syncCurrentLandlord($syncChannel));
return self::SUCCESS;
}
private function syncCurrentLandlord(SyncChannel $syncChannel): void
{
$channels = Channel::query()->active()
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
->get()
->filter(fn (Channel $channel): bool => $channel->importsOccupations());
foreach ($channels as $channel) {
$log = $syncChannel->handle($channel);
$log->successful
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
: $this->error("✗ {$channel->name}: {$log->message}");
}
}
}
+47
View File
@@ -0,0 +1,47 @@
<?php
namespace App\Documents;
use App\Models\Booking;
use App\Models\Site;
use Barryvdh\DomPDF\Facade\Pdf;
use Illuminate\Support\Facades\Storage;
/**
* The rental contract as PDF. As a draft it is part of the offer (offer_path, one file per offer version);
* the final contract is generated at confirmation (contract_path). Both are stored, so later changes of
* texts or prices do not alter a document the guest already received.
*/
class RentalContract
{
private const DISK = 'local';
public function generate(Booking $booking, bool $draft = false): string
{
$booking->loadMissing(['guest', 'property']);
$filename = $draft
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
: "contracts/Mietvertrag-{$booking->reference}.pdf";
$path = "contracts/tenants/{$booking->tenant_id}/bookings/{$booking->id}/".basename($filename);
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
// fetching anything over the network. Each website has its own (A14).
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', [
'booking' => $booking,
'draft' => $draft,
'logo' => $logo,
])->setPaper('a4')->output());
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
return $path;
}
public function absolutePath(Booking $booking, bool $draft = false): ?string
{
$path = $draft ? $booking->offer_path : $booking->contract_path;
return $path && Storage::disk(self::DISK)->exists($path) ? Storage::disk(self::DISK)->path($path) : null;
}
}
+86
View File
@@ -0,0 +1,86 @@
<?php
namespace App\Enums;
use App\Filament\Pages\OccupancyCalendar;
use App\Filament\Pages\PricesAndOffers;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Channels\ChannelResource;
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
use App\Filament\Resources\Guests\GuestResource;
use App\Filament\Resources\Photos\PhotoResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Filament\Resources\Reviews\ReviewResource;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* How much of the admin a user sees. It only shapes the menu – what a user may do is decided by the role.
*/
enum AdminMode: string implements HasDescription, HasLabel
{
case Simple = 'simple';
case Expert = 'expert';
/**
* Menu entries of the simple mode: day-to-day work with requests, bookings, contracts and the calendar.
*
* @var list<class-string>
*/
public const SIMPLE_NAVIGATION = [
OccupancyCalendar::class,
InboxMessageResource::class,
BookingResource::class,
PortalOccupationResource::class,
BlockedPeriodResource::class,
PricesAndOffers::class,
GuestResource::class,
ChannelTaskResource::class,
ChannelResource::class,
ReviewResource::class,
PhotoResource::class,
];
public function getLabel(): string
{
return match ($this) {
self::Simple => 'Einfache Ansicht',
self::Expert => 'Expertenansicht',
};
}
public function getDescription(): string
{
return match ($this) {
self::Simple => 'Das Tägliche: Postfach, Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
};
}
/**
* Whether a resource or page appears in the menu in this mode.
*
* @param class-string $class
*/
public function shows(string $class): bool
{
return $this === self::Expert || in_array($class, self::SIMPLE_NAVIGATION, true);
}
/**
* Label of the user menu entry that switches to this mode.
*/
public function switchLabel(): string
{
return match ($this) {
self::Simple => 'Zur einfachen Ansicht wechseln',
self::Expert => 'Zur Expertenansicht wechseln',
};
}
public function other(): self
{
return $this === self::Simple ? self::Expert : self::Simple;
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum BlockedPeriodPurpose: string implements HasLabel
{
case OwnUse = 'own_use';
case Maintenance = 'maintenance';
case Other = 'other';
public function getLabel(): string
{
return match ($this) {
self::OwnUse => 'Eigenbelegung',
self::Maintenance => 'Wartung / Renovierung',
self::Other => 'Sonstige Sperre',
};
}
}
+19 -2
View File
@@ -7,8 +7,13 @@
enum BookingStatus: string implements HasColor, HasLabel
{
/** Guest request; the dates are held until hold_expires_at. */
/** Non-binding guest request; the dates are held until hold_expires_at. */
case Reserved = 'reserved';
/** The landlord sent an offer; the dates are held until hold_expires_at (= end of the offer's validity). */
case OfferSent = 'offer_sent';
/** Binding booking: the guest accepted the offer (or the landlord confirmed directly). */
case Confirmed = 'confirmed';
case DepositPaid = 'deposit_paid';
case Paid = 'paid';
@@ -20,7 +25,8 @@ enum BookingStatus: string implements HasColor, HasLabel
public function getLabel(): string
{
return match ($this) {
self::Reserved => 'Vorreserviert',
self::Reserved => 'Anfrage (vorgemerkt)',
self::OfferSent => 'Angebot gesendet',
self::Confirmed => 'Bestätigt',
self::DepositPaid => 'Anzahlung erhalten',
self::Paid => 'Bezahlt',
@@ -35,12 +41,23 @@ public function getColor(): string
{
return match ($this) {
self::Reserved => 'warning',
self::OfferSent => 'primary',
self::Confirmed, self::DepositPaid => 'info',
self::Paid, self::Completed => 'success',
self::Declined, self::Expired, self::Cancelled => 'gray',
};
}
/**
* Statuses that occupy the calendar while their hold time (hold_expires_at) runs.
*
* @return list<self>
*/
public static function holding(): array
{
return [self::Reserved, self::OfferSent];
}
/**
* Statuses that occupy the calendar regardless of any hold time.
*
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum ChannelBookingModel: string implements HasLabel
{
case Inquiry = 'inquiry';
case PortalBooking = 'portal_booking';
case Mixed = 'mixed';
public function getLabel(): string
{
return match ($this) {
self::Inquiry => 'Vermittlung / Anfrage',
self::PortalBooking => 'Portalbuchung',
self::Mixed => 'Gemischt',
};
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum ChannelEchoBehavior: string implements HasLabel
{
case Unverified = 'unverified';
case NoReexport = 'no_reexport';
case Reexports = 'reexports';
public function getLabel(): string
{
return match ($this) {
self::Unverified => 'Noch ungeprüft',
self::NoReexport => 'Im geprüften Fall keine Weitergabe importierter Ereignisse',
self::Reexports => 'Gibt importierte Ereignisse weiter – neue Belegungen erst klären',
};
}
}
+19
View File
@@ -0,0 +1,19 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum ChannelExportMode: string implements HasLabel
{
case Test = 'test';
case Regular = 'regular';
public function getLabel(): string
{
return match ($this) {
self::Test => 'Testbetrieb: nur eigene Belegungen',
self::Regular => 'Regulär: alle übrigen Kanäle einbeziehen',
};
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum ChannelStatus: string implements HasLabel
{
case Setup = 'setup';
case Active = 'active';
case Paused = 'paused';
public function getLabel(): string
{
return match ($this) {
self::Setup => 'Noch nicht eingerichtet',
self::Active => 'Aktiv',
self::Paused => 'Pausiert',
};
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChannelTaskAction: string implements HasColor, HasLabel
{
case Block = 'block';
case Unblock = 'unblock';
public function getLabel(): string
{
return match ($this) {
self::Block => 'Sperren',
self::Unblock => 'Freigeben',
};
}
public function getColor(): string
{
return match ($this) {
self::Block => 'danger',
self::Unblock => 'success',
};
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum ChannelTaskStatus: string implements HasColor, HasLabel
{
case Open = 'open';
case Done = 'done';
case Dismissed = 'dismissed';
public function getLabel(): string
{
return match ($this) {
self::Open => 'Offen',
self::Done => 'Erledigt',
self::Dismissed => 'Verworfen',
};
}
public function getColor(): string
{
return match ($this) {
self::Open => 'warning',
self::Done => 'success',
self::Dismissed => 'gray',
};
}
}
+55
View File
@@ -0,0 +1,55 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* The parts of the daily/weekly summary a landlord can choose (System › Betrieb › Benachrichtigungen).
*/
enum DigestSection: string implements HasDescription, HasLabel
{
case Inbox = 'inbox';
case Requests = 'requests';
case News = 'news';
case Stays = 'stays';
case Payments = 'payments';
case Portals = 'portals';
case Reviews = 'reviews';
public function getLabel(): string
{
return match ($this) {
self::Inbox => 'Postfach',
self::Requests => 'Offene Anfragen und Angebote',
self::News => 'Neu seit der letzten Übersicht',
self::Stays => 'An- und Abreisen',
self::Payments => 'Überfällige Zahlungen',
self::Portals => 'Portale: Aufgaben und Klärungsfälle',
self::Reviews => 'Bewertungen zur Freigabe',
};
}
public function getDescription(): string
{
return match ($this) {
self::Inbox => 'Ungelesene Meldungen, z. B. mögliche Doppelbuchungen',
self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist',
self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen',
self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage',
self::Payments => 'Anzahlungen und Restzahlungen nach Fälligkeit',
self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler',
self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind',
};
}
/**
* @param list<string>|null $values stored choice; null = everything
* @return list<self>
*/
public static function chosen(?array $values): array
{
return $values === null ? self::cases() : array_values(array_filter(self::cases(), fn (self $section): bool => in_array($section->value, $values, true)));
}
}
+9
View File
@@ -18,6 +18,9 @@ enum DiscountType: string implements HasLabel
/** discount_value = number of cheapest nights that are free */
case FreeNights = 'free_nights';
/** discount_value = package price in euro cents for all nights of the stay */
case FixedStayPrice = 'fixed_stay_price';
public function getLabel(): string
{
return match ($this) {
@@ -25,6 +28,12 @@ public function getLabel(): string
self::AmountPerStay => 'Rabatt in € pro Aufenthalt',
self::NightlyRate => 'Sonderpreis pro Nacht',
self::FreeNights => 'Gratis-Nächte',
self::FixedStayPrice => 'Pauschalpreis für den Aufenthalt',
};
}
public function isMoney(): bool
{
return in_array($this, [self::AmountPerStay, self::NightlyRate, self::FixedStayPrice], true);
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* What an inbox message is about.
*/
enum InboxMessageKind: string implements HasColor, HasLabel
{
case ChannelConflict = 'channel_conflict';
public function getLabel(): string
{
return match ($this) {
self::ChannelConflict => 'Mögliche Doppelbuchung',
};
}
public function getColor(): string
{
return match ($this) {
self::ChannelConflict => 'danger',
};
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum OccupationKind: string implements HasColor, HasLabel
{
case Reservation = 'reservation';
case Block = 'block';
case Unknown = 'unknown';
public function getLabel(): string
{
return match ($this) {
self::Reservation => 'Portalreservierung',
self::Block => 'Sperrzeit',
self::Unknown => 'Ungeklärte Belegung',
};
}
public function getColor(): string
{
return match ($this) {
self::Reservation => 'info',
self::Block => 'gray',
self::Unknown => 'warning',
};
}
}
+39
View File
@@ -0,0 +1,39 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasDescription;
use Filament\Support\Contracts\HasLabel;
/**
* How an offer finds its stays. All kinds are priced by PriceCalculator and advertised by OfferShowcase.
*/
enum OfferKind: string implements HasDescription, HasLabel
{
/** Conditions only (last minute, early bird, from N nights, weekend …). */
case Rule = 'rule';
/** One fixed arrival and departure (stay_from / stay_until), e.g. a week as a package. */
case FixedDates = 'fixed_dates';
/** Free gaps of at most max_gap_nights between two occupations, found automatically. */
case GapFiller = 'gap_filler';
public function getLabel(): string
{
return match ($this) {
self::Rule => 'Rabattaktion (nach Bedingungen)',
self::FixedDates => 'Fester Termin',
self::GapFiller => 'Lückenfüller (Kalenderlücken)',
};
}
public function getDescription(): string
{
return match ($this) {
self::Rule => 'Gilt für jeden Aufenthalt, der die Bedingungen erfüllt, z. B. Last Minute oder „ab 3 Nächten −10 %“.',
self::FixedDates => 'Ein bestimmter Zeitraum, z. B. „7 Nächte vom 07. bis 14.11.“ – wird nur beworben, solange er frei ist.',
self::GapFiller => 'Findet freie Lücken zwischen zwei Buchungen automatisch und bewirbt sie mit konkreten Terminen.',
};
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum PaymentMethod: string implements HasLabel
{
case Transfer = 'transfer';
case Cash = 'cash';
case Other = 'other';
public function getLabel(): string
{
return match ($this) {
self::Transfer => 'Überweisung',
self::Cash => 'Bar',
self::Other => 'Sonstiges',
};
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
namespace App\Enums;
/**
* What a role may do inside the current landlord. A new role is a new case on UserRole plus a list here.
*/
enum Permission: string
{
case Bookings = 'bookings';
case Properties = 'properties';
case Guests = 'guests';
case Reviews = 'reviews';
case Channels = 'channels';
case Content = 'content';
case Users = 'users';
case Settings = 'settings';
}
+13
View File
@@ -9,6 +9,8 @@ enum PhotoCategory: string implements HasLabel
case Apartment = 'apartment';
case Outdoor = 'outdoor';
case Area = 'area';
/** Floor plans and drawings: chosen explicitly (e.g. for the interactive floor plan), never shown in galleries. */
case Plan = 'plan';
public function getLabel(): string
{
@@ -16,6 +18,17 @@ public function getLabel(): string
self::Apartment => 'Wohnung',
self::Outdoor => 'Terrasse & Garten',
self::Area => 'Kühlungsborn & Umgebung',
self::Plan => 'Grundriss & Pläne',
};
}
/**
* Categories a gallery or an automatic photo may show.
*
* @return list<self>
*/
public static function forGalleries(): array
{
return array_values(array_filter(self::cases(), fn (self $category): bool => $category !== self::Plan));
}
}
+43
View File
@@ -0,0 +1,43 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum PortalEmailStatus: string implements HasColor, HasLabel
{
/** A new block was created from the e-mail. */
case Blocked = 'blocked';
/** The period was already blocked (e.g. by the calendar sync). */
case AlreadyKnown = 'already_known';
/** A cancellation released a block created from an e-mail. */
case Released = 'released';
case NeedsReview = 'needs_review';
case Reviewed = 'reviewed';
case Ignored = 'ignored';
public function getLabel(): string
{
return match ($this) {
self::Blocked => 'Gesperrt',
self::AlreadyKnown => 'Bereits gesperrt',
self::Released => 'Freigegeben',
self::NeedsReview => 'Bitte prüfen',
self::Reviewed => 'Geprüft',
self::Ignored => 'Ignoriert',
};
}
public function getColor(): string
{
return match ($this) {
self::Blocked, self::Released => 'success',
self::AlreadyKnown, self::Reviewed, self::Ignored => 'gray',
self::NeedsReview => 'danger',
};
}
}
+23
View File
@@ -0,0 +1,23 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
enum PortalEmailType: string implements HasLabel
{
case Booking = 'booking';
case Cancellation = 'cancellation';
case Inquiry = 'inquiry';
case Unknown = 'unknown';
public function getLabel(): string
{
return match ($this) {
self::Booking => 'Buchung',
self::Cancellation => 'Stornierung',
self::Inquiry => 'Anfrage',
self::Unknown => 'Unbekannt',
};
}
}
+4 -1
View File
@@ -10,11 +10,14 @@ enum QuoteLineType: string
case Extra = 'extra';
case Discount = 'discount';
/** Manual price change by the landlord in an offer (negative = reduction). */
case Adjustment = 'adjustment';
/**
* Whether the line counts towards the rent on which the deposit is calculated.
*/
public function isRent(): bool
{
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount], true);
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment], true);
}
}
+36
View File
@@ -0,0 +1,36 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasLabel;
/**
* "How did you find us?" – answered by the guest in the request form.
*/
enum ReferralSource: string implements HasLabel
{
case SearchEngine = 'search_engine';
case FewoDirekt = 'fewo_direkt';
case Ostseeklar = 'ostseeklar';
case FerienUndWohnen = 'ferienundwohnen';
case TouristInformation = 'tourist_information';
case SocialMedia = 'social_media';
case Recommendation = 'recommendation';
case ReturningGuest = 'returning_guest';
case Other = 'other';
public function getLabel(): string
{
return match ($this) {
self::SearchEngine => 'Suchmaschine (z. B. Google)',
self::FewoDirekt => 'FeWo-direkt',
self::Ostseeklar => 'Ostseeklar',
self::FerienUndWohnen => 'ferienundwohnen.de',
self::TouristInformation => 'Tourist-Information Kühlungsborn',
self::SocialMedia => 'Social Media',
self::Recommendation => 'Empfehlung',
self::ReturningGuest => 'Ich war schon Gast',
self::Other => 'Sonstiges',
};
}
}
+76
View File
@@ -0,0 +1,76 @@
<?php
namespace App\Enums;
/**
* Services the operator unlocks per landlord. `isWired()` says whether the application really asks before
* it acts – a service that nothing asks for must not be offered as a switch, because switching it would
* promise something that does not happen.
*/
enum TenantServiceKey: string
{
case PortalSync = 'portal_sync';
case PortalMail = 'portal_mail';
case AiOffers = 'ai_offers';
case AiMarketing = 'ai_marketing';
case AiGuestMail = 'ai_guest_mail';
public function label(): string
{
return match ($this) {
self::PortalSync => 'Portal-Abgleich (iCal)',
self::PortalMail => 'Portal-Postfach (Schnellweg)',
self::AiOffers => 'KI: Angebotsentwürfe',
self::AiMarketing => 'KI: Vermarktungsassistent',
self::AiGuestMail => 'KI: Gästekommunikation',
};
}
public function description(): string
{
return match ($this) {
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
};
}
/**
* Whether the application asks this switch before it acts. Only wired services are offered for switching.
*/
public function isWired(): bool
{
return match ($this) {
self::PortalSync, self::PortalMail => true,
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
};
}
/**
* What applies to a landlord the operator has not decided about yet. The portal services were part of
* the product before there were landlords, so switching tenancy on must not silently stop them.
*/
public function enabledByDefault(): bool
{
return $this->isWired();
}
/**
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
*/
public function usesApiKey(): bool
{
return match ($this) {
self::AiOffers, self::AiMarketing, self::AiGuestMail => true,
self::PortalSync, self::PortalMail => false,
};
}
/**
* @return list<self>
*/
public static function wired(): array
{
return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired()));
}
}
+30 -2
View File
@@ -14,7 +14,7 @@ enum UserRole: string implements HasDescription, HasLabel
public function getLabel(): string
{
return match ($this) {
self::Admin => 'Administrator',
self::Admin => 'Mandanten-Administrator',
self::Rentals => 'Vermietung',
self::Content => 'Inhalte',
};
@@ -23,9 +23,37 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Admin => 'Alles, inklusive Benutzerverwaltung',
self::Admin => 'Alles im eigenen Mandanten, inklusive Benutzerverwaltung',
self::Rentals => 'Buchungen, Gäste, Preise, Angebote und Bewertungen',
self::Content => 'Bilder, Texte, FAQ, Hinweise und Bewertungen',
};
}
public function grants(Permission $permission): bool
{
return in_array($permission, $this->permissions(), true);
}
/**
* Abilities inside the current landlord. The operator is not a role here.
*
* @return list<Permission>
*/
public function permissions(): array
{
return match ($this) {
self::Admin => Permission::cases(),
self::Rentals => [
Permission::Bookings,
Permission::Properties,
Permission::Guests,
Permission::Reviews,
Permission::Channels,
],
self::Content => [
Permission::Content,
Permission::Reviews,
],
};
}
}
+10
View File
@@ -14,6 +14,16 @@ public static function notAvailable(): self
return new self('Der gewünschte Zeitraum ist leider nicht mehr frei.');
}
public static function offerExpired(): self
{
return new self('Dieses Angebot ist nicht mehr gültig. Bitte melden Sie sich bei uns – gern erstellen wir Ihnen ein neues Angebot.');
}
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 invalidTransition(string $statusLabel, string $action): self
{
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
@@ -0,0 +1,50 @@
<?php
namespace App\Filament\Actions;
use App\Actions\AssignOccupationGuest;
use App\Enums\OccupationKind;
use App\Filament\Resources\Guests\Schemas\GuestForm;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Components\Utilities\Get;
class AssignGuestAction
{
public static function make(): Action
{
return Action::make('assignGuest')->label('Gast zuordnen')
->modalWidth('3xl')
->visible(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record)
&& ($record instanceof Booking || (! $record->trashed() && ! $record->is_representation && $record->occupationKind() === OccupationKind::Reservation)))
->authorize(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false)
->modalDescription('Einen vorhandenen Gast persönlich auswählen oder einen neuen Gast anlegen. Ein Namensfragment ist kein Identitätsnachweis. Die Zuordnung versendet keine Nachricht und ändert keine Belegungszeiträume.')
->fillForm(fn (Booking|BlockedPeriod $record): array => [
'mode' => 'existing', 'guest_id' => $record->guest_id, 'country' => 'DE',
'first_name' => $record instanceof BlockedPeriod ? ($record->ical_interpretation['fields']['guest_first_name'] ?? '') : '',
])
->schema([
Select::make('mode')->label('Zuordnung')->options(['existing' => 'Vorhandenen Gast auswählen', 'new' => 'Neuen Gast anlegen'])->required()->live(),
Select::make('guest_id')->label('Gast')->searchable()
->getSearchResultsUsing(fn (string $search): array => Guest::query()->whereNull('anonymized_at')
->where(fn ($query) => $query->where('first_name', 'like', '%'.$search.'%')->orWhere('last_name', 'like', '%'.$search.'%')->orWhere('email', 'like', '%'.$search.'%'))
->orderBy('last_name')->orderBy('id')->limit(50)->get()->mapWithKeys(fn (Guest $guest): array => [$guest->id => $guest->full_name.($guest->email ? ' · '.$guest->email : ' · E-Mail unbekannt')])->all())
->getOptionLabelUsing(fn ($value): ?string => Guest::find($value)?->full_name)
->visible(fn (Get $get): bool => $get('mode') === 'existing')->required(fn (Get $get): bool => $get('mode') === 'existing'),
Section::make('Kontakt & Adresse')->columns(2)->visible(fn (Get $get): bool => $get('mode') === 'new')
->schema(GuestForm::contactFields()),
Section::make('Notizen & Markierungen')->visible(fn (Get $get): bool => $get('mode') === 'new')
->schema(GuestForm::personalFields()),
])
->action(function (Booking|BlockedPeriod $record, array $data, AssignOccupationGuest $assign): void {
$assign->handle($record, $data['mode'] === 'existing' ? (int) $data['guest_id'] : null, $data);
$record->refresh()->load('guest');
Notification::make()->title('Gast zugeordnet')->success()->send();
});
}
}
Loaded 100 of 740 files, more files were not shown because too many files have changed in this diff. Show more