Compare commits
101
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4c9e6992f4 | ||
|
|
c8bb0f6e97 | ||
|
|
81c025f1ee | ||
|
|
5ba9ae08ab | ||
|
|
0c4187edaf | ||
|
|
5baf39441f | ||
|
|
89d569b6c8 | ||
|
|
a73b164ea1 | ||
|
|
eafab8a2cb | ||
|
|
e7cc37a15b | ||
|
|
cc47cac93e | ||
|
|
b5ff837dcd | ||
|
|
d42c42059c | ||
|
|
f5f18cd984 | ||
|
|
1c757f7429 | ||
|
|
70a39315e2 | ||
|
|
b9225f5fb8 | ||
|
|
876a0a20f3 | ||
|
|
4e6ad792eb | ||
|
|
d2b1a853dc | ||
|
|
791786ed3e | ||
|
|
d02f3e05c7 | ||
|
|
8bcda9a4bc | ||
|
|
e74033a958 | ||
|
|
add2367869 | ||
|
|
8b36e07dc4 | ||
|
|
a0497fcccd | ||
|
|
678e15256d | ||
|
|
2ae48e77fa | ||
|
|
386e2cf0a9 | ||
|
|
54efd3b858 | ||
|
|
7d998e2b81 | ||
|
|
e7efb06277 | ||
|
|
94df35e702 | ||
|
|
bc3872c01f | ||
|
|
0bba50bd7b | ||
|
|
5bffe44435 | ||
|
|
4389894959 | ||
|
|
2b2e732612 | ||
|
|
78aafd7c28 | ||
|
|
13f1b5856c | ||
|
|
f19d698203 | ||
|
|
f369018a68 | ||
|
|
c74199e978 | ||
|
|
4186872b3f | ||
|
|
f80c0f9f3b | ||
|
|
1fb839b24e | ||
|
|
2dca2bccfa | ||
|
|
952f8574c8 | ||
|
|
089d7f894b | ||
|
|
606ef8850f | ||
|
|
7c7955b982 | ||
|
|
e9db98701b | ||
|
|
c4ebccbbea | ||
|
|
8927f2eeb1 | ||
|
|
25b5a61461 | ||
|
|
e5a083ce71 | ||
|
|
0be1cfcdb8 | ||
|
|
2893192344 | ||
|
|
511faa64d2 | ||
|
|
98eabaeb0c | ||
|
|
1f59cbb9a5 | ||
|
|
783068501c | ||
|
|
6fe5bbc6e3 | ||
|
|
06df80e4db | ||
|
|
86374b1659 | ||
|
|
1b03689c46 | ||
|
|
e7f79e4075 | ||
|
|
f5d8be5eaf | ||
|
|
92fb01da9d | ||
|
|
01900d6550 | ||
|
|
8eae37e11d | ||
|
|
92ccf40312 | ||
|
|
6d8f1d6692 | ||
|
|
abf0e9004b | ||
|
|
3a0bb6e40f | ||
|
|
361acfa12a | ||
|
|
c459f7f83c | ||
|
|
4e66add1f0 | ||
|
|
f686996122 | ||
|
|
2c5b5fc2d7 | ||
|
|
9cd39f791f | ||
|
|
c55937d20e | ||
|
|
c2cf632ad5 | ||
|
|
f2e78446a8 | ||
|
|
03ad4667ac | ||
|
|
d9383cf3e5 | ||
|
|
e0e8c1d856 | ||
|
|
2f2aceb3bd | ||
|
|
2e3f2ca938 | ||
|
|
fd2a7f7ded | ||
|
|
220ec6bfdb | ||
|
|
afffa79289 | ||
|
|
f143a4f5f4 | ||
|
|
e6d4d89141 | ||
|
|
12e4079126 | ||
|
|
1871c04507 | ||
|
|
dfd3f77a5d | ||
|
|
f7cbc66451 | ||
|
|
04b5189bd8 | ||
|
|
9b8a851ce9 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git merge *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
+46
-88
@@ -1,105 +1,63 @@
|
||||
# Tests on every push; deployment to Strato for tags "v*" or by hand (Gitea › Actions › Deploy › Run workflow).
|
||||
# Needs a Gitea act_runner (e.g. on the private server) and these repository secrets:
|
||||
# DEPLOY_SSH_KEY private key whose public key is stored at Strato (SFTP & SSH)
|
||||
# DEPLOY_HOST package-specific SSH server, e.g. 51539426.ssh.w1.strato.hosting (not ssh.strato.de)
|
||||
# DEPLOY_USER SSH user from the Strato customer login
|
||||
# DEPLOY_PATH e.g. fewo-production
|
||||
# DEPLOY_PHP e.g. /opt/RZphp84/bin/php-cli
|
||||
# DEPLOY_URL e.g. https://www.fewo-stommer.de
|
||||
name: Deploy
|
||||
|
||||
name: Deploy FeWo mit PipelineManager
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
branches: [develop, main]
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
environment:
|
||||
description: Ziel
|
||||
type: choice
|
||||
options: [production, staging]
|
||||
default: production
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
mariadb:
|
||||
image: mariadb:11.8
|
||||
env:
|
||||
MARIADB_DATABASE: fewo_test
|
||||
MARIADB_ROOT_PASSWORD: test
|
||||
ports: ['3306:3306']
|
||||
options: >-
|
||||
--health-cmd="healthcheck.sh --connect --innodb_initialized"
|
||||
--health-interval=5s --health-timeout=5s --health-retries=20
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, pdo_sqlite, sqlite3, pdo_mysql, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: Install
|
||||
run: |
|
||||
composer install --no-interaction --no-progress --prefer-dist
|
||||
npm ci --no-audit --no-fund
|
||||
npm run build
|
||||
cp .env.example .env
|
||||
php artisan key:generate
|
||||
|
||||
- name: Tests (SQLite)
|
||||
run: php artisan test --compact
|
||||
|
||||
- name: Tests (MariaDB 11.8, wie auf Strato)
|
||||
env:
|
||||
DB_CONNECTION: mariadb
|
||||
DB_HOST: 127.0.0.1
|
||||
DB_PORT: '3306'
|
||||
DB_DATABASE: fewo_test
|
||||
DB_USERNAME: root
|
||||
DB_PASSWORD: test
|
||||
run: php artisan test --compact
|
||||
|
||||
deploy:
|
||||
needs: test
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||
# 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
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: SSH key
|
||||
- name: Anwendung im Manager-Container vorbereiten und testen
|
||||
id: build
|
||||
run: |
|
||||
mkdir -p ~/.ssh
|
||||
printf '%s\n' "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
|
||||
chmod 600 ~/.ssh/deploy_key
|
||||
ssh-keyscan -H "${{ secrets.DEPLOY_HOST }}" >> ~/.ssh/known_hosts
|
||||
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: Deploy
|
||||
- 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_PATH: ${{ secrets.DEPLOY_PATH }}
|
||||
DEPLOY_PHP: ${{ secrets.DEPLOY_PHP }}
|
||||
DEPLOY_URL: ${{ secrets.DEPLOY_URL }}
|
||||
DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
|
||||
DEPLOY_KNOWN_HOSTS: ${{ secrets.DEPLOY_KNOWN_HOSTS }}
|
||||
run: |
|
||||
export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key"
|
||||
bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy
|
||||
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
|
||||
@@ -24,6 +24,7 @@
|
||||
/storage/*.key
|
||||
/storage/pail
|
||||
/vendor
|
||||
/.pipeline/
|
||||
_ide_helper.php
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
@@ -32,3 +33,4 @@ Thumbs.db
|
||||
# Deployment settings with access data
|
||||
/scripts/deploy.*.env
|
||||
!/scripts/deploy.example.env
|
||||
storage/app/private/exports/
|
||||
@@ -1,8 +1,8 @@
|
||||
# Ferienwohnung Stommer
|
||||
|
||||
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`).
|
||||
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`.
|
||||
@@ -16,11 +16,11 @@ # Ferienwohnung Stommer
|
||||
- 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`.
|
||||
- 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 ===
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# BOOKING-COMPLIANCE-HANDOVER
|
||||
|
||||
Technische Fakten für die nachgelagerte Compliance-Prüfung. **Keine rechtlichen Bewertungen**, keine Änderung von CMS-Rechtstexten. Stand: 30.10.2026, Entwicklungsstand Branch `feature/buchung-e2e` (nicht deployt). Details: `BOOKING-E2E-IMPLEMENTATION.md`.
|
||||
|
||||
## 1. Tatsächlicher Ablauf des Vertragsschlusses (Direktbuchung)
|
||||
1. Gast sendet das Anfrageformular (`/buchen`, Livewire; Bot-Schutz: Honeypot, Zeitsperre, Rate-Limits). Eingabe: Name, E-Mail, optional Telefon/Adresse, Nachricht, Zeitraum, Personen, optional Rabattcode, Einwilligungs-Checkbox Datenschutz, optional Newsletter-Opt-in.
|
||||
2. System prüft Verfügbarkeit und berechnet den Preis (`PriceCalculator`). Je Wohnung: **Vorreservierung** an (Kalender wird bis zum Ablauf der Haltefrist gesperrt) oder aus (keine Sperre).
|
||||
3. **Manueller Modus (Standard):** Eingangsbestätigung an den Gast (unverbindlich, ggf. mit Ablaufzeit der Vormerkung), Mitteilung an den Betreiber; Betreiber erstellt/sendet das Angebot im Admin.
|
||||
**Automatischer Modus:** Angebot geht sofort an den Gast, wenn alle Prüfungen bestanden sind (Details Implementation §Phase 3); sonst Rückfall auf manuell.
|
||||
4. Angebot (Version n): E-Mail mit Preisaufstellung und PDF-Entwurf (Angebot/Mietvertrag) im Anhang und einem **signierten, befristeten Link** (`/angebot/{id}?v=n`, Ablauf = Angebotsfrist).
|
||||
5. Der Link öffnet die Angebotsseite (GET, ändert nichts). Sie zeigt Zeitraum, Preiszeilen, Zahlungsplan, Mietbedingungen, Stornobedingungen, „Gültig bis“, Hinweistext (`offer.accept_note`), Checkbox „Ich habe die Angaben und Bedingungen dieses Angebots gelesen“ und die Schaltfläche (Beschriftung `offer.accept_button`, CMS; Standardtext aktuell „Angebot zahlungspflichtig annehmen“). Daneben „Angebot ablehnen“.
|
||||
6. Annahme = POST auf eine signierte URL (CSRF-geschützt, Rate-Limit 10/min). Eine Transaktion prüft Version, Status, Frist, Prüfsumme des Angebots, Verfügbarkeit (und vorher Aktualität der Portalkalender), schreibt den Nachweis und setzt die Buchung auf `Confirmed`.
|
||||
7. Danach: Vertrags-PDF (final) wird erzeugt; Bestätigungs-E-Mail mit PDF geht an den Gast; Betreiber erhält eine Annahme-Mail. Fristen: Anzahlung = Annahmetag + `deposit_due_days` (Standard 7), Rest zum vereinbarten Termin.
|
||||
8. Der Kalender ist sofort belegt (iCal-Ausgangsfeed wird bei jedem Abruf live berechnet); für Portale mit manueller Sperre entstehen Aufgaben (+ optionaler Webhook).
|
||||
|
||||
## 2. Angebots- und Annahmenachweise (Datenbank `bookings`)
|
||||
| Feld | Inhalt |
|
||||
|---|---|
|
||||
| `offer_version`, `offer_sent_at`, `hold_expires_at` | Version, Versandzeit, Gültigkeit (nach Annahme `null`) |
|
||||
| `quote`, `total`, `deposit`, `balance_due_on` | Preis und Zahlungsplan der Version |
|
||||
| `offer_terms` (JSON) | eingefrorene Texte: Mietbedingungen, Storno, Hausordnung, Vertragseinleitung/-schluss, Vertragshinweis, Annahmehinweis, Button-Beschriftung; Anzahlungsfrist; Vermieter- und Bankdaten; `captured_at` |
|
||||
| `offer_hash` | SHA-256 über Version, Termine, Personen, Quote, Beträge, Zahlungstermin, Snapshot |
|
||||
| `acceptance` (JSON), `accepted_at` | Version, Zeitpunkt, Gültigkeit, Gesamtbetrag, `offer_hash`, `quote_sha256`, `terms_sha256` (Hash der **angezeigten** Texte), Button-Text, `via=offer_link` |
|
||||
| `confirmed_at`, `deposit_due_on`, `contract_path`, `offer_path` | Bestätigungszeit, Fälligkeit, Pfade der PDFs |
|
||||
| `confirmation_sent_at`, `confirmation_failed_at` | Zustellstatus der Bestätigungsmail (nur Versand an den Mailserver, kein Lesenachweis) |
|
||||
Es wird **keine IP-Adresse, kein User-Agent und kein Token** im Nachweis gespeichert. Der Nachweis zeigt „diese Angebotsversion mit diesem Inhalt wurde über den signierten Link angenommen“; er identifiziert den Handelnden nur über den Besitz des Links.
|
||||
Nach Versand geänderte CMS-Texte wirken **nicht** auf bestehende Angebote (Snapshot). Eine Änderung der gespeicherten Angebotsdaten verhindert die Annahme (Hash-Prüfung, Postfachmeldung).
|
||||
|
||||
## 3. Technische Darstellung der Vertragsinformationen
|
||||
- Angebotsseite (HTML) und PDF (Angebot/Entwurf → final) werden aus demselben Snapshot gerendert. PDFs liegen als Dateien (nicht neu gerendert beim Abruf); „Mietvertrag neu erzeugen“ im Admin nutzt den Snapshot.
|
||||
- Das Angebots-PDF hängt an der Angebotsmail (dauerhaft speicherbar); das finale Vertrags-PDF an der Bestätigungsmail. Auf der Angebotsseite selbst gibt es keinen PDF-Download-Link (Hinweis auf den Anhang).
|
||||
- Hausordnung steht im PDF, nicht auf der Angebotsseite. Die Texte sind **noch Mustertexte** im CMS (`[MUSTER …]`); im Livebetrieb werden automatische Angebote nur bei freigegebenen (nicht-Muster) Texten und gefüllter IBAN gesendet.
|
||||
- Zahlungspflicht-Hinweis und Button-Beschriftung sind CMS-Felder (`offer.accept_note`, `offer.accept_button`).
|
||||
|
||||
## 4. Speicherorte und Aufbewahrung
|
||||
- PDFs: `storage/app/private/contracts/tenants/{tenant}/bookings/{booking}/` (nicht per Web erreichbar). Buchungsdaten/Nachweise: Datenbank, Tabelle `bookings`; Gäste: `guests`.
|
||||
- Löschung/Anonymisierung (`guests:anonymize`, täglich): nie bestätigte Anfragen nach 6 Monaten (`FEWO_RETENTION_INQUIRY_MONTHS`); Gästedaten bestätigter Buchungen 10 Jahre (`FEWO_GUEST_RETENTION_YEARS`) – Vorschlagswerte laut `docs/LOESCHKONZEPT.md`. **Vertragsdokumente haben dort noch keine Löschfrist (als Lücke vermerkt).** `internal_notes`/`acceptance` werden nicht gesondert gelöscht.
|
||||
- Datenbank-Backup täglich (`backup:database`, 14 Dateien), enthält Gäste- und Buchungsdaten.
|
||||
- Logs: bei Mail-/Sync-/Auto-Angebot-Fehlern nur Meldungstext, Exception-Klasse und Buchungs-ID, keine Adressen, Links oder Tokens (Laufzeit: Laravel-Log, Kanal `daily`, 14 Tage).
|
||||
|
||||
## 5. Automatisch versendete Nachrichtentypen
|
||||
| Klasse | Empfänger | Auslöser |
|
||||
|---|---|---|
|
||||
| `ReservationReceived` | Gast | Anfrage (nicht bei erfolgreichem Auto-Angebot) |
|
||||
| `NewReservation` | Betreiber | Anfrage (inkl. Hinweis „Angebot automatisch versendet“ bzw. Gründe) |
|
||||
| `OfferMade` | Gast | Angebot (manuell/automatisch) |
|
||||
| `OfferAnswered` | Betreiber | Annahme/Ablehnung durch den Gast |
|
||||
| `BookingConfirmed` (+ Vertrag-PDF) | Gast | Annahme / direkte Bestätigung; Nachversand durch Admin/Befehl |
|
||||
| `BookingDeclined`, `ReservationExpired` | Gast / Betreiber | Ablehnung durch Betreiber / Ablauf |
|
||||
| `PaymentReminder`, `ArrivalInformation`, `ReviewRequest` | Gast | Fristen (bestehend, unverändert) |
|
||||
| `MarketingConsentRequest` | Gast | nur bei Newsletter-Opt-in (bestehend) |
|
||||
| Digest/Kanal-/Postfach-Meldungen | Betreiber | bestehend |
|
||||
Im **Testbetrieb** gehen alle Mails ausschließlich an die Testadresse (`App\Support\Settings`, unverändert).
|
||||
|
||||
## 6. Technische Stornierungs-/Kündigungsmöglichkeiten
|
||||
- Gast: Angebot **ablehnen** (Angebotsseite, bis zur Annahme). Eine Stornierung/Kündigung **nach** Annahme ist im Gastbereich **nicht** vorgesehen (kein Kundenkonto, kein Stornolink); sie läuft über Kontakt (Telefon/E-Mail).
|
||||
- Betreiber: Aktionen *Ablehnen*, *Stornieren* (setzt `Cancelled`, gibt den Kalender frei), Vormerkung verlängern. Eine automatische Berechnung von Stornokosten gibt es nicht; die Stornobedingungen sind reiner CMS-Text im Snapshot.
|
||||
- Es gibt keine automatische Stornierung bei Nichtzahlung (nur Zahlungserinnerungen).
|
||||
|
||||
## 7. Externe Datenquellen und Empfänger
|
||||
- Eingehend: iCal-Feeds der Portale (nur Zeiträume, ggf. Titel/Beschreibungstexte), Portal-Benachrichtigungs-Mails aus dem Betreiber-Postfach (IMAP) – können Gästedaten enthalten (Aufbewahrung 90 Tage laut Löschkonzept).
|
||||
- Ausgehend: iCal-Feeds je Portal (nur Belegungen, ohne Gästedaten, Zugriff über zufälligen Token pro Kanal); optional signierter Webhook an die Betreiber-Automation (n8n) mit Aufgabendaten (Zeitraum, Kanal); Mailserver (Strato SMTP).
|
||||
- Aufgezeichnet: Abrufe der Export-Feeds je Kanal (Zeit, Methode, User-Agent, Status) in `channel_export_requests`.
|
||||
- Keine externen Dienste im Buchungsweg (kein Captcha, keine Zahlungs-/Tracking-Dienste).
|
||||
|
||||
## 8. Cookies / Technologien (neu betroffen)
|
||||
Keine neuen Cookies oder Browser-Speicher. Die Angebotsseite nutzt die bestehende Laravel-Sitzung und das XSRF-Cookie (CSRF-Schutz des Annahmeformulars). Neue deutsche Fehlerseiten (403/404/419/429/500/503) laden keine externen Ressourcen.
|
||||
Die Angebotsseite ist `noindex`; Links stehen in Zugriffsprotokollen des Webservers (signierte URL) – Aufbewahrung dort liegt bei Strato.
|
||||
|
||||
## 9. Bekannte technische Einschränkungen, die für die Prüfung relevant sind
|
||||
- Der Nachweis enthält keine IP/Geräteangabe (Entscheidung offen, siehe READINESS Frage 5).
|
||||
- Standard-Buttontext enthält „zahlungspflichtig annehmen“, nicht wörtlich „Zahlungspflichtig buchen“ (CMS, Betreiber).
|
||||
- Bestätigungsseite nach Annahme (Erfolgsmeldung) und Bestätigungs-E-Mail sind die einzigen unverzüglichen Bestätigungen; Zustellung der Mail kann scheitern (Statusfeld, Nachversand).
|
||||
- Widerrufsinformationen, AGB-Link, Datenschutzlink auf der Angebotsseite sind **nicht** automatisch eingebaut (nur CMS-Texte `contract.terms`/`stay.cancellation`); der Datenschutzlink am Anfrageformular ist laut MVP-TECHNICAL-GATE Blocker #2 offen.
|
||||
@@ -0,0 +1,81 @@
|
||||
# BOOKING-E2E-ACCEPTANCE
|
||||
|
||||
Stand: 30.10.2026 · Branch `feature/buchung-e2e` · Umgebung: lokale Entwicklung, PHP 8.4, **SQLite**, Mails/HTTP gefaket.
|
||||
|
||||
## Ergebnis in Kürze
|
||||
- **Vollsuite: 561 Tests, 561 bestanden** (`php artisan test`, 30.10.2026, 4. Lauf). Davon neu: 14 + 3 in `BookingAcceptanceTest` (17), 12 in `AutoOfferTest`; 1 bestehender Test bereinigt (`dump()`). `vendor/bin/pint --dirty`: sauber.
|
||||
- Hinweis zur Stabilität: In zwei früheren Läufen schlugen `WebsiteTenancyTest` (Status 301) und `PrivacyHardeningTest` (Datei im Test-Datenträger fehlt) fehl. Diese Läufe liefen zeitgleich mit einem zweiten Testlauf bzw. nach einer Fehlkonfiguration meinerseits (fehlender `use`-Import, inzwischen behoben); im sauberen Einzellauf bestehen sie. Eine Ursachenklärung für `WebsiteTenancyTest` (301 beim Parallellauf) habe ich nicht durchgeführt.
|
||||
- **NICHT durchgeführt (BLOCKED):** MariaDB-Parallelitätstests, Browser-E2E, Zustellung echter Test-Mails, Sichtprüfung der PDFs, Staging-Durchlauf. Gründe unten.
|
||||
- **Empfehlung: NO-GO für Staging-Freigabe/Aktivierung echter Buchungen**, solange die BLOCKED-Punkte offen sind. Technisch kein bekannter Fehler im Code; die Lücke ist fehlender praktischer Nachweis.
|
||||
|
||||
## Blockierte Nachweise (Warum)
|
||||
| Nachweis | Status | Grund / nötige Entscheidung |
|
||||
|---|---|---|
|
||||
| Echte Parallelität auf MariaDB | **BLOCKED** | Lokal ist kein MariaDB vorhanden. Ich habe ein portables MariaDB (ZIP von archive.mariadb.org) in das Scratch-Verzeichnis geladen, **den Start der heruntergeladenen Binärdatei verweigerte das Berechtigungssystem** („Code from External“). Ich habe das nicht umgangen. Optionen: MariaDB/Docker selbst bereitstellen und `DB_CONNECTION=mariadb` für einen Testlauf freigeben, oder die Tests gegen die Staging-DB laufen lassen (Freigabe nötig). Der Schutz beruht auf `SELECT … FOR UPDATE` (Wohnung + Buchung); unter SQLite ist `lockForUpdate` wirkungslos, die Tests belegen daher die **Logik** (frisches Neuladen unter Sperre, Idempotenz mit veralteter Modellkopie), nicht das Sperrverhalten der Datenbank. |
|
||||
| Browser-E2E, Tastatur/Screenreader | BLOCKED | nicht ausgeführt |
|
||||
| Echte Mailzustellung (SPF/DKIM, Anhang öffnen) | BLOCKED | Staging läuft mit `MAIL_MAILER=log` (MVP-TECHNICAL-GATE #3); Staging-Deployment ohne gesonderte Freigabe nicht erlaubt |
|
||||
| PDF-Sichtprüfung | BLOCKED | PDFs werden in Tests nur auf Existenz und Snapshot-Quelle geprüft, nicht visuell |
|
||||
| Staging-Durchlauf mit Mail-Umleitung | BLOCKED | Deployment/Migration auf Staging nicht freigegeben |
|
||||
|
||||
## Testfälle (Auftrag §13)
|
||||
Legende: **PASS** = automatisiert ausgeführt und bestanden · **PARTIAL** = Logik getestet, Praxisnachweis offen · **BLOCKED** = nicht ausgeführt · **EXISTING** = durch bereits vorhandenen, bestehenden Test abgedeckt (in der Vollsuite grün).
|
||||
|
||||
| # | Fall | Ergebnis | Nachweis (Test) |
|
||||
|---|---|---|---|
|
||||
| 1 | Manuelle Anfrage ohne Vorreservierung | PASS | `AutoOfferTest::test_without_pre_reservation_a_request_blocks_nothing` (keine Sperre, Mailtext „noch nicht reserviert“, zweite Anfrage derselben Zeit möglich) |
|
||||
| 2 | Manuelle Anfrage mit Vorreservierung | PASS | `test_manual_mode_sends_the_receipt_and_no_offer` |
|
||||
| 3 | Automatisches Angebot mit Vorreservierung | PASS | `test_automatic_mode_sends_the_offer_instead_of_the_receipt`, `…_can_be_accepted_end_to_end` |
|
||||
| 4 | Auto ohne Vorreservierung | PASS | `test_automatic_mode_without_pre_reservation_falls_back_to_manual_and_says_why` (Grund in Notiz + Betreiber-Mail); Formular lehnt die Kombination ab (Regel in `PropertyForm`, **nicht** per Test geprüft) |
|
||||
| 5 | Angebot aufrufen und annehmen | PASS (HTTP) / BLOCKED (Mail-Client) | `test_accepting_twice_over_http_…`, `OfferWorkflowTest` |
|
||||
| 6 | Bestätigung + PDF | PARTIAL | Mail mit Vertrag gesendet, Datei vorhanden (`test_acceptance_records_the_evidence_and_confirms_once`); Inhalt nicht visuell geprüft |
|
||||
| 7 | Kalender und iCal-Ausgabe | PARTIAL | Belegung/`occupying()` geprüft; Feed-Inhalt nach Annahme nicht eigens neu getestet (Feed wird live aus DB gebaut; `ChannelExportRequestTest` EXISTING) |
|
||||
| 8 | Abgelaufene Haltefrist | PASS | `test_expired_offer_cannot_be_accepted`; `OfferWorkflowTest::test_offer_holds_the_dates_until_it_expires` |
|
||||
| 9 | Annahme kurz vor Fristablauf | PARTIAL | Frist wird in der Transaktion gegen die gesperrte Zeile geprüft; Randfall (Sekunden vor Ablauf) nicht eigens getestet. Bekannte Lücke: signierte POST-URL läuft mit der Frist ab → 403 mit neuer deutscher Seite statt Angebots-Hinweis |
|
||||
| 10 | Doppelte Annahme | PASS | `test_second_acceptance_…_idempotent`, `test_stale_copy_…`, `test_accepting_twice_over_http_…` (1× Bestätigung, 1× Betreiber-Mail) |
|
||||
| 11 | Gleichzeitige Annahmen | **BLOCKED** (MariaDB) | nur Logik (Fall 10) belegt |
|
||||
| 12 | Zwei konkurrierende Buchungen | PARTIAL | `test_two_overlapping_stays_cannot_both_become_binding` (sequenziell); echte Parallelität BLOCKED |
|
||||
| 13 | Konflikt durch externen Kalendereintrag | PASS | `test_conflicting_occupation_prevents_acceptance_and_leaves_no_evidence` |
|
||||
| 14 | Änderung von Preis/Bedingungen nach Versand | PASS | `test_changed_website_texts_do_not_alter…`, `test_tampered_offer_is_refused…`, `test_changed_terms_snapshot_is_refused` |
|
||||
| 15 | Erfolgreicher Import | EXISTING | `ChannelSyncTest` |
|
||||
| 16 | Fehlgeschlagener Import | PASS | `test_stale_calendar_import_blocks_the_automatic_offer` (HTTP 500 gefaket → Kanal bleibt veraltet), `test_acceptance_is_refused_while_a_portal_calendar_is_stale` |
|
||||
| 17 | Sofortbuchungsportal vor Abruf | PASS | `test_instant_booking_portal_holds_the_offer_back_until_it_fetched_our_feed` |
|
||||
| 18 | Sofortbuchungsportal nach nachgewiesenem Abruf | PASS | derselbe Test (Angebot nach Abruf per `bookings:auto-offers`); Abruf als Datensatz erzeugt, nicht über den echten Feed-Endpunkt |
|
||||
| 19 | Kanal ohne Sofortbuchung | PASS | `test_portal_without_instant_booking_needs_no_proof` |
|
||||
| 20 | Nicht zuordenbarer Abruf | PASS | `test_unattributable_feed_request_is_not_recorded_as_proof`, `test_feed_fetch_before_the_block_or_failed_fetch_or_other_channel_is_no_proof` |
|
||||
| 21 | Sync-Fehler nach bestätigter Buchung | PASS | `test_failing_portal_task_creation_does_not_fail_the_acceptance` |
|
||||
| 22 | Anfrage über Portal-Mail | EXISTING | `PortalMailTest` (nicht Teil dieser Änderung) |
|
||||
| 23 | Portal-Mail unvollständig | EXISTING | `PortalMailTest::…without_readable_dates…` |
|
||||
| 24 | iCal ohne Gastdaten | EXISTING | `ChannelOccupationResolutionTest`, `ChannelSyncTest` |
|
||||
| 25 | Bereits verbindliche Portalbuchung | EXISTING | `PortalMailTest::test_booking_mail_blocks_immediately…` (Sperre, kein Annahmeprozess) |
|
||||
| 26 | Doppelt eintreffende Infos | EXISTING | `ChannelOccupationResolutionTest` (UID-/Alias-Fälle) |
|
||||
| 27 | Mailfehler bei Angebot | PASS | `test_failing_offer_mail_is_reported_but_the_offer_stays` |
|
||||
| 28 | Mailfehler bei Bestätigung | PASS | `test_failing_confirmation_mail_keeps_the_binding_booking_and_can_be_resent` (keine Adresse im Postfachtext) |
|
||||
| 29 | Wiederholter Nachversand | PASS | gleicher Test + `test_command_retries_failed_confirmations_once_the_mail_server_is_back` (genau 1 Zustellung) |
|
||||
| 30 | Abgelaufener/manipulierter Link | PASS | `test_invalid_signature_shows_the_german_error_page`, `OfferWorkflowTest::test_offer_page_needs_a_valid_signature`, `…older_offer_version…` |
|
||||
| 31 | Fehlerhafte Session / 419 | PARTIAL | deutsche 419-Seite angelegt; **kein Test**, der ein 419 auslöst |
|
||||
| 32 | Regression bei deaktivierter Automatik | PASS | Standard `manual`; gesamte bestehende Suite grün (561/561) |
|
||||
| – | GET löst nichts aus | PASS | `test_get_on_the_offer_link_never_changes_the_booking` |
|
||||
| – | Testbetrieb/Mail-Umleitung unverändert | EXISTING | bestehende Tests (`MailRoutingTest` u. a.) grün; Code in `Settings` nicht angefasst |
|
||||
| – | Live: Muster-Texte blockieren Auto-Angebot | PASS | `test_live_operation_needs_released_contract_texts_for_automatic_offers` |
|
||||
|
||||
## Kontrolle nach Tests (§13 Abnahmekriterien) – was geprüft wurde
|
||||
Datenbankstatus, Annahmenachweis (Felder, Hash), gespeicherte Angebotsversion und Snapshot, Postfacheinträge, gesendete Mailklassen und Anzahl: **per Assertion in den Tests**. Belegungskalender: `occupying()`/Verfügbarkeitsprüfung. **Nicht geprüft:** ausgehende iCal-Feeds nach Annahme (kein eigener Test), tatsächliche E-Mail-Inhalte außer den genannten Textstellen, PDF-Inhalt, Admin-Ansicht (Infolist/Aktion „Bestätigung erneut senden“ sind nur durch die Seitenaufrufe der bestehenden Suite „gerendert“, die neue Aktion selbst hat **keinen** Test), Monitoring.
|
||||
|
||||
## Bekannte Fehler und Einschränkungen
|
||||
1. Neue Admin-Aktion und die Property-Formulargültigkeit (auto + ohne Vorreservierung) sind ungetestet.
|
||||
2. Keine Tests für 419 und die Annahme in der letzten Sekunde.
|
||||
3. Echte Datenbanksperren unbelegt (siehe oben) – wichtigster offener Punkt.
|
||||
4. Migrationen wurden nur in der SQLite-Testdatenbank ausgeführt; nicht gegen MariaDB (Syntax ist Standard `json`/`string`/`boolean`/`timestamp`, aber ungeprüft).
|
||||
5. Das Verhalten „Annahme verlangt aktuellen Import“ gilt für alle Wohnungen mit aktivem Import (nicht nur Automatik) und kann Annahmen bei gestörtem Portalimport verhindern (gewollt, siehe Implementation §Restrisiken).
|
||||
6. Ursache der früheren Einzelfehler in `WebsiteTenancyTest` nicht geklärt (siehe oben).
|
||||
|
||||
## Status produktive Einsatzfähigkeit
|
||||
Code und automatisierte Tests: bereit zur Überprüfung (Review). **Nicht einsatzbereit für echte Gäste**, solange offen: MariaDB-Parallelitätsnachweis, Staging-Durchlauf mit echter Mailzustellung und PDF-Sichtprüfung, Produktivumgebung (MVP-TECHNICAL-GATE #1–#4), freigegebene Vertragstexte, separate Compliance-Prüfung.
|
||||
|
||||
## GO / NO-GO
|
||||
**NO-GO** für Aktivierung automatischer oder verbindlicher Online-Buchungen mit echten Gästen. **GO** für: Code-Review, Merge in einen Feature-Branch, anschließend MariaDB-Test und Staging-Migration nach ausdrücklicher Freigabe.
|
||||
|
||||
## Nächste Schritte (Reihenfolge)
|
||||
1. Entscheidung, wie MariaDB für den Parallelitätstest bereitgestellt wird (lokal selbst installiert oder Docker; oder Test gegen Staging-DB).
|
||||
2. Dann: zwei-Prozess-Test (gleichzeitige Annahme, konkurrierende Buchung) und Migrationen auf MariaDB.
|
||||
3. Freigabe für Staging-Migration + Deployment → Durchlauf mit Mail-Umleitung, PDF- und Feed-Prüfung.
|
||||
@@ -0,0 +1,78 @@
|
||||
# BOOKING-E2E-IMPLEMENTATION
|
||||
|
||||
Stand: 30.10.2026 · Branch `feature/buchung-e2e` (von `develop`) · nur Entwicklungsumgebung (SQLite-Tests). **Nichts committet, nichts deployt, keine Migration auf Staging/Produktion.**
|
||||
Grundlage: `BOOKING-E2E-READINESS.md`. Ergebnisse der Prüfungen: `BOOKING-E2E-ACCEPTANCE.md`.
|
||||
|
||||
## 1. Umgesetzte Änderungen
|
||||
|
||||
### Phase 1 – Sicherheitskern
|
||||
| Thema | Umsetzung |
|
||||
|---|---|
|
||||
| Angebots-Snapshot | `SendOffer` friert pro Version in `bookings.offer_terms` ein: Mietbedingungen, Storno, Hausordnung, Vertragseinleitung/-schluss, Vertragshinweis, Annahmehinweis, Button-Beschriftung, Anzahlungsfrist, Vermieter- und Bankdaten (`App\Documents\OfferTerms`). Angebotsseite, Angebots-PDF, Final-PDF und Annahme lesen aus dem Snapshot (`Booking::offerText()/offerHtml()`); Altbuchungen ohne Snapshot fallen auf die Live-Texte zurück. Direkte Bestätigung durch den Admin friert beim Bestätigen ein. |
|
||||
| Angebots-Hash | `bookings.offer_hash` = SHA-256 über Version, Termine, Personen, Quote, Beträge, Zahlungstermin und Snapshot (ohne Gültigkeit, die der Betreiber verlängern darf). |
|
||||
| Atomare Annahme | `AcceptOffer`: eine Transaktion mit Sperre auf Wohnung **und** Buchungszeile (`Booking::lockForTransition()`), dann Version, Status, Frist, Hash und Verfügbarkeit prüfen, Nachweis schreiben **und** `Confirmed` setzen – oder nichts. Dieselbe Wohnungssperre nutzen jetzt `CreateReservation`, `SendOffer`, `ConfirmBooking`, `RejectOffer`. |
|
||||
| Idempotenz | Zweite Annahme derselben Version: keine zweite Buchung, keine zweite Mail, Gast sieht „bereits verbindlich bestätigt“. Auch eine veraltete Modellkopie wird über die gesperrte Zeile erkannt. |
|
||||
| Nachweis | `acceptance` (JSON): Angebotsversion, Annahme-/Versandzeit, Gültigkeit, Gesamtbetrag, `offer_hash`, `quote_sha256`, `terms_sha256` (über den **gezeigten** Snapshot), Button-Text, `via`. Keine IP, kein Token. |
|
||||
| Mail nach Commit | `ConfirmBooking::deliver()` (Vertrag + Mail) läuft nach dem Commit; Fehler setzen `confirmation_failed_at`, schreiben ins Postfach (`InboxMessageKind::ConfirmationFailed`) und lassen die Buchung bestehen. Ohne erzeugtes Vertrags-PDF wird keine Bestätigung ohne Anhang versendet. |
|
||||
| Nachversand | Admin-Aktion „Bestätigung erneut senden“ (Buchungsseite), Befehl `bookings:resend-confirmations` (alle 15 Min., nur Fehlversuche der letzten 3 Tage). |
|
||||
| Angebotsmail | `SendOffer::deliver()`: Fehler → Postfach (`OfferMailFailed`), Angebot bleibt gespeichert, Admin erhält verständliche Meldung (Link kann kopiert werden). |
|
||||
| Portal-Sync | `BookingObserver`: Fehler beim Anlegen von Portalaufgaben schlagen nicht mehr auf den Gast durch; Postfachmeldung `SyncFailed`. |
|
||||
| Logs | Fehler werden nur mit Klasse + Buchungs-ID geloggt (Mailer-Meldungen können Adressen enthalten). Keine Tokens/Links. |
|
||||
| Fehlerseiten | Deutsche Seiten 403/404/419/429/500/503 (`resources/views/errors`), 403 erklärt abgelaufene/ungültige Links, 419 „Sitzung abgelaufen – nichts wurde verändert“. Betrifft alle Seiten der Anwendung (vorher englische Standardseiten). |
|
||||
| Aufräumen | Debug-`dump()` aus `OfferWorkflowTest` entfernt. |
|
||||
|
||||
### Phase 2 – Betriebsmodi und Vorreservierung
|
||||
- Je Wohnung (`properties`): `offer_mode` (`manual` Standard / `automatic`) und `pre_reservation_enabled` (Standard `true`), neben dem vorhandenen `hold_hours`. Einstellbar in der Wohnungsverwaltung (Abschnitt Zahlung/Vorreservierung). Validierung: *automatisch* + *ohne Vorreservierung* wird abgelehnt.
|
||||
- Ohne Vorreservierung entsteht eine `Reserved`-Anfrage **ohne** `hold_expires_at`; sie sperrt nichts (`occupying()`-Scope), läuft nicht ab und wird erst durch Angebot/Entscheidung des Betreibers weiterbewegt.
|
||||
- `CreateReservation` entscheidet über Mails: *manuell* → Eingangsbestätigung an Gast + Mitteilung an Betreiber; *automatisch und freigegeben* → nur das Angebot an den Gast, Betreiber-Mail „Angebot automatisch versendet“; *automatisch, aber nicht freigegeben* → Eingangsbestätigung + Betreiber-Mail mit den Gründen, Gründe zusätzlich in den internen Notizen. Keine doppelten Gast-Mails.
|
||||
- Eingangsbestätigung, Betreiber-Mail und Bestätigungsseite behaupten eine Vormerkung nur, wenn tatsächlich eine aktive Haltefrist besteht (genauer Ablaufzeitpunkt), sonst „noch nicht reserviert“.
|
||||
- Der bestehende Testbetrieb (`Settings`, Mail-Umleitung) ist **unverändert**; Modus und Testbetrieb sind unabhängig.
|
||||
|
||||
### Phase 3 – Kanalabhängige Freigabe
|
||||
`App\Actions\AutoOffer` + `App\Availability\CalendarClearance`:
|
||||
1. Stufe Betreiberfreigabe: im **Livebetrieb** müssen Mietbedingungen (kein „[MUSTER“), Storno und IBAN gefüllt sein; im Testbetrieb entfällt die Prüfung, damit der Ablauf mit Mustertexten testbar ist.
|
||||
2. Import: jeder aktive Importkanal braucht einen erfolgreichen Import innerhalb von `fewo.channels.fresh_within_minutes` (15, `FEWO_CHANNEL_FRESH_WITHIN_MINUTES`); sonst wird **einmal** ein Import versucht (Netzwerk außerhalb jeder Transaktion), danach gilt „nicht aktuell“.
|
||||
3. Sofortbuchung: Kanäle mit Buchungsmodell *Portalbuchung* oder *Gemischt* gelten als sofortbuchungsfähig (bestehendes Feld `booking_model`, keine neue Spalte). Freigabe nur, wenn dieser Kanal **nach Anlage der Sperre** (`created_at` + 1 s) unseren Feed mit **HTTP 200 und Zustand „live“** abgerufen hat (bestehende Tabelle `channel_export_requests`; Zuordnung über den kanaleigenen Token). Unzuordenbare Abrufe (falscher Token → 404) werden nicht protokolliert und zählen nie. Abrufe vor der Sperre, fehlgeschlagene (503) und Abrufe anderer Kanäle zählen nicht.
|
||||
4. Kanäle ohne Sofortbuchung: kein Abrufnachweis nötig.
|
||||
5. Verfügbarkeit erneut prüfen; Vorreservierung muss aktiv sein.
|
||||
6. Nicht freigegeben → kontrollierter Rückfall auf manuell; `bookings:auto-offers` (alle 5 Min.) versucht es für noch gehaltene Anfragen erneut (z. B. sobald das Portal den Feed abgerufen hat).
|
||||
7. **Bei der Annahme** (`AcceptOffer`): vor der Transaktion Import aufgefrischt; bleibt ein Importkanal veraltet, wird **nicht** gebucht, der Gast erhält eine verständliche Meldung, der Betreiber eine Postfachmeldung. Danach gesperrte Verfügbarkeitsprüfung (inkl. Portal-Sperren) in der Transaktion.
|
||||
|
||||
### Phase 4 – Portalanfragen / Verwaltung
|
||||
Weitgehend **bereits vorhanden** und durch bestehende Tests belegt (nicht neu implementiert): Portal-Mails → Sperre mit Quelle `email` (`ProcessPortalMail`, `PortalMailTest`), iCal-Einträge ohne Gastdaten bleiben anonyme Sperren mit Kanalbezug (`BlockedPeriod`), manuelle Gast-Zuordnung (`AssignOccupationGuest`), Zusammenführung nur über eindeutige UID bzw. ausdrückliche Betreiber-Entscheidung (`ChannelOccupationResolutionTest`), Doppelmeldungen/Konflikte (`ConflictDetector`, Postfach), Portalbuchungen gehen nie durch den Annahmeprozess. Neu: Buchungsseite zeigt Bearbeitungsmodus, Angebotsversion + Prüfsumme, Annahmezeitpunkt und Zustellstatus der Bestätigung.
|
||||
|
||||
## 2. Geänderte / neue Dateien
|
||||
|
||||
Neu: `app/Documents/OfferTerms.php`, `app/Actions/AutoOffer.php`, `app/Availability/CalendarClearance.php`, `app/Enums/OfferMode.php`, `app/Console/Commands/ResendBookingConfirmations.php`, `app/Console/Commands/SendPendingAutoOffers.php`, `resources/views/errors/*`, `tests/Feature/BookingAcceptanceTest.php`, `tests/Feature/AutoOfferTest.php`, zwei Migrationen (unten).
|
||||
Geändert: `AcceptOffer`, `ConfirmBooking`, `SendOffer`, `RejectOffer`, `CreateReservation`, `BookingObserver`, `OfferController`, `Booking`, `Property`, `ReservationException`, `InboxMessageKind`, `Inbox` (optionale `propertyId`), `NewReservation`/`ReservationReceived` (Mail + Views), `offer.blade.php`, `pdf/contract.blade.php`, `booking-request.blade.php`, `PropertyForm`, `BookingInfolist`, `ViewBooking`, `config/fewo.php`, `routes/console.php`, `OfferWorkflowTest`.
|
||||
|
||||
### Migrationen (additiv, nullable bzw. mit Default; bestehende Daten unverändert)
|
||||
1. `2026_10_30_110811_add_offer_snapshot_and_confirmation_tracking_to_bookings_table`: `bookings.offer_terms` (json), `offer_hash` (string 64), `confirmation_sent_at`, `confirmation_failed_at`.
|
||||
2. `…_add_offer_mode_and_pre_reservation_to_properties_table`: `properties.offer_mode` (Default `manual`), `pre_reservation_enabled` (Default `true`).
|
||||
Nicht migriert zur Wahrung des Bestands: Altbuchungen bekommen **keinen** nachträglichen Snapshot/Hash.
|
||||
|
||||
## 3. Konfiguration der Betriebsarten
|
||||
- Wohnung bearbeiten → *Vorreservierung halten* (Stunden), *Anfrage blockiert den Kalender*, *Bearbeitung von Anfragen* (manuell/automatisch).
|
||||
- Kombination automatisch + ohne Vorreservierung ist gesperrt (Formularfehler).
|
||||
- Kanal bearbeiten → Buchungsmodell: *Vermittlung/Anfrage* = keine Sofortbuchung; *Portalbuchung* oder *Gemischt* = Sofortbuchung (konservativ). Export muss aktiv sein.
|
||||
- Testbetrieb/Livebetrieb: System › Betrieb, unverändert und unabhängig.
|
||||
- **Standard bleibt: manuell, Vorreservierung an** → Verhalten wie bisher. Rollback: Modus auf *manuell* stellen.
|
||||
- Neue Zeitpläne (Scheduler, bestehender n8n-Aufruf genügt): `bookings:auto-offers` (5 Min.), `bookings:resend-confirmations` (15 Min.).
|
||||
|
||||
## 4. Restrisiken
|
||||
1. **Portal-Verzögerung:** Ein erfolgreicher Feed-Abruf beweist die Auslieferung, nicht die Verarbeitung im Portal. Eine gleichzeitige Sofortbuchung im Portal ist nicht ausschließbar; sie wird erst über Import/Portal-Mail erkannt und als Konflikt gemeldet (KONZEPT §7).
|
||||
2. Veraltete Importe verhindern Annahmen (gewollt) – ein dauerhaft gestörter Kanal blockiert also Buchungen, bis er repariert oder pausiert wird. Postfach zeigt es.
|
||||
3. Ohne Vorreservierung zählen offene Anfragen nicht in die Obergrenze „offene Anfragen je E-Mail“ (Rate-Limits bleiben aktiv).
|
||||
4. `bookings:auto-offers` sendet in Automatikwohnungen auch dann, wenn der Betreiber eine vorgemerkte Anfrage noch nicht angefasst hat – wer einzelne Anfragen prüfen will, schaltet die Wohnung auf manuell.
|
||||
5. Eine später per Wiederholung gesendete automatische Offerte meldet dem Betreiber nichts Zusätzliches (er sieht den Status in der Buchung).
|
||||
6. Parallelitätsschutz beruht auf `SELECT … FOR UPDATE` (InnoDB). Unter SQLite wirkt die Sperre nicht (Einzelschreiber); **auf MariaDB noch nicht praktisch nachgewiesen** (siehe Acceptance).
|
||||
7. Keine Datenbank-Constraint gegen überlappende Buchungen (nicht sinnvoll realisierbar); Schutz = einheitliche Wohnungssperre in allen schreibenden Pfaden. Neue Schreibpfade müssen `lockForTransition()` nutzen.
|
||||
8. Das 403/419-Verhalten gilt für alle Seiten; die Formular-Session des Annahmeformulars (CSRF) läuft weiter nach 120 Min. ab (jetzt mit klarer Seite).
|
||||
|
||||
## 5. Nicht umgesetzt / spätere Ausbaustufen
|
||||
- Portal-APIs, Channel-Manager, Webhook-Bestätigung durch Portale.
|
||||
- Eigene Tabelle für Ereignisverlauf (Audit-Trail); aktuell JSON `acceptance` + Postfach + Statusfelder.
|
||||
- Gast-Nachfrage/Kommunikationsverlauf in der Buchung; E-Mail-Verifikation der Anfrage.
|
||||
- Auswertung `Retry-After`/Portal-Rückmeldungen; kanalspezifische Abrufnachweise für `HEAD`.
|
||||
- Anzeige der Bedingungen des Snapshots im Admin als Download; Hausordnung auf der Angebotsseite (steht im PDF).
|
||||
- Portal-Anfragen mit unvollständigen Daten: weiterhin über die bestehende Zuordnungsmaske; keine neuen Importformate.
|
||||
@@ -0,0 +1,194 @@
|
||||
# BOOKING-E2E-READINESS – End-to-End-Direktbuchung
|
||||
|
||||
Stand: 30.10.2026 · Branch `feature/titelvideo-rundgang` · Phase 1: **Analyse und Plan, nur lesend.**
|
||||
Es wurden keine Code-, Datenbank-, CMS- oder Serveränderungen vorgenommen. Phase 2 beginnt erst nach ausdrücklicher Freigabe.
|
||||
|
||||
**Grenzen dieser Analyse (ehrlich vorab):**
|
||||
- Geprüft wurde der **Quellcode** (Actions, Controller, Views, Mails, Observer, Tests). Die Testsuite wurde **nicht ausgeführt**, Staging (stommer.info) wurde **nicht** aufgerufen, kein Mail-Versand versucht.
|
||||
- Die Aussagen zu Nebenläufigkeit (Abschnitt 3) sind **Code-Analyse, nicht durch Lasttest belegt**. Sie sind in Phase 2 mit einem echten Parallel-Test auf MariaDB zu bestätigen.
|
||||
- Rechtstexte, Button-Wortlaut und Vertragsinhalte wurden nicht rechtlich bewertet (Verantwortung Betreiber).
|
||||
|
||||
---
|
||||
|
||||
## 1. Fazit in drei Sätzen
|
||||
|
||||
Der Weg „Anfrage → Angebot → signierter Link → Annahme → Bestätigung + Vertrag“ **existiert bereits vollständig** (KONZEPT §6a, Weg 1) und ist architektonisch passend. Zum Soll-Prozess fehlen **drei Dinge**: (a) das Angebot wird heute **manuell** durch die Vermieterin erzeugt (Soll: automatisch), (b) die Annahme ist **nicht transaktionssicher und nicht idempotent**, und die Fehlerbehandlung bei Mailproblemen kann einen Gast nach verbindlicher Buchung vor eine Fehlerseite stellen, (c) die **Vertragsbedingungen werden nicht als Angebotsversion eingefroren** – die Annahme-Nachweise hashen die zum Zeitpunkt der Annahme gerade gültigen Texte, nicht die dem Gast gezeigten. Alles ist mit kleinen, rückwärtskompatiblen Änderungen lösbar, ohne Architekturumbau.
|
||||
|
||||
---
|
||||
|
||||
## 2. Ist-/Soll-Abgleich
|
||||
|
||||
| # | Soll-Schritt | Ist (Fundstelle) | Bewertung |
|
||||
|---|---|---|---|
|
||||
| 1 | Gast stellt unverbindliche Anfrage | `Livewire\BookingRequest` → `CreateReservation`; Bot-Schutz, Rate-Limits | ✅ vorhanden |
|
||||
| 2 | Verfügbarkeit prüfen, Preis berechnen | `CreateReservation` (Property-`lockForUpdate`, `AvailabilityChecker`, `PriceCalculator`) | ✅ vorhanden |
|
||||
| 3 | Zeitraum befristet reservieren, **versioniertes Angebot** mit allen Bedingungen | Reservierung: `Reserved` + `hold_expires_at` (✅). Angebot: `SendOffer` erhöht `offer_version`, speichert `quote`, erzeugt Entwurfs-PDF (✅). **Aber:** nur auf manuelle Aktion im Admin; Bedingungen werden **nicht** als Snapshot gespeichert | ⚠️ **Lücke A + C** |
|
||||
| 4 | Angebot per E-Mail mit sicherem Annahmelink | `OfferMade` + `SendOffer::offerUrl()` (`temporarySignedRoute`, Ablauf = `hold_expires_at`, Version `v` im Link) | ✅ vorhanden |
|
||||
| 5 | Link öffnet nur die Angebotsseite, ohne Buchung | `GET /angebot/{booking}` → `OfferController::show` ändert nichts; Annahme nur per `POST` | ✅ vorhanden |
|
||||
| 6 | Gast prüft Preis, Leistungen, Zahlungs-/Stornobedingungen | `resources/views/offer.blade.php`: Aufenthalt, Preiszeilen, Zahlungsplan, `contract.terms`, `stay.cancellation`, Gültig-bis | ✅ weitgehend. Lücken: Bedingungen kommen aus *aktuellem* CMS-Stand (C); Hausordnung (`stay.house_rules`) steht im PDF, aber nicht auf der Seite; kein speicher-/druckbares Dokument auf der Seite selbst |
|
||||
| 7 | Ausdrückliche Bestätigung „Zahlungspflichtig buchen“ | Checkbox „gelesen“ + Button, Text aus `offer.accept_button` (Default: „Angebot zahlungspflichtig annehmen“), Hinweis `offer.accept_note` | ✅ technisch; **Wortlaut ist Betreiber-/Rechtsfrage** (Q1) |
|
||||
| 8 | Gültigkeit **und** Verfügbarkeit erneut prüfen | Gültigkeit/Version/Status: `AcceptOffer::ensureAcceptable`. Verfügbarkeit: `ConfirmBooking` (in Transaktion, ohne Sperre) | ⚠️ **Lücke B** |
|
||||
| 9 | Annahme dokumentieren, `Confirmed` setzen | `AcceptOffer`: `accepted_at` + JSON `acceptance` (Version, Zeit, Gesamt, `quote_sha256`, `terms_sha256`, `via`) → `ConfirmBooking` | ⚠️ Nachweis unvollständig (C); Schreiben nicht atomar mit Statuswechsel (B) |
|
||||
| 10 | Bestätigung + Vertragsunterlagen | `BookingConfirmed` mit Vertrags-PDF (`RentalContract::generate`) | ⚠️ Fehlerbehandlung (D); finales PDF wird aus *aktuellen* Texten neu gerendert (C) |
|
||||
| 11 | Kalender verbindlich gesperrt, Portal-Sync ausgelöst | `occupying()`-Scope; iCal-Feed wird bei Abruf live berechnet (kein Cache, `no-cache`); `BookingObserver` → `CreateChannelTasks` für Portale mit manueller Sperre, Webhook-Automation | ✅ im Kern; Fehlerpfad prüfen (E) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Gefundene Schwachstellen (aus dem Code belegt)
|
||||
|
||||
**B1 – Annahme ist nicht atomar und nicht idempotent** (`AcceptOffer::handle`, `ConfirmBooking::handle`)
|
||||
- `ensureAcceptable()` liest Status/Frist **außerhalb** einer Transaktion und ohne Zeilensperre. Zwei gleichzeitige POSTs (Doppelklick, Mail-Client-Prefetch ist hier unkritisch, weil POST) können beide die Prüfung bestehen.
|
||||
- Beide schreiben `accepted_at`/`acceptance`; beide rufen `ConfirmBooking` mit **veraltetem In-Memory-Status** `OfferSent` auf → doppelte `BookingConfirmed`-Mail und doppelte `OfferAnswered`-Mail sind möglich; `confirmed_at` und `deposit_due_on` werden überschrieben.
|
||||
- Wird `ConfirmBooking` mit `notAvailable` abgewiesen, **bleiben `accepted_at` und `acceptance` bereits gesetzt**, während der Status `OfferSent` bleibt (Schreiben erfolgt vor der Transaktion). Das ist ein falscher Annahmenachweis.
|
||||
- Zweiter, *nacheinander* erfolgender Klick: Gast sieht die Fehlermeldung „Eine Buchung im Status ‚Bestätigt‘ kann nicht angenommen werden“, obwohl seine Annahme gelungen ist. Soll: idempotent („bereits angenommen am …“).
|
||||
|
||||
**B2 – Verfügbarkeitsprüfung ohne Sperre** (`ConfirmBooking`, `SendOffer`)
|
||||
- `CreateReservation` sperrt die Property-Zeile (`lockForUpdate`), `ConfirmBooking` und `SendOffer` nicht. Unter MariaDB/InnoDB (REPEATABLE READ) ist `exists()` ein nicht sperrender Lesezugriff. Für überlappende Buchungen reicht die Sperre in `CreateReservation` nur, solange alle Schreiber dieselbe Sperre nehmen.
|
||||
- Konkretes Risiko: Hold einer Anfrage läuft ab (`Expired`-Status wird nur vom 5-Minuten-Cron gesetzt, der Kalender gibt den Zeitraum aber sofort frei) → Dritter reserviert denselben Zeitraum → alte Anfrage wird danach durch den Admin über `ConfirmBooking` bestätigt (Expired ist dort erlaubt, Prüfung läuft ohne Sperre). Für die **Gast-Annahme** ist das durch `ensureAcceptable` (Frist) abgefangen; für Parallelität zweier Bestätigungen gilt B2 trotzdem.
|
||||
- Es gibt **keine Datenbank-Garantie** gegen überlappende verbindliche Buchungen (kein Constraint; bei MariaDB ohnehin nur mit Exclusion-Tricks möglich). Sinnvoll ist daher die konsequente Property-Sperre in jedem schreibenden Pfad.
|
||||
- Portal-Importe (`SyncChannel` → `BlockedPeriod`) laufen unabhängig; eine Doppelbelegung durch Portalbuchung zwischen Prüfung und Commit wird erst von `ConflictDetector` / `ReportChannelConflicts` gemeldet (Restrisiko laut KONZEPT §7, nicht lösbar ohne Channel-Manager-API).
|
||||
|
||||
**C – Angebotsversion ist nicht unveränderlich** (`SendOffer`, `AcceptOffer`, `offer.blade.php`, `pdf/contract.blade.php`)
|
||||
- Preis/Quote werden pro Version gespeichert und das Entwurfs-PDF pro Version abgelegt (gut). **Nicht** gespeichert: Mietbedingungen (`contract.terms`), Stornobedingungen (`stay.cancellation`), Hausordnung, Vertragseinleitung/-schluss, Zahlungsdaten (`deposit_due_days`, Bankdaten).
|
||||
- Die Angebotsseite rendert diese Texte **live** aus `Content`. Ändert der Betreiber nach Versand die Bedingungen, sieht der Gast beim Annehmen *andere* Bedingungen als in der E-Mail/dem PDF.
|
||||
- `AcceptOffer` berechnet `terms_sha256` **beim Annehmen** aus dem dann aktuellen Text. Der Nachweis belegt also „Texte zum Zeitpunkt der Annahme“, nicht „Texte, die in Version n angeboten wurden“. Eine Änderung zwischen Versand und Annahme bleibt unbemerkt (Testaufgabe 5 würde das aufdecken).
|
||||
- `ConfirmBooking` erzeugt das finale Vertrags-PDF neu aus **aktuellen** Texten; es kann vom Angebots-PDF abweichen.
|
||||
- `quote_sha256` wird ebenfalls erst bei Annahme gebildet; eine Änderung von `quote`/`total` zwischen Versand und Annahme (z. B. durch Admin-Bearbeitung) würde mitgehasht statt erkannt.
|
||||
|
||||
**D – Fehlerbehandlung bei Mail** (`AcceptOffer`, `ConfirmBooking`, `SendOffer`, `OfferController::answer`)
|
||||
- `ConfirmBooking` sendet `BookingConfirmed` **ungeschützt** nach dem Commit. Wirft der Mailversand (SMTP down), ist die Buchung bereits `Confirmed`, der Controller fängt nur `ReservationException` → Gast sieht eine **500-Seite** und glaubt, nichts sei passiert. Er klickt erneut → Fehlermeldung „Status Bestätigt“ (B1). Die Betreiber-Mail `OfferAnswered` wird in diesem Fall nicht mehr gesendet (Exception unterbricht `AcceptOffer`).
|
||||
- Es gibt keine Nachversand-Möglichkeit/-Markierung: kein Feld „Bestätigung gesendet am“, kein Eintrag im Postfach (`AppSupportInbox`) für fehlgeschlagene Gästemails. `CreateReservation` fängt dagegen korrekt ab (`report($exception)`), ist aber ebenfalls nur im Log sichtbar.
|
||||
- `SendOffer`: wirft der Versand, ist der Status schon `OfferSent` (Frist läuft!), aber der Gast hat nichts bekommen; der Admin sieht den Fehler, ein automatischer Prozess hätte keinen Ort dafür.
|
||||
- `report($exception)` schreibt die Exception ins Log; Symfony-Mailer-Fehlermeldungen können Empfängeradressen enthalten → **personenbezogene Daten im Log** (Q6).
|
||||
|
||||
**E – Portal-Sync-Fehlerpfad** (`BookingObserver::tasks`, `CreateChannelTasks`)
|
||||
- Der iCal-Export wird live berechnet; die Sperre ist sofort im Feed sichtbar. Portale ziehen den Feed selbst (Verzögerung portalseitig, bekannt).
|
||||
- Der Observer läuft in `DB::afterCommit`. Exceptions in diesem Closure (z. B. DB-Fehler beim Anlegen der `ChannelTask`) würden **nach** dem Commit nach oben durchschlagen → Gast bekäme 500, obwohl Buchung steht. Mail und Webhook darin sind einzeln mit `rescue`/`try` abgesichert, die Aufgabenanlage selbst nicht.
|
||||
- Fehlgeschlagene Webhooks landen in `ChannelTask.automation_error` und werden vom bestehenden Erinnerungs-/Monitor-Mechanismus aufgegriffen (✅). Für den Gast-Pfad soll gelten: **Sync-Fehler dürfen die Annahme nie scheitern lassen**, müssen aber für die Betreiber sichtbar werden.
|
||||
|
||||
**F – Sonstiges**
|
||||
- `tests/Feature/OfferWorkflowTest.php` (Test `test_guest_accepts_the_offer_and_the_booking_becomes_binding`) enthält am Ende ein **`dump(strip_tags(...))`** – Debug-Überbleibsel, erzeugt Ausgabe in jedem Testlauf. Beim Umbau entfernen.
|
||||
- Formular-POST nutzt CSRF + Session. Bleibt die Angebotsseite > 120 Min. offen, liefert der Server eine **englische 419-Standardseite** (bereits in MVP-TECHNICAL-GATE #6 als Fehlerseiten-Thema). Für den Annahmeweg besonders unglücklich → deutsche 419-Seite mit Rücksprung auf die (neu signierte) Angebotsseite.
|
||||
- Die signierte POST-URL läuft mit `hold_expires_at` ab; der Gast, der bis kurz vor Fristende wartet, kann zwischen Seitenaufruf und Klick in den Ablauf laufen → bekommt dann die (richtige) Meldung „nicht mehr gültig“ über die 403 des `signed`-Middleware (englische Standardseite!), nicht über `offerExpired()`. Zu prüfen/abzufangen.
|
||||
|
||||
---
|
||||
|
||||
## 4. Wiederverwendbare Bestandteile (nicht neu bauen)
|
||||
|
||||
| Bestandteil | Verwendung |
|
||||
|---|---|
|
||||
| `CreateReservation` | Schritt 1–2 unverändert; Property-Sperre als Vorlage für B2 |
|
||||
| `SendOffer` (`handle(..., sendMail)`, `offerUrl()`) | Auto-Angebot: Aufruf mit leerem `$changes`; Preis wird neu berechnet |
|
||||
| `PriceCalculator` / `PriceQuote` / `QuoteException` | unverändert |
|
||||
| `AcceptOffer` / `RejectOffer` / `ConfirmBooking` | Kern bleibt, wird gehärtet statt ersetzt |
|
||||
| `OfferController`, `offer.blade.php`, Routen `offers.*` (signiert, Throttle) | bleiben, Bedingungen kommen künftig aus dem Snapshot |
|
||||
| `RentalContract` (Draft pro Version, finaler Vertrag) | Snapshot als Datenquelle |
|
||||
| `OfferMade`, `BookingConfirmed`, `OfferAnswered`, `ReservationReceived`, `NewReservation` | unverändert (Inhalt Betreiber) |
|
||||
| `Booking::occupying()`, `AvailabilityChecker` | unverändert; nur Sperre ergänzen |
|
||||
| `BookingObserver` → `CreateChannelTasks`, iCal-Feed, `ConflictDetector` | Sync-Auslösung bleibt; Fehlerpfad absichern |
|
||||
| `ExpireReservations` / `bookings:expire-holds` | unverändert |
|
||||
| `AppSupportInbox` (Postfach, Fingerprint, Erinnerungsintervall) | Ablage für Mail-/Sync-Fehler |
|
||||
| `Settings::notificationRecipients()`, Testmodus | unverändert (alle Tests laufen im Testmodus) |
|
||||
| `ReservationException` (gast-taugliche Meldungen) | um wenige Fälle erweitern |
|
||||
|
||||
---
|
||||
|
||||
## 5. Minimal erforderliche Codeänderungen
|
||||
|
||||
1. **Auto-Angebot (A):** Neue Action `App\Actions\AutoOffer` (oder Option in `CreateReservation`), die nach erfolgreicher Reservierung `SendOffer->handle($booking)` aufruft. Gesteuert über eine **Einstellung je Wohnung/Mandant** (`auto_offer`, Default **aus** → bisheriges Verhalten bleibt). Fehler des Versands werden abgefangen (siehe D); die Reservierung geht nie verloren. Die bisherige Eingangsbestätigung (`ReservationReceived`) wird bei aktivem Auto-Angebot nicht doppelt gesendet.
|
||||
*Hinweis:* Das Angebot soll bei Auto-Angebot dieselbe Frist wie `hold_hours` haben (48 h, je Wohnung einstellbar).
|
||||
2. **Angebots-Snapshot (C):** In `SendOffer` beim Versand Bedingungen, Storno, Hausordnung, Vertragstexte und Zahlungsfristen in einem JSON-Feld festhalten, samt Hash. Angebotsseite, Entwurfs- **und** Final-PDF lesen aus dem Snapshot. Altbuchungen ohne Snapshot: Fallback auf Live-Content (rückwärtskompatibel).
|
||||
3. **Atomare, idempotente Annahme (B1/B2):** `AcceptOffer::handle` komplett in `DB::transaction`: Property-Zeile `lockForUpdate`, Buchung frisch mit `lockForUpdate` laden, dann Version/Status/Frist/Verfügbarkeit prüfen, Nachweis schreiben **und** Status setzen. Ist die Buchung bereits mit derselben Version angenommen: **kein Fehler, keine zweite Mail**, Erfolgsseite. `ConfirmBooking` bekommt dieselbe Property-Sperre. Mails erst **nach** Commit.
|
||||
4. **Nachweis (C):** `acceptance` um `offer_hash` (Hash über Quote + Snapshot **bei Versand**), `offer_sent_at`, `valid_until`, `button_label`, `checkbox_label`, `user_agent_hash`-optional ergänzen. Bei Annahme: gespeicherten `offer_hash` mit dem aktuellen vergleichen; Abweichung → Annahme abweisen („Angebot wurde geändert“) und Admin-Postfachmeldung.
|
||||
5. **Fehlerisolierung (D/E):** Gast-Mails und Betreiber-Mails in `AcceptOffer` einzeln in `try/catch`; bei Fehler Eintrag in `AppSupportInbox` (ohne Empfängeradresse im Text) und Zeitstempel-Felder (`confirmation_sent_at`, `confirmation_failed_at`). Der Gast sieht immer die Erfolgsseite, falls die Buchung committed ist, mit Hinweis „Bestätigung folgt“, wenn die Mail scheiterte. Observer-Closure in `rescue()` kapseln, Fehler → Postfach.
|
||||
6. **Nachversand:** Admin-Aktion „Bestätigung erneut senden“ (Buchungsseite) und Cron-Fallback `bookings:resend-confirmations`, der Bestätigungen mit gesetztem `confirmation_failed_at` erneut versucht.
|
||||
7. **Gast-Fehlerseiten:** Deutsche 403/419-Seiten für den Annahmeweg mit Rücksprung auf die Angebotsseite (bündelt sich mit MVP-Gate #6).
|
||||
8. **Bereinigung:** `dump()` aus `OfferWorkflowTest` entfernen.
|
||||
|
||||
Nicht geändert: Preisberechnung, Tenancy, Kanalarchitektur, Themes, Rechnungs-/Zahlungslogik (`RecordPayment`).
|
||||
|
||||
---
|
||||
|
||||
## 6. Notwendige Datenbankänderungen (eine additive Migration, rückwärtskompatibel)
|
||||
|
||||
Tabelle `bookings`:
|
||||
|
||||
| Spalte | Typ | Zweck |
|
||||
|---|---|---|
|
||||
| `offer_terms` | `json` nullable | eingefrorene Bedingungen/Texte/Zahlungsfristen der aktuellen Angebotsversion |
|
||||
| `offer_hash` | `string(64)` nullable | SHA-256 über `quote` + `offer_terms` + `total` bei Versand |
|
||||
| `confirmation_sent_at` | `timestamp` nullable | Gästebestätigung nachweislich versendet |
|
||||
| `confirmation_failed_at` | `timestamp` nullable | Versand fehlgeschlagen → Nachversand |
|
||||
|
||||
Tenant/Property: Einstellung `auto_offer` (bool, Default `false`) – an der Stelle, wo `hold_hours` bereits liegt (`properties`), eine Spalte `auto_offer`.
|
||||
|
||||
Alle Spalten nullable bzw. mit Default; bestehende Daten werden nicht verändert; kein Backfill nötig (Fallback für `NULL`). Down-Migration entfernt die Spalten. **Produktionsdaten werden nicht berührt, solange die Migration nicht deployt wird.**
|
||||
|
||||
Optional (später): eigene Tabelle `booking_events` (Audit-Trail) statt JSON-Feld – für den MVP nicht nötig.
|
||||
|
||||
---
|
||||
|
||||
## 7. Tests und Akzeptanzkriterien
|
||||
|
||||
Alle Tests laufen in der Entwicklungsumgebung (`php artisan test`), Mail über `Mail::fake()` bzw. `MAIL_MAILER=array`; zusätzlich ein Staging-Durchlauf im **Testmodus** (Mails nur an Testadresse).
|
||||
|
||||
| # | Testaufgabe | Konkrete Prüfung | Akzeptanzkriterium |
|
||||
|---|---|---|---|
|
||||
| 1 | **Erfolgreiche Buchung inkl. aller Mails** | Anfrage über Livewire → (Auto-)Angebot → GET Angebotsseite → POST Annahme | Status `Confirmed`; genau 1× `OfferMade`, 1× `BookingConfirmed` (mit PDF-Anhang), 1× `OfferAnswered`; Kalender zeigt Nächte belegt; iCal-Feed enthält Sperre; Nachweis vollständig |
|
||||
| 2 | **Abgelaufenes Angebot** | Zeit hinter `hold_expires_at` schieben (a) vor, (b) nach Cron-Lauf | GET zeigt Hinweis; POST abgelehnt mit deutscher Meldung; Zeitraum frei; Status bleibt unverändert; keine Mail |
|
||||
| 3 | **Doppelte Annahme** | zweimal POST nacheinander; zusätzlich zwei gleichzeitige Requests (zwei Prozesse gegen MariaDB) | genau **eine** `BookingConfirmed`, eine `confirmed_at`; zweite Anfrage → Erfolgsseite „bereits angenommen“, kein Fehler, keine zweite Mail |
|
||||
| 4 | **Parallele Buchungen derselben Zeit** | (a) zwei Anfragen gleichzeitig; (b) Annahme von Angebot A, während Angebot B (anderer Gast, abgelaufene Haltefrist) denselben Zeitraum bekam; (c) Admin-`ConfirmBooking` parallel zur Gastannahme | niemals zwei überlappende `occupying`-Buchungen; Verlierer erhält `notAvailable`-Meldung, **kein** Annahmenachweis, kein Statuswechsel |
|
||||
| 5 | **Geänderte Angebotsbedingungen** | (a) `contract.terms` nach Versand ändern; (b) Admin sendet neue Version; (c) alter Link (`v=1`) | (a) Seite/Annahme/PDF zeigen weiterhin den Snapshot v1 und der Nachweis hasht v1; (b) alter Link → `offerOutdated`; (c) bei manipuliertem `quote`/`total` nach Versand wird die Annahme abgewiesen (Hash-Abweichung) |
|
||||
| 6 | **Fehlgeschlagener Mailversand** | Mailer wirft Exception bei `BookingConfirmed`, `OfferMade`, `OfferAnswered` | Buchung bleibt `Confirmed`; Gast sieht Erfolgsseite mit Hinweis; `confirmation_failed_at` gesetzt; Postfach-Eintrag ohne E-Mail-Adresse; Nachversand per Admin-Aktion/Command klappt, danach `confirmation_sent_at` gesetzt. Bei `OfferMade`-Fehler: Angebot bleibt, Hinweis im Admin, Nachversand möglich |
|
||||
| 7 | **Fehlgeschlagene Kalender-Synchronisierung** | `CreateChannelTasks`/Webhook wirft Exception, Kanal mit `requires_manual_blocking` | Annahme erfolgreich (kein 500); `ChannelTask` mit `automation_error` bzw. Postfachmeldung; iCal-Feed enthält die Sperre trotzdem; Erinnerungs-/Monitorlauf meldet die offene Aufgabe |
|
||||
| 8 | **Gespeicherte Nachweise** | Datenbank/Dateien nach Testlauf 1 prüfen | `acceptance` enthält Version, Zeitpunkte, Gesamtbetrag, `offer_hash`, Texte-Hash, Beschriftungen; Hash stimmt mit nachgerechnetem Wert überein; Angebots-PDF (v), finales PDF und Snapshot sind identisch im Inhalt der Bedingungen; **keine IP-Adresse, kein Token** gespeichert |
|
||||
| 9 | **Keine Zustandsänderung per GET** | wiederholt GET (auch mit Prefetch-User-Agent) | Status/`accepted_at` unverändert |
|
||||
| 10 | **Signatur** | manipulierte Signatur, fremde Booking-ID, falsche Version | 403 bzw. `offerOutdated`; keine Datenausgabe |
|
||||
| 11 | **Log-Hygiene** | Laravel-Log nach Fehlerfällen durchsuchen | keine signierten URLs, keine Tokens, keine E-Mail-Adressen/Namen |
|
||||
| 12 | **Regression** | komplette bestehende Suite, `vendor/bin/pint --dirty` | grün; Verhalten mit `auto_offer = false` unverändert |
|
||||
|
||||
Staging-Durchlauf (nach Freigabe): einmal komplett mit echter Zustellung an die Testadresse (SPF/DKIM unauffällig), PDFs öffnen, Sperre im Portal-Feed prüfen. Bei der Parallelitätsprüfung unbedingt **MariaDB** verwenden (SQLite verhält sich bei Sperren anders).
|
||||
|
||||
---
|
||||
|
||||
## 8. Kritische rechtlich-technische Fragen (Entscheidung beim Betreiber / Rechtsberatung)
|
||||
|
||||
1. **Button-Wortlaut („Zahlungspflichtig buchen“):** Die Vorgabe fordert diesen Wortlaut; aktuell ist der Default „Angebot zahlungspflichtig annehmen“ (CMS-Feld `offer.accept_button`). Änderung ist reine CMS-Sache des Betreibers. Ist die Formulierung bei Vermietung (kein Verbrauchervertrag über Online-Kauf im engeren Sinn?) einschlägig und ausreichend?
|
||||
2. **Widerrufsrecht:** Für Beherbergung zu bestimmten Terminen gilt regelmäßig eine Ausnahme vom Widerrufsrecht – ist das hier so einzuordnen und muss das vor Annahme angezeigt werden? Das System kann es technisch anzeigen, entscheidet es aber nicht.
|
||||
3. **Vorvertragliche Informationen / AGB:** Müssen Mietbedingungen, Storno, Datenschutz und Widerrufsinformation als Link **und** als Anhang (dauerhafter Datenträger) vorliegen? Aktuell: Bedingungen auf der Seite + Vertrags-PDF in der Mail. Die Texte `contract.terms` sind noch **[MUSTER]**.
|
||||
4. **Bestätigung der Zahlungspflicht vs. Kenntnisnahme:** Die aktuelle Checkbox lautet „Ich habe … gelesen“; der Button löst die Verpflichtung aus. Ist zusätzlich eine eigene Checkbox „Ich akzeptiere die Bedingungen“ gewünscht?
|
||||
5. **Beweis der Annahme ohne IP-Adresse:** Es wird bewusst keine IP gespeichert (Datensparsamkeit). Reicht „Zeit + Version + Hashes + Gesamtbetrag“ als Nachweis, oder wird zusätzlich ein gekürzter IP-Hash/User-Agent gewünscht? (DSGVO-Abwägung.)
|
||||
6. **Personenbezogene Daten in Logs/Fehlermeldungen:** Mailer-Exceptions können Adressen enthalten. Vorschlag: eigenes Exception-Masking im `report()`-Pfad. Aufbewahrung von Annahmenachweisen und Verträgen ist im Löschkonzept (`docs/LOESCHKONZEPT.md`) noch als offene Lücke vermerkt – Frist festlegen.
|
||||
7. **Verbindliche Buchung ohne manuelle Prüfung:** Auto-Angebot und sofortige Annahme verzichten auf menschliche Prüfung (KONZEPT §6a sah „manuell, später KI-Entwurf mit Freigabe“ vor). Bewusste Entscheidung bestätigen; **Portalrisiko** (Doppelbuchung durch Verzögerung beim iCal-Abgleich, KONZEPT §7/§7a) bleibt. Vorschlag: Auto-Angebot nur für Zeiträume, die weiter als X Tage entfernt sind, und/oder Sperre der Portale mit Sofortbuchung per Aufgabe.
|
||||
8. **Reservierung als Zusage?** Die Haltezeit blockiert den Kalender auch für andere Gäste und Portale (wegen `occupying()`); bei Auto-Angeboten kann Missbrauch (Blockieren fremder Termine) leichter werden – bestehende Limits (max. 2 offene Anfragen je E-Mail, Rate-Limits) greifen, ggf. E-Mail-Verifikation erwägen.
|
||||
9. **Zahlungsfristen:** Anzahlung wird erst mit Annahme fällig (`deposit_due_days`). Rechtlich festlegen, was bei Nichtzahlung passiert (Rücktritt/Storno) – aktuell nur Erinnerungen (`SendBookingReminders`), keine automatische Storno.
|
||||
|
||||
---
|
||||
|
||||
## 9. Vorschlag: kleine, rückwärtskompatible Implementierung (nach Freigabe)
|
||||
|
||||
**Reihenfolge (jeweils eigenständig lauffähig, Standardverhalten unverändert):**
|
||||
|
||||
1. **Schritt 1 – Sicherheitskern (ohne Funktionsänderung für Betreiber):** Migration (nur `offer_terms`, `offer_hash`, `confirmation_*`), Snapshot in `SendOffer`, atomare/idempotente `AcceptOffer` mit Sperren, Hash-Prüfung, Fehlerisolierung für Mail und Observer. Tests 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 (+ `dump()` entfernen).
|
||||
2. **Schritt 2 – Nachsende-Funktion:** Admin-Aktion „Bestätigung erneut senden“ plus Command; Postfach-Einträge. Test 6 erweitern.
|
||||
3. **Schritt 3 – Auto-Angebot:** `auto_offer` je Wohnung (Default aus), `AutoOffer`-Aufruf nach `CreateReservation`; Staging einschalten, produktiv erst nach Freigabe. Test 1 + 12.
|
||||
4. **Schritt 4 – Gast-Fehlerseiten** 403/419 deutsch (mit MVP-Gate #6 gemeinsam).
|
||||
5. **Schritt 5 – Staging-Durchlauf** gemäß Abschnitt 7 mit Protokoll in `docs/STATUS.md`.
|
||||
|
||||
**Umfang grob:** 1 Migration, ~5 geänderte Dateien (`SendOffer`, `AcceptOffer`, `ConfirmBooking`, `OfferController`, `BookingObserver`), 1 neue Action, 2 Views (Angebotsseite, Fehlerseiten), 1 Command, Tests; keine neuen Abhängigkeiten, kein neuer Basisordner.
|
||||
|
||||
**Rollback:** `auto_offer` ausschalten stellt das bisherige Verhalten sofort wieder her; die Migration ist additiv und reversibel.
|
||||
|
||||
**Nicht Teil dieses Vorschlags:** Online-Zahlung, Kundenkonto, KI, Änderung von Preis-/Tenancy-/Kanalarchitektur, CMS-Inhalte (Bedingungen, Button-Text), Produktions-Deployment.
|
||||
|
||||
---
|
||||
|
||||
## 10. Freigabe
|
||||
|
||||
Bitte bestätigen, bevor Phase 2 beginnt:
|
||||
- [ ] Umfang Schritt 1–2 (Sicherheitskern + Nachversand) in der Entwicklungsumgebung
|
||||
- [ ] Schritt 3 (Auto-Angebot) ja/nein, und ob zunächst nur auf Staging
|
||||
- [ ] Antworten bzw. Zuständigkeiten zu den Fragen 1–9
|
||||
- [ ] Migration in Entwicklung/Staging ausführen (nicht in Produktion)
|
||||
|
||||
Bis dahin: **keine Änderungen an Code, Datenbank, CMS oder Servern.**
|
||||
@@ -17,7 +17,7 @@ # Ferienwohnung Stommer
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – 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.
|
||||
- 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`.
|
||||
|
||||
+141
-24
@@ -2,53 +2,91 @@
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\CalendarClearance;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Content;
|
||||
use App\Support\Inbox;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest accepts the offer on the signed offer page: the booking is concluded. A record of what was
|
||||
* accepted is kept (offer version, time, fingerprints of price and terms – no IP address), then the booking
|
||||
* is confirmed as usual (contract + confirmation mail as electronic acknowledgement).
|
||||
* The guest accepts the offer on the signed offer page: the booking is concluded. Everything happens in one
|
||||
* locked transaction (property + booking row): status, validity, integrity of the frozen offer and availability
|
||||
* are checked, the acceptance record is written and the booking becomes binding – or nothing changes at all.
|
||||
* Accepting the same version again is idempotent (no second booking, no second mail). Mails follow after the commit
|
||||
* and never undo the acceptance.
|
||||
*/
|
||||
class AcceptOffer
|
||||
{
|
||||
public function __construct(private ConfirmBooking $confirm) {}
|
||||
public function __construct(private ConfirmBooking $confirm, private Inbox $inbox, private CalendarClearance $clearance) {}
|
||||
|
||||
/**
|
||||
* @return bool true when this call concluded the booking, false when the version had already been accepted
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, int $offerVersion): void
|
||||
public function handle(Booking $booking, int $offerVersion): bool
|
||||
{
|
||||
$this->ensureAcceptable($booking, $offerVersion);
|
||||
|
||||
$booking->update([
|
||||
'accepted_at' => now(),
|
||||
'acceptance' => [
|
||||
'offer_version' => $booking->offer_version,
|
||||
'accepted_at' => now()->toIso8601String(),
|
||||
'total' => $booking->total,
|
||||
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
|
||||
'terms_sha256' => hash('sha256', (string) Content::get('contract.terms').'|'.Content::get('stay.cancellation')),
|
||||
'via' => 'offer_link',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->confirm->handle($booking);
|
||||
if ($booking->status === BookingStatus::OfferSent) {
|
||||
$this->ensureCalendarFresh($booking);
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$accepted = DB::transaction(function () use ($booking, $offerVersion): bool {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if ($this->alreadyAccepted($booking, $offerVersion)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$this->ensureAcceptable($booking, $offerVersion);
|
||||
$this->ensureUnchanged($booking);
|
||||
|
||||
$validUntil = $booking->hold_expires_at?->toIso8601String();
|
||||
$this->confirm->bind($booking);
|
||||
$booking->update([
|
||||
'accepted_at' => now(),
|
||||
'acceptance' => [
|
||||
'offer_version' => $booking->offer_version,
|
||||
'accepted_at' => now()->toIso8601String(),
|
||||
'offer_sent_at' => $booking->offer_sent_at?->toIso8601String(),
|
||||
'valid_until' => $validUntil,
|
||||
'total' => $booking->total,
|
||||
'offer_hash' => $booking->offer_hash,
|
||||
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
|
||||
'terms_sha256' => hash('sha256', json_encode($booking->offer_terms['texts'] ?? [])),
|
||||
'accept_button' => $booking->offerText('offer.accept_button'),
|
||||
'via' => 'offer_link',
|
||||
],
|
||||
]);
|
||||
|
||||
return true;
|
||||
});
|
||||
} catch (ReservationException $exception) {
|
||||
$this->noteRejection($booking, $offerVersion, $exception);
|
||||
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
if ($accepted) {
|
||||
$this->confirm->deliver($booking);
|
||||
$this->notifyLandlord($booking);
|
||||
}
|
||||
|
||||
return $accepted;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that make the offer page show the form: version, status and validity (no locks, read only).
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function ensureAcceptable(Booking $booking, int $offerVersion): void
|
||||
@@ -65,4 +103,83 @@ public function ensureAcceptable(Booking $booking, int $offerVersion): void
|
||||
throw ReservationException::offerExpired();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The frozen offer must still match its fingerprint (price, dates, terms); offers made before the
|
||||
* fingerprint existed have none and are not checked.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function ensureUnchanged(Booking $booking): void
|
||||
{
|
||||
if ($booking->offer_hash !== null && ! hash_equals($booking->offer_hash, OfferTerms::hash($booking))) {
|
||||
throw ReservationException::offerChanged();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Before the guest becomes bound, the imported portal calendars must be recent (an import is tried first –
|
||||
* network access, so outside the transaction). Otherwise nothing is concluded and the landlord is told.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
private function ensureCalendarFresh(Booking $booking): void
|
||||
{
|
||||
$property = $booking->property;
|
||||
$this->clearance->refresh($property);
|
||||
|
||||
$stale = $this->clearance->staleImports($property);
|
||||
if ($stale->isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->inbox->post(
|
||||
InboxMessageKind::SyncFailed,
|
||||
'accept-'.$booking->id.':'.now()->format('YmdH'),
|
||||
'Annahme von '.$booking->reference.' zurückgestellt: Kalenderstand nicht aktuell',
|
||||
'Der Gast wollte das Angebot annehmen, aber der Import von '.$stale->pluck('name')->implode(', ').' ist nicht aktuell. Bitte Kalenderabgleich prüfen und den Gast kontaktieren.',
|
||||
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||
propertyId: $booking->property_id,
|
||||
);
|
||||
|
||||
throw ReservationException::calendarUnverified();
|
||||
}
|
||||
|
||||
private function alreadyAccepted(Booking $booking, int $offerVersion): bool
|
||||
{
|
||||
return in_array($booking->status, BookingStatus::occupying(), true)
|
||||
&& $booking->accepted_at !== null
|
||||
&& ($booking->acceptance['offer_version'] ?? null) === $offerVersion;
|
||||
}
|
||||
|
||||
private function noteRejection(Booking $booking, int $offerVersion, ReservationException $exception): void
|
||||
{
|
||||
if ($offerVersion !== $booking->offer_version || $booking->status !== BookingStatus::OfferSent) {
|
||||
return;
|
||||
}
|
||||
|
||||
$reasonIsUnexpected = $exception->getMessage() === ReservationException::offerChanged()->getMessage()
|
||||
|| $exception->getMessage() === ReservationException::notAvailable()->getMessage();
|
||||
if (! $reasonIsUnexpected) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->inbox->post(
|
||||
InboxMessageKind::OfferRejected,
|
||||
'booking-'.$booking->id.':v'.$offerVersion,
|
||||
'Annahme von Angebot '.$booking->reference.' abgewiesen',
|
||||
'Der Gast wollte das Angebot annehmen, aber: '.$exception->getMessage().' Bitte den Gast kontaktieren oder ein neues Angebot senden.',
|
||||
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||
propertyId: $booking->property_id,
|
||||
);
|
||||
}
|
||||
|
||||
private function notifyLandlord(Booking $booking): void
|
||||
{
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Benachrichtigung über Annahme nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -22,12 +22,14 @@ 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();
|
||||
|
||||
$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();
|
||||
|
||||
@@ -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']);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Availability\CalendarClearance;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OfferMode;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
|
||||
/**
|
||||
* Automatic offer processing (property setting "Automatisch"): sends the offer without the landlord when every
|
||||
* release rule is met, otherwise leaves the request untouched for manual processing and says why.
|
||||
*
|
||||
* Rules: pre-reservation active (the dates are really blocked), guest e-mail known, dates still free, contract
|
||||
* texts released by the landlord (not the sample text; skipped while mails only go to the test recipient),
|
||||
* and the calendar clearance of {@see CalendarClearance} (fresh imports, instant-booking portals fetched our feed).
|
||||
*/
|
||||
class AutoOffer
|
||||
{
|
||||
public function __construct(
|
||||
private SendOffer $sendOffer,
|
||||
private CalendarClearance $clearance,
|
||||
private AvailabilityChecker $availability,
|
||||
) {}
|
||||
|
||||
public function applies(Booking $booking): bool
|
||||
{
|
||||
return $booking->property->offer_mode === OfferMode::Automatic;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string> reasons why the offer cannot be sent automatically (empty = may be sent)
|
||||
*/
|
||||
public function blockers(Booking $booking): array
|
||||
{
|
||||
$property = $booking->property;
|
||||
$reasons = [];
|
||||
|
||||
if (! $property->pre_reservation_enabled) {
|
||||
$reasons[] = 'Die Vorreservierung ist für diese Wohnung ausgeschaltet; ohne Sperre im Kalender wird kein Angebot automatisch erteilt.';
|
||||
}
|
||||
if ($booking->status !== BookingStatus::Reserved || ! $booking->isHoldActive()) {
|
||||
$reasons[] = 'Die Anfrage ist nicht mehr vorgemerkt (Frist abgelaufen oder bereits bearbeitet).';
|
||||
}
|
||||
if (blank($booking->guest?->email)) {
|
||||
$reasons[] = 'Die E-Mail-Adresse des Gastes fehlt.';
|
||||
}
|
||||
if (! $this->availability->isAvailable($property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||
$reasons[] = 'Der Zeitraum ist inzwischen belegt.';
|
||||
}
|
||||
if (! $this->contractTextsReleased()) {
|
||||
$reasons[] = 'Mietbedingungen, Stornobedingungen oder Bankverbindung sind noch nicht vom Betreiber freigegeben (leer oder Mustertext).';
|
||||
}
|
||||
|
||||
return [...$reasons, ...$this->clearance->reasons($property, $booking->created_at)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Tries to send the offer. Imports of stale channels are refreshed first (network access, outside transactions).
|
||||
*
|
||||
* @return list<string> reasons for the manual fallback; empty when the offer was sent
|
||||
*/
|
||||
public function handle(Booking $booking): array
|
||||
{
|
||||
$booking->loadMissing(['property', 'guest']);
|
||||
|
||||
if ($booking->property->pre_reservation_enabled) {
|
||||
$this->clearance->refresh($booking->property);
|
||||
}
|
||||
|
||||
$reasons = $this->blockers($booking);
|
||||
if ($reasons !== []) {
|
||||
return $reasons;
|
||||
}
|
||||
|
||||
try {
|
||||
$this->sendOffer->handle($booking->fresh());
|
||||
} catch (QuoteException|ReservationException $exception) {
|
||||
// A mail failure keeps the saved offer (SendOffer reports it in the inbox); the landlord can resend the link.
|
||||
return [$exception->getMessage()];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
private function contractTextsReleased(): bool
|
||||
{
|
||||
if (! Settings::isLive()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$terms = (string) Content::get('contract.terms');
|
||||
|
||||
return filled($terms) && ! str_contains($terms, '[MUSTER')
|
||||
&& filled(Content::get('stay.cancellation'))
|
||||
&& filled(config('fewo.bank.iban'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingCancelled;
|
||||
use App\Mail\CancellationRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Support\CancellationCost;
|
||||
use App\Support\Money;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The landlord cancels a binding booking. The dates are free again; the guest and the landlord are informed by mail
|
||||
* (the guest mail can be switched off, e.g. when the guest cancelled by phone and was told already) and a task for
|
||||
* the cancellation costs is created. Open cancellation requests of the guest are completed.
|
||||
*/
|
||||
class CancelBooking
|
||||
{
|
||||
/**
|
||||
* @return bool whether the guest has been informed (true as well when no mail was wanted; false when it failed)
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true, bool $costsTask = true, string $by = 'Verwaltung'): bool
|
||||
{
|
||||
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Der Gast hat keine E-Mail-Adresse – bitte ohne Mail an den Gast stornieren oder die Adresse ergänzen.');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking, $costsTask, $by): void {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||
}
|
||||
|
||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
||||
app(RecordCancellation::class)->handle($booking, 'landlord');
|
||||
|
||||
BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->where('status', BookingTaskStatus::Open)
|
||||
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
|
||||
|
||||
if ($costsTask) {
|
||||
$cost = CancellationCost::calculate($booking);
|
||||
BookingTask::query()->firstOrCreate(['booking_id' => $booking->id, 'kind' => BookingTaskKind::CancellationFee], [
|
||||
'status' => BookingTaskStatus::Open,
|
||||
'due_on' => today(),
|
||||
'note' => $cost ? 'Vorschlag nach Stornoregel „'.$cost['policy'].'“: '.Money::format($cost['fee']).' ('.$cost['tier_text'].')' : 'Keine Stornoregel hinterlegt – Kosten von Hand festlegen.',
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
|
||||
return $this->notify($booking, $notifyGuest);
|
||||
}
|
||||
|
||||
private function notify(Booking $booking, bool $notifyGuest): bool
|
||||
{
|
||||
$informed = true;
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, cancelled: true));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Stornomitteilung an den Vermieter nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
|
||||
if ($notifyGuest) {
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, cancelled: true));
|
||||
} catch (Throwable $exception) {
|
||||
$informed = false;
|
||||
Log::warning('Stornomail an den Gast nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
|
||||
return $informed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Enums\CancellationMode;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingCancelled;
|
||||
use App\Mail\CancellationRequested;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use App\Support\CancellationCost;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest uses the cancellation link of the booking confirmation. Depending on the property's setting the
|
||||
* booking is cancelled at once (dates released) or only a request task is created for the landlord – costs
|
||||
* are never settled automatically. Repeating the click changes nothing.
|
||||
*/
|
||||
class CancelBookingByGuest
|
||||
{
|
||||
/**
|
||||
* What a click on the link does for this booking today.
|
||||
*/
|
||||
public function modeFor(Booking $booking): CancellationMode
|
||||
{
|
||||
$property = $booking->property;
|
||||
$freeUntil = $booking->arrival->subDays($property->free_cancellation_days);
|
||||
|
||||
return match ($property->cancellation_mode) {
|
||||
CancellationMode::Instant => CancellationMode::Instant,
|
||||
CancellationMode::InstantWhenFree => ($cost = CancellationCost::calculate($booking)) !== null
|
||||
? ($cost['free'] ? CancellationMode::Instant : CancellationMode::Request)
|
||||
: (today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request),
|
||||
default => CancellationMode::Request,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return CancellationMode|null what happened (Instant = cancelled, Request = request recorded); null when it had happened before
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, ?string $message = null): ?CancellationMode
|
||||
{
|
||||
$outcome = DB::transaction(function () use ($booking, $message): ?CancellationMode {
|
||||
$booking->lockForTransition();
|
||||
|
||||
$alreadyAsked = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->exists();
|
||||
if ($booking->status === BookingStatus::Cancelled || $alreadyAsked) {
|
||||
return null;
|
||||
}
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true) || $booking->arrival->isPast()) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert');
|
||||
}
|
||||
|
||||
$mode = $this->modeFor($booking);
|
||||
if ($mode === CancellationMode::Instant) {
|
||||
$booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]);
|
||||
app(RecordCancellation::class)->handle($booking, 'guest');
|
||||
}
|
||||
BookingTask::query()->create([
|
||||
'booking_id' => $booking->id,
|
||||
'kind' => BookingTaskKind::CancellationRequest,
|
||||
'status' => BookingTaskStatus::Open,
|
||||
'note' => trim(($mode === CancellationMode::Instant ? 'Vom Gast storniert – bitte Stornokosten und Rückzahlung prüfen. ' : '').($message ?? '')) ?: null,
|
||||
]);
|
||||
|
||||
return $mode;
|
||||
});
|
||||
|
||||
if ($outcome !== null) {
|
||||
$this->notify($booking, $outcome);
|
||||
}
|
||||
|
||||
return $outcome;
|
||||
}
|
||||
|
||||
private function notify(Booking $booking, CancellationMode $mode): void
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$cancelled = $mode === CancellationMode::Instant;
|
||||
|
||||
$sends = [
|
||||
fn () => Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, $cancelled)),
|
||||
fn () => $booking->guest?->email ? Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, $cancelled)) : null,
|
||||
];
|
||||
foreach ($sends as $send) {
|
||||
try {
|
||||
$send();
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Stornomitteilung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,52 +3,128 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Mail\BookingConfirmed;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Inbox;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Makes a booking binding: payment due dates are fixed, the rental contract is generated and sent with the
|
||||
* confirmation. Used when the guest accepts an offer (AcceptOffer) and when the landlord confirms directly
|
||||
* (e.g. a booking agreed on the phone). Expired requests/offers can still be confirmed while the dates are free.
|
||||
*
|
||||
* Binding is one locked database step ({@see bind()}); contract and mail follow afterwards ({@see deliver()}).
|
||||
* A failing mail server never undoes a binding booking – the failure is recorded and the mail can be resent.
|
||||
*/
|
||||
class ConfirmBooking
|
||||
{
|
||||
public function __construct(
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
private Inbox $inbox,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return bool whether the guest has the confirmation (true when no mail was requested)
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): bool
|
||||
{
|
||||
if ($notifyGuest && blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.');
|
||||
}
|
||||
|
||||
DB::transaction(fn () => $this->bind($booking));
|
||||
|
||||
return $this->deliver($booking, $notifyGuest);
|
||||
}
|
||||
|
||||
/**
|
||||
* Locks the property and the booking, checks status and availability and makes the booking binding.
|
||||
* Must run inside a transaction; every writer of bookings takes the same property lock, so two
|
||||
* overlapping stays can never both become binding.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function bind(Booking $booking): void
|
||||
{
|
||||
$booking->lockForTransition();
|
||||
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking): void {
|
||||
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||
throw ReservationException::notAvailable();
|
||||
if (! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||
throw ReservationException::notAvailable();
|
||||
}
|
||||
|
||||
$terms = $booking->offer_terms ?? OfferTerms::capture(OfferTerms::templateFor($booking), $booking);
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'hold_expires_at' => null,
|
||||
'confirmed_at' => now(),
|
||||
'offer_terms' => $terms,
|
||||
'deposit_due_on' => today()->addDays((int) ($terms['deposit_due_days'] ?? config('fewo.deposit_due_days')))->toDateString(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the contract and sends the confirmation – after the booking is saved, with every failure
|
||||
* contained: the booking stays binding, the failure is marked and shown in the admin inbox.
|
||||
*
|
||||
* @return bool whether the guest has the confirmation (true when no mail was requested)
|
||||
*/
|
||||
public function deliver(Booking $booking, bool $notifyGuest = true): bool
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
|
||||
try {
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if (! $notifyGuest) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'hold_expires_at' => null,
|
||||
'confirmed_at' => now(),
|
||||
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
|
||||
]);
|
||||
});
|
||||
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if ($notifyGuest) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
|
||||
$booking->forceFill(['confirmation_sent_at' => now(), 'confirmation_failed_at' => null])->saveQuietly();
|
||||
|
||||
return true;
|
||||
} catch (Throwable $exception) {
|
||||
// Only class and booking id are logged: mail errors can contain the recipient's address.
|
||||
Log::warning('Buchungsbestätigung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
$booking->forceFill(['confirmation_failed_at' => now()])->saveQuietly();
|
||||
$this->inbox->post(
|
||||
InboxMessageKind::ConfirmationFailed,
|
||||
'booking-'.$booking->id,
|
||||
'Buchungsbestätigung '.$booking->reference.' nicht zugestellt',
|
||||
'Die Buchung ist verbindlich gespeichert, aber der Vertrag konnte nicht erzeugt oder die Bestätigung nicht versendet werden. Auf der Buchungsseite kann die Bestätigung erneut gesendet werden.',
|
||||
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||
propertyId: $booking->property_id,
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the confirmation again (admin action / command). Does nothing for bookings that are not binding.
|
||||
*/
|
||||
public function resend(Booking $booking): bool
|
||||
{
|
||||
if (! in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'erneut bestätigt');
|
||||
}
|
||||
|
||||
return $this->deliver($booking);
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,16 @@
|
||||
|
||||
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;
|
||||
@@ -24,7 +28,7 @@ class CreateChannelTasks
|
||||
/**
|
||||
* @return list<ChannelTask>
|
||||
*/
|
||||
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null): array
|
||||
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 [];
|
||||
@@ -33,14 +37,25 @@ public function handle(Property $property, CarbonInterface $startsOn, CarbonInte
|
||||
$channels = $property->channels()->active()
|
||||
->where('requires_manual_blocking', true)
|
||||
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
|
||||
->get();
|
||||
->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 = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([
|
||||
'action' => $action,
|
||||
'starts_on' => $startsOn->toDateString(),
|
||||
'ends_on' => $endsOn->toDateString(),
|
||||
'reason' => $reason,
|
||||
]))->all();
|
||||
$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 [];
|
||||
@@ -61,6 +76,30 @@ public function handle(Property $property, CarbonInterface $startsOn, CarbonInte
|
||||
*/
|
||||
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)) {
|
||||
@@ -90,4 +129,27 @@ public function sendToAutomation(ChannelTask $task): void
|
||||
$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;
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@
|
||||
use App\Tenancy\TenantContextMissing;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
@@ -84,7 +85,7 @@ private function create(Property $property, StayRequest $stay, array $guestData,
|
||||
'total' => $quote->total(),
|
||||
'deposit' => $quote->deposit(),
|
||||
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||
'hold_expires_at' => now()->addHours($property->hold_hours),
|
||||
'hold_expires_at' => $property->pre_reservation_enabled ? now()->addHours($property->hold_hours) : null,
|
||||
'message' => $message,
|
||||
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
||||
]);
|
||||
@@ -107,8 +108,8 @@ private function create(Property $property, StayRequest $stay, array $guestData,
|
||||
*/
|
||||
private function guestFor(array $guestData): array
|
||||
{
|
||||
$email = mb_strtolower($guestData['email']);
|
||||
$guest = Guest::query()->where('email', $email)->first();
|
||||
$email = mb_strtolower(trim((string) ($guestData['email'] ?? '')));
|
||||
$guest = $email === '' ? null : Guest::query()->where('email', $email)->first();
|
||||
|
||||
if ($guest === null) {
|
||||
return [Guest::create([
|
||||
@@ -138,15 +139,38 @@ private function guestFor(array $guestData): array
|
||||
}
|
||||
|
||||
/**
|
||||
* A failing mail server must not lose the reservation; failures are reported and visible in the log.
|
||||
* Automatic mode first tries to send the offer; the guest then gets the offer instead of the receipt, the
|
||||
* landlord a note either way (with the reasons when the automatic offer was not possible). A failing mail
|
||||
* server or any other error must not lose the reservation; failures are logged without personal data.
|
||||
*/
|
||||
private function sendMails(Booking $booking): void
|
||||
{
|
||||
$blockers = [];
|
||||
$offerSent = false;
|
||||
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking));
|
||||
$auto = app(AutoOffer::class);
|
||||
if ($auto->applies($booking)) {
|
||||
$blockers = $auto->handle($booking);
|
||||
$offerSent = $blockers === [];
|
||||
if (! $offerSent) {
|
||||
$booking->update(['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n\n" : '')."Automatisches Angebot nicht versendet:\n- ".implode("\n- ", $blockers))]);
|
||||
}
|
||||
$booking->refresh();
|
||||
}
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
Log::warning('Automatisches Angebot fehlgeschlagen', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
$blockers = ['Technischer Fehler beim automatischen Angebot – bitte von Hand bearbeiten.'];
|
||||
$offerSent = false;
|
||||
}
|
||||
|
||||
try {
|
||||
if (! $offerSent) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||||
}
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking, $offerSent, $blockers));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Eingangsmail nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,10 @@ class DeclineBooking
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
{
|
||||
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');
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ public static function mailboxIsStale(): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
|
||||
$lastSuccess = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
|
||||
|
||||
return $lastSuccess === null
|
||||
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
|
||||
@@ -56,7 +56,7 @@ private function monitorMailbox(): int
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
|
||||
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OccupationKind;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\PortalPrice;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Opens the booking file for a reservation that arrived through a portal calendar. The calendar only says "these
|
||||
* nights are taken"; the file gives the reservation its workflow (contact data, contract, payments, arrival,
|
||||
* cancellation) like every other booking. The imported calendar entry stays as the portal's mirror of the booking
|
||||
* (it keeps its calendar source and UID, but the booking now leads the calendar), the dates stay occupied throughout.
|
||||
*
|
||||
* Unknown facts stay unknown: the guest is a placeholder without contact data, the price is our own calculation (or
|
||||
* empty) until the portal price is entered.
|
||||
*/
|
||||
class OpenPortalFile
|
||||
{
|
||||
public function __construct(private PortalPrice $price) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(BlockedPeriod $block): Booking
|
||||
{
|
||||
return DB::transaction(function () use ($block): Booking {
|
||||
Property::query()->whereKey($block->property_id)->lockForUpdate()->firstOrFail();
|
||||
$block = BlockedPeriod::query()->whereKey($block->id)->lockForUpdate()->firstOrFail();
|
||||
|
||||
if (! in_array($block->source, ['channel', 'email'], true) || $block->channel_id === null) {
|
||||
throw new ReservationException('Eine Akte gibt es nur für Reservierungen aus einem Portalkalender.');
|
||||
}
|
||||
if ($block->occupationKind() === OccupationKind::Block) {
|
||||
throw new ReservationException('Eine Sperrzeit ist keine Reservierung. Bitte zuerst „Einordnen“ und als Portalreservierung kennzeichnen.');
|
||||
}
|
||||
if ($block->is_representation && $block->linked_booking_id !== null) {
|
||||
return Booking::query()->findOrFail($block->linked_booking_id);
|
||||
}
|
||||
if ($block->is_representation) {
|
||||
throw new ReservationException('Dieser Eintrag ist die Spiegelung einer anderen Belegung. Die Akte gehört an die führende Belegung.');
|
||||
}
|
||||
|
||||
$property = $block->property;
|
||||
$channel = $block->channel;
|
||||
$fields = (array) ($block->ical_interpretation['fields'] ?? []);
|
||||
$guest = $block->guest ?? Guest::query()->create([
|
||||
'first_name' => filled($fields['guest_first_name'] ?? null) ? (string) $fields['guest_first_name'] : 'Gast',
|
||||
'last_name' => '('.$channel->name.')',
|
||||
'email' => '',
|
||||
'tenant_id' => app(TenantContext::class)->id(),
|
||||
]);
|
||||
|
||||
$stay = new StayRequest(CarbonImmutable::parse($block->starts_on), CarbonImmutable::parse($block->ends_on), min(2, $property->max_guests));
|
||||
$booking = $property->bookings()->create([
|
||||
'guest_id' => $guest->id,
|
||||
'status' => BookingStatus::Reserved,
|
||||
'source' => 'portal',
|
||||
'origin_channel_id' => $block->origin_channel_id ?? $channel->id,
|
||||
'portal_reference' => $fields['booking_reference'] ?? null,
|
||||
'arrival' => $stay->arrival->toDateString(),
|
||||
'departure' => $stay->departure->toDateString(),
|
||||
'guests' => $stay->guests,
|
||||
'hold_expires_at' => null,
|
||||
'internal_notes' => 'Akte aus dem Portalkalender „'.$channel->name.'“ angelegt. Personenzahl und Preis sind nicht bekannt – bitte den Portalpreis erfassen.',
|
||||
...$this->price->unknownColumns($property, $stay),
|
||||
]);
|
||||
|
||||
$block->forceFill([
|
||||
'is_representation' => true, 'representation_automatic' => false, 'canonical_block_id' => null,
|
||||
'linked_booking_id' => $booking->id, 'export_approved' => false, 'needs_review' => false, 'reviewed_at' => now(),
|
||||
'occupation_kind' => OccupationKind::Reservation, 'guest_id' => $guest->id,
|
||||
'review_note' => 'Akte angelegt; die Buchung führt diese Belegung.',
|
||||
])->save();
|
||||
|
||||
app(ConfirmBooking::class)->bind($booking);
|
||||
app(ReconcileChannelRepresentations::class)->handle($property);
|
||||
|
||||
return $booking->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,14 @@
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Mail\ChannelConflict;
|
||||
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;
|
||||
|
||||
@@ -40,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
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 = [];
|
||||
|
||||
@@ -73,7 +80,7 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
}
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
|
||||
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
|
||||
}
|
||||
|
||||
return $record;
|
||||
@@ -86,7 +93,7 @@ public function channelFor(string $from): ?Channel
|
||||
{
|
||||
$from = mb_strtolower($from);
|
||||
|
||||
return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool {
|
||||
$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;
|
||||
@@ -95,6 +102,16 @@ public function channelFor(string $from): ?Channel
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -109,7 +126,7 @@ public function senders(Channel $channel): array
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $conflicts
|
||||
* @param array<string, CarbonInterface> $conflicts description => first night
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
|
||||
@@ -118,11 +135,13 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
|
||||
return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.'];
|
||||
}
|
||||
|
||||
$known = $channel->blockedPeriods()
|
||||
->whereDate('starts_on', $parsed->startsOn)
|
||||
->whereDate('ends_on', $parsed->endsOn)
|
||||
->first();
|
||||
$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];
|
||||
}
|
||||
|
||||
@@ -132,10 +151,14 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
|
||||
'ends_on' => $parsed->endsOn->toDateString(),
|
||||
'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''),
|
||||
'source' => 'email',
|
||||
'external_uid' => 'email:'.($parsed->reference ?? $parsed->startsOn->format('Ymd').'-'.$parsed->endsOn->format('Ymd')),
|
||||
'external_uid' => 'email:'.($parsed->reference ?? bin2hex(random_bytes(16))),
|
||||
]);
|
||||
|
||||
$conflicts = $this->conflictDetector->conflictsFor($block);
|
||||
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];
|
||||
}
|
||||
@@ -151,7 +174,6 @@ private function release(Channel $channel, ParsedPortalMail $parsed): array
|
||||
|
||||
$block = match (true) {
|
||||
$parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(),
|
||||
$parsed->hasPeriod() => (clone $emailBlocks)->whereDate('starts_on', $parsed->startsOn)->whereDate('ends_on', $parsed->endsOn)->first(),
|
||||
default => null,
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Support\BookingProgress;
|
||||
use Illuminate\Support\Arr;
|
||||
|
||||
/**
|
||||
* The guest's contact data arrived (portal message, e-mail, phone) and is entered on the booking. The landlord chooses
|
||||
* whether the process continues automatically – a binding portal booking gets its contract, a request gets the
|
||||
* offer – or by hand (data only). An already existing e-mail confirmation of the guest can be recorded as well.
|
||||
*/
|
||||
class ProvideGuestContact
|
||||
{
|
||||
public const AUTOMATIC = 'automatic';
|
||||
|
||||
public const MANUAL = 'manual';
|
||||
|
||||
public function __construct(private ConfirmBooking $confirm, private SendOffer $offer) {}
|
||||
|
||||
/**
|
||||
* @param array<string, ?string> $contact first_name, last_name, email, phone, street, postal_code, city, country
|
||||
* @return string what was done, for the notification
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, array $contact, string $process = self::MANUAL, bool $guestConfirmed = false): string
|
||||
{
|
||||
$contact = array_map(fn ($value) => filled($value) ? trim((string) $value) : null, Arr::only($contact, ['first_name', 'last_name', 'email', 'phone', 'street', 'postal_code', 'city', 'country']));
|
||||
if (isset($contact['email'])) {
|
||||
$contact['email'] = mb_strtolower($contact['email']);
|
||||
}
|
||||
|
||||
if ($process === self::AUTOMATIC && blank($contact['email'] ?? $booking->guest?->email)) {
|
||||
throw new ReservationException('Für den automatischen Ablauf wird die E-Mail-Adresse des Gastes benötigt.');
|
||||
}
|
||||
|
||||
$booking->guest->update(array_filter($contact, fn ($value) => $value !== null));
|
||||
if ($guestConfirmed) {
|
||||
$booking->forceFill(['guest_confirmed_at' => $booking->guest_confirmed_at ?? now()])->saveQuietly();
|
||||
}
|
||||
$booking->refresh()->load('guest');
|
||||
|
||||
if ($process !== self::AUTOMATIC) {
|
||||
return 'Kontaktdaten gespeichert';
|
||||
}
|
||||
|
||||
if (in_array($booking->status, BookingStatus::occupying(), true)) {
|
||||
$this->confirm->deliver($booking);
|
||||
|
||||
return 'Kontaktdaten gespeichert, Vertrag gesendet';
|
||||
}
|
||||
|
||||
if (BookingProgress::kind($booking) === BookingProgress::PORTAL_BOOKING) {
|
||||
$this->confirm->handle($booking);
|
||||
|
||||
return 'Kontaktdaten gespeichert, Buchung bestätigt und Vertrag gesendet';
|
||||
}
|
||||
|
||||
$this->offer->handle($booking);
|
||||
|
||||
return 'Kontaktdaten gespeichert, Angebot gesendet';
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Cancellation;
|
||||
use App\Support\CancellationCost;
|
||||
|
||||
/**
|
||||
* Records the cancellation of a booking with the cost proposed by the frozen cancellation rule. Called when a booking
|
||||
* is cancelled (by the landlord or through the guest's link); safe to call twice.
|
||||
*/
|
||||
class RecordCancellation
|
||||
{
|
||||
public function handle(Booking $booking, string $initiatedBy): Cancellation
|
||||
{
|
||||
$cost = CancellationCost::calculate($booking);
|
||||
|
||||
return Cancellation::query()->firstOrCreate(
|
||||
['booking_id' => $booking->id],
|
||||
[
|
||||
'cancelled_on' => today(),
|
||||
'initiated_by' => $initiatedBy,
|
||||
'has_policy' => $cost !== null,
|
||||
'policy_name' => $cost['policy'] ?? null,
|
||||
'days_before' => $cost['days_before'] ?? null,
|
||||
'percent' => $cost['percent'] ?? null,
|
||||
'base_amount' => $cost['base_amount'] ?? null,
|
||||
'calculated_fee' => $cost['fee'] ?? null,
|
||||
'paid_amount' => $booking->paidAmount(),
|
||||
'status' => Cancellation::OPEN,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Property;
|
||||
use App\Pricing\PortalPrice;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Records a booking that a portal already made binding (e.g. a direct booking on FeWo-direkt) – usually without
|
||||
* the guest's contact data. The booking keeps the portal as its origin channel and may carry the portal's price and
|
||||
* reference. The landlord decides how the contract process continues:
|
||||
*
|
||||
* - {@see self::CONFIRM}: the booking becomes binding right away (the dates are occupied), the contract follows
|
||||
* once the contact data is known ({@see ProvideGuestContact}) – no contract is generated before that;
|
||||
* - {@see self::CONTRACT}: binding and contract mail at once (needs the guest's e-mail address);
|
||||
* - {@see self::RECORD}: only recorded as a request, everything else is done by hand.
|
||||
*/
|
||||
class RecordPortalBooking
|
||||
{
|
||||
public const CONFIRM = 'confirm';
|
||||
|
||||
public const CONTRACT = 'contract';
|
||||
|
||||
public const RECORD = 'record';
|
||||
|
||||
public function __construct(
|
||||
private CreateReservation $create,
|
||||
private ConfirmBooking $confirm,
|
||||
private PortalPrice $price,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array<string, ?string> $guestData first_name and last_name are required, everything else optional
|
||||
*
|
||||
* @throws QuoteException
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Property $property, Channel $channel, StayRequest $stay, array $guestData, string $process = self::CONFIRM, ?string $portalReference = null, ?int $portalTotal = null, ?string $notes = null, bool $guestConfirmed = false): Booking
|
||||
{
|
||||
if ($channel->property_id !== $property->id) {
|
||||
throw new ReservationException('Der Kanal gehört nicht zu dieser Wohnung.');
|
||||
}
|
||||
|
||||
if ($process === self::CONTRACT && blank($guestData['email'] ?? null)) {
|
||||
throw new ReservationException('Für den sofortigen Vertragsversand wird die E-Mail-Adresse des Gastes benötigt.');
|
||||
}
|
||||
|
||||
$booking = $this->create->handle($property, $stay, $guestData, source: 'portal', sendMails: false);
|
||||
|
||||
$changes = ['origin_channel_id' => $channel->id, 'portal_reference' => filled($portalReference) ? trim($portalReference) : null, 'internal_notes' => filled($notes) ? trim($notes) : $booking->internal_notes];
|
||||
if ($guestConfirmed) {
|
||||
$changes['guest_confirmed_at'] = now();
|
||||
}
|
||||
if ($portalTotal !== null) {
|
||||
$changes += $this->price->columns($property, $stay, $portalTotal);
|
||||
}
|
||||
$booking->update($changes);
|
||||
|
||||
if ($process === self::RECORD) {
|
||||
return $booking->refresh();
|
||||
}
|
||||
|
||||
if ($process === self::CONTRACT) {
|
||||
$this->confirm->handle($booking, notifyGuest: true);
|
||||
} else {
|
||||
DB::transaction(fn () => $this->confirm->bind($booking));
|
||||
}
|
||||
|
||||
return $booking->refresh();
|
||||
}
|
||||
}
|
||||
+16
-11
@@ -7,6 +7,7 @@
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
@@ -20,19 +21,23 @@ class RejectOffer
|
||||
*/
|
||||
public function handle(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
if ($offerVersion !== $booking->offer_version) {
|
||||
throw ReservationException::offerOutdated();
|
||||
}
|
||||
DB::transaction(function () use ($booking, $offerVersion): void {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if ($booking->status !== BookingStatus::OfferSent) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
|
||||
}
|
||||
if ($offerVersion !== $booking->offer_version) {
|
||||
throw ReservationException::offerOutdated();
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Declined,
|
||||
'declined_by' => 'guest',
|
||||
'hold_expires_at' => null,
|
||||
]);
|
||||
if ($booking->status !== BookingStatus::OfferSent) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Declined,
|
||||
'declined_by' => 'guest',
|
||||
'hold_expires_at' => null,
|
||||
]);
|
||||
});
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest releases a held request or offer through the link in the mail – the dates are free again at once.
|
||||
* Repeating it is harmless. The link only reaches requests that are still held; a binding booking is never touched.
|
||||
*/
|
||||
class ReleaseReservation
|
||||
{
|
||||
/**
|
||||
* @return bool true when this call released the dates, false when they had been released before
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking): bool
|
||||
{
|
||||
$released = DB::transaction(function () use ($booking): bool {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if ($booking->status === BookingStatus::Declined && $booking->declined_by === 'guest') {
|
||||
return false;
|
||||
}
|
||||
if (! in_array($booking->status, BookingStatus::holding(), true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'freigegeben');
|
||||
}
|
||||
|
||||
$booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'guest', 'hold_expires_at' => null]);
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
if ($released) {
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
|
||||
} catch (Throwable $exception) {
|
||||
Log::warning('Meldung über Freigabe nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
}
|
||||
}
|
||||
|
||||
return $released;
|
||||
}
|
||||
}
|
||||
@@ -5,18 +5,24 @@
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
|
||||
* Reminds the landlord about blocking tasks that are still open after the reminder time, and again after
|
||||
* the landlord's reminder interval while they stay open (Settings::reminderIntervalDays(), 0 = only once).
|
||||
*/
|
||||
class RemindChannelTasks
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$interval = Settings::reminderIntervalDays();
|
||||
|
||||
$tasks = ChannelTask::query()
|
||||
->open()
|
||||
->whereNull('reminded_at')
|
||||
->where(fn (Builder $query) => $query
|
||||
->whereNull('reminded_at')
|
||||
->when($interval > 0, fn (Builder $query) => $query->orWhere('reminded_at', '<=', now()->subDays($interval))))
|
||||
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
|
||||
->with('channel')
|
||||
->get();
|
||||
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\OccupationKind;
|
||||
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.'];
|
||||
}
|
||||
// A stay confirmed as independent with a known booking channel (or privately) is no longer "unclear".
|
||||
if ($resolution === 'independent' && ($originId !== null || $attributes['is_private']) && in_array($block->occupationKind(), [OccupationKind::Unknown], true)) {
|
||||
$attributes['occupation_kind'] = OccupationKind::Reservation;
|
||||
}
|
||||
$block->forceFill(['representation_automatic' => false])->fill($attributes)->save();
|
||||
app(ReconcileChannelRepresentations::class)->handle($block->property);
|
||||
|
||||
return $block->refresh();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -3,22 +3,27 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Mail\ArrivalInformation;
|
||||
use App\Mail\PaymentReminder;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
|
||||
* Every message is sent at most once per booking.
|
||||
* Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord
|
||||
* (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click
|
||||
* ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured
|
||||
* number of days before arrival. Completion after departure.
|
||||
*/
|
||||
class SendBookingReminders
|
||||
{
|
||||
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
|
||||
|
||||
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
|
||||
/** Upper bound of the per-property setting; the property decides the actual day. */
|
||||
private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14;
|
||||
|
||||
/**
|
||||
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
|
||||
@@ -33,7 +38,7 @@ public function handle(): array
|
||||
->whereNull('deposit_reminded_at')
|
||||
->whereDate('deposit_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
|
||||
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
|
||||
$depositTasks = $this->createTasks($depositOverdue, BookingTaskKind::DepositReminder, fn (Booking $booking) => $booking->deposit_due_on);
|
||||
|
||||
$balanceRequest = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
@@ -41,20 +46,21 @@ public function handle(): array
|
||||
->whereDate('balance_due_on', '>=', $today)
|
||||
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
|
||||
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
|
||||
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
|
||||
$requestTasks = $this->createTasks($balanceRequest, BookingTaskKind::BalanceRequest, fn (Booking $booking) => $booking->balance_due_on);
|
||||
|
||||
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
->whereNull('balance_reminded_at')
|
||||
->whereDate('balance_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
|
||||
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
|
||||
$overdueTasks = $this->createTasks($balanceOverdue, BookingTaskKind::BalanceReminder, fn (Booking $booking) => $booking->balance_due_on);
|
||||
|
||||
$arrivals = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->whereNull('arrival_info_sent_at')
|
||||
->whereDate('arrival', '>=', $today)
|
||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
|
||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE)))
|
||||
->filter(fn (Booking $booking): bool => $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->property->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()]);
|
||||
@@ -67,9 +73,9 @@ public function handle(): array
|
||||
$completed->each->update(['status' => BookingStatus::Completed]);
|
||||
|
||||
return [
|
||||
'deposit_overdue' => $depositOverdue->count(),
|
||||
'balance_request' => $balanceRequest->count(),
|
||||
'balance_overdue' => $balanceOverdue->count(),
|
||||
'deposit_overdue' => $depositTasks,
|
||||
'balance_request' => $requestTasks,
|
||||
'balance_overdue' => $overdueTasks,
|
||||
'arrival_info' => $arrivals->count(),
|
||||
'completed' => $completed->count(),
|
||||
];
|
||||
@@ -81,20 +87,28 @@ public function handle(): array
|
||||
*/
|
||||
private function bookings(callable $constraints): Collection
|
||||
{
|
||||
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at'))
|
||||
return $constraints(Booking::query()->with(['guest', 'property', 'payments', 'importChannel', 'originChannel']))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', ''))
|
||||
->get()
|
||||
->toBase();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Booking> $bookings
|
||||
* @param callable(Booking): mixed $dueOn
|
||||
* @return int the number of tasks created now
|
||||
*/
|
||||
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
|
||||
private function createTasks(Collection $bookings, BookingTaskKind $kind, callable $dueOn): int
|
||||
{
|
||||
foreach ($bookings as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
|
||||
$booking->update([$sentAtColumn => now()]);
|
||||
$created = 0;
|
||||
foreach ($bookings->filter(fn (Booking $booking): bool => $booking->wantsPaymentTasks()) as $booking) {
|
||||
$task = BookingTask::query()->firstOrCreate(
|
||||
['booking_id' => $booking->id, 'kind' => $kind],
|
||||
['status' => BookingTaskStatus::Open, 'due_on' => $dueOn($booking)],
|
||||
);
|
||||
$created += $task->wasRecentlyCreated ? 1 : 0;
|
||||
}
|
||||
|
||||
return $created;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -3,10 +3,13 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\OfferTerms;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\InboxMessageKind;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Mail\OfferMade;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PriceCalculator;
|
||||
@@ -14,11 +17,14 @@
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Inbox;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Booking path 1 (docs/KONZEPT.md §6a): the landlord turns a request into an offer. Dates, guests, promo
|
||||
@@ -32,21 +38,32 @@ public function __construct(
|
||||
private PriceCalculator $calculator,
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
private Inbox $inbox,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, guest?: array<string, ?string>} $changes
|
||||
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, annex_ids?: ?list<int|string>, guest?: array<string, ?string>} $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 {
|
||||
$booking->lockForTransition();
|
||||
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
||||
}
|
||||
|
||||
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||
|
||||
@@ -80,19 +97,48 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t
|
||||
'offer_version' => $booking->offer_version + 1,
|
||||
'offer_sent_at' => now(),
|
||||
'offer_message' => $changes['offer_message'] ?? null,
|
||||
'offer_terms' => OfferTerms::capture(OfferTerms::templateFor($booking, $changes['contract_template_id'] ?? null), $booking, array_key_exists('annex_ids', $changes) && is_array($changes['annex_ids']) ? array_map('intval', $changes['annex_ids']) : null),
|
||||
]);
|
||||
$booking->refresh();
|
||||
$booking->update(['offer_hash' => OfferTerms::hash($booking)]);
|
||||
});
|
||||
|
||||
$booking->refresh();
|
||||
$this->contract->generate($booking, draft: true);
|
||||
|
||||
if ($sendMail) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new OfferMade($booking, $this->offerUrl($booking)));
|
||||
$this->deliver($booking);
|
||||
}
|
||||
|
||||
return $booking;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the offer mail. The offer is already saved (and its validity runs), so a failing mail server is
|
||||
* recorded in the admin inbox and reported to the caller instead of being lost.
|
||||
*
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function deliver(Booking $booking): void
|
||||
{
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new OfferMade($booking, $this->offerUrl($booking)));
|
||||
} catch (Throwable $exception) {
|
||||
// Only class and booking id are logged: mail errors can contain the recipient's address.
|
||||
Log::warning('Angebot nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]);
|
||||
$this->inbox->post(
|
||||
InboxMessageKind::OfferMailFailed,
|
||||
'booking-'.$booking->id.':v'.$booking->offer_version,
|
||||
'Angebot '.$booking->reference.' nicht zugestellt',
|
||||
'Das Angebot ist gespeichert und der Zeitraum gehalten, aber die E-Mail konnte nicht versendet werden. Auf der Buchungsseite kann der Angebotslink kopiert und dem Gast anders übermittelt werden.',
|
||||
actionUrl: BookingResource::getUrl('view', ['record' => $booking]),
|
||||
propertyId: $booking->property_id,
|
||||
);
|
||||
|
||||
throw new ReservationException('Das Angebot wurde gespeichert, aber die E-Mail konnte nicht versendet werden. Der Angebotslink kann über „Angebotslink“ kopiert werden.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's link to the offer page; valid while the offer is valid and only for this offer version.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\PaymentReminder;
|
||||
use App\Models\BookingTask;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Sends the payment mail belonging to a task – only when the landlord decides to, after checking the payment.
|
||||
* The task is completed and the dispatch is recorded on the booking; a failing mail server leaves the task open.
|
||||
*/
|
||||
class SendPaymentReminder
|
||||
{
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(BookingTask $task, string $by): void
|
||||
{
|
||||
$reminder = $task->kind->reminder();
|
||||
$booking = $task->booking->loadMissing(['guest', 'property', 'payments']);
|
||||
|
||||
if ($reminder === null) {
|
||||
throw new ReservationException('Zu dieser Aufgabe gibt es keine Zahlungs-E-Mail.');
|
||||
}
|
||||
if (blank($booking->guest?->email)) {
|
||||
throw new ReservationException('Der Gast hat keine E-Mail-Adresse.');
|
||||
}
|
||||
if ($booking->openAmount() <= 0) {
|
||||
throw new ReservationException('Die Buchung ist bereits vollständig bezahlt.');
|
||||
}
|
||||
|
||||
[$kind, $column] = $reminder;
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
|
||||
$booking->update([$column => now()]);
|
||||
$task->complete($by);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\BookingTaskKind;
|
||||
use App\Enums\BookingTaskStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use App\Models\BookingTask;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Manual status change for processes the system does not drive itself (bookings entered by hand, portal bookings):
|
||||
* the landlord moves the booking along the stages and gives a reason, which is added to the internal notes.
|
||||
* Cancelling and declining are separate actions (they inform people and record costs). Making a booking binding
|
||||
* again checks the calendar like every other writer; no mail is sent and no contract is generated here.
|
||||
*/
|
||||
class SetBookingStatus
|
||||
{
|
||||
/** @var list<BookingStatus> */
|
||||
public const TARGETS = [BookingStatus::Reserved, BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid, BookingStatus::Completed];
|
||||
|
||||
public function __construct(private AvailabilityChecker $availability) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, BookingStatus $status, string $reason, string $by = 'Verwaltung'): Booking
|
||||
{
|
||||
if (! in_array($status, self::TARGETS, true)) {
|
||||
throw new ReservationException('Auf diesen Status kann nicht von Hand gewechselt werden. Stornieren und Ablehnen haben eigene Aktionen.');
|
||||
}
|
||||
|
||||
if (blank(trim($reason))) {
|
||||
throw new ReservationException('Bitte einen Grund für die Statusänderung angeben.');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking, $status, $reason, $by): void {
|
||||
$booking->lockForTransition();
|
||||
$from = $booking->status;
|
||||
|
||||
if ($from === $status) {
|
||||
throw new ReservationException('Die Buchung hat diesen Status bereits.');
|
||||
}
|
||||
|
||||
$becomesBinding = in_array($status, BookingStatus::occupying(), true) && ! in_array($from, BookingStatus::occupying(), true);
|
||||
if ($becomesBinding && ! $this->availability->isAvailable($booking->property, $booking->arrival, $booking->departure, ignore: $booking)) {
|
||||
throw ReservationException::notAvailable();
|
||||
}
|
||||
|
||||
$changes = ['status' => $status];
|
||||
if ($becomesBinding) {
|
||||
$changes += ['hold_expires_at' => null, 'confirmed_at' => $booking->confirmed_at ?? now(), 'cancelled_at' => null];
|
||||
}
|
||||
if ($status === BookingStatus::Reserved) {
|
||||
$changes['hold_expires_at'] = null;
|
||||
}
|
||||
|
||||
$line = now()->format('d.m.Y H:i').' '.$by.': Status von „'.$from->getLabel().'“ auf „'.$status->getLabel().'“ gesetzt – '.trim($reason);
|
||||
$booking->update($changes + ['internal_notes' => trim(($booking->internal_notes ? $booking->internal_notes."\n" : '').$line)]);
|
||||
|
||||
// A booking taken back into the process no longer needs the cancellation follow-up.
|
||||
if ($becomesBinding) {
|
||||
BookingTask::query()->where('booking_id', $booking->id)->where('status', BookingTaskStatus::Open)
|
||||
->whereIn('kind', [BookingTaskKind::CancellationFee, BookingTaskKind::CancellationRequest])
|
||||
->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]);
|
||||
}
|
||||
});
|
||||
|
||||
return $booking->refresh();
|
||||
}
|
||||
}
|
||||
+124
-102
@@ -5,19 +5,17 @@
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Enums\ChannelEchoBehavior;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Support\Settings;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Imports the occupations of one portal as blocked periods and reports overlaps with
|
||||
* occupations from anywhere else immediately (possible double booking).
|
||||
*/
|
||||
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
|
||||
class SyncChannel
|
||||
{
|
||||
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
|
||||
@@ -25,105 +23,129 @@ public function __construct(private ConflictDetector $conflictDetector = new Con
|
||||
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 {
|
||||
$periods = $channel->connector()->fetchOccupations($channel);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$channel->forceFill(['last_synced_at' => now(), 'last_error' => $exception->getMessage()])->save();
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
'successful' => false,
|
||||
'message' => $exception->getMessage(),
|
||||
'duration_ms' => $this->elapsed($startedAt),
|
||||
]);
|
||||
}
|
||||
|
||||
$today = CarbonImmutable::today();
|
||||
$suffix = config('channels.uid_suffix');
|
||||
$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];
|
||||
$conflicts = [];
|
||||
|
||||
DB::transaction(function () use ($channel, $periods, $today, &$counts, &$conflicts): void {
|
||||
$existing = $channel->blockedPeriods()->where('source', 'channel')->get()->keyBy('external_uid');
|
||||
$fromEmails = $channel->blockedPeriods()->where('source', 'email')->get();
|
||||
$seen = [];
|
||||
|
||||
foreach ($periods as $period) {
|
||||
$seen[$period->uid] = true;
|
||||
$block = $existing->get($period->uid);
|
||||
|
||||
if ($block && $block->starts_on->equalTo($period->startsOn) && $block->ends_on->equalTo($period->endsOn)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
'property_id' => $channel->property_id,
|
||||
'starts_on' => $period->startsOn->toDateString(),
|
||||
'ends_on' => $period->endsOn->toDateString(),
|
||||
// The portal's SUMMARY is not stored: it may contain guest names (data minimisation).
|
||||
'reason' => $channel->name,
|
||||
'source' => 'channel',
|
||||
];
|
||||
|
||||
$confirmedEmailBlock = $block ? null : $fromEmails->first(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->equalTo($period->startsOn) && $emailBlock->ends_on->equalTo($period->endsOn));
|
||||
|
||||
if ($confirmedEmailBlock) {
|
||||
// Already blocked from the portal's e-mail; the calendar only confirms it.
|
||||
$confirmedEmailBlock->update([...$attributes, 'external_uid' => $period->uid]);
|
||||
$fromEmails = $fromEmails->reject(fn (BlockedPeriod $emailBlock): bool => $emailBlock->is($confirmedEmailBlock));
|
||||
$counts['changed']++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($block) {
|
||||
$block->update($attributes);
|
||||
$counts['changed']++;
|
||||
} else {
|
||||
$block = $channel->blockedPeriods()->create([...$attributes, 'external_uid' => $period->uid]);
|
||||
$counts['added']++;
|
||||
}
|
||||
|
||||
// E-mail blocks of this portal overlapping the calendar entry describe the same booking with deviating dates.
|
||||
$superseded = $fromEmails->filter(fn (BlockedPeriod $emailBlock): bool => $emailBlock->starts_on->lessThan($block->ends_on) && $emailBlock->ends_on->greaterThan($block->starts_on));
|
||||
$superseded->each->delete();
|
||||
$fromEmails = $fromEmails->diff($superseded);
|
||||
|
||||
array_push($conflicts, ...$this->conflictDetector->conflictsFor($block));
|
||||
$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);
|
||||
|
||||
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
|
||||
$stale->each->delete();
|
||||
$counts['removed'] = $stale->count();
|
||||
});
|
||||
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();
|
||||
|
||||
$channel->forceFill([
|
||||
'last_synced_at' => now(),
|
||||
'last_success_at' => now(),
|
||||
'last_error' => null,
|
||||
'alerted_at' => null,
|
||||
])->save();
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
|
||||
return $channel->syncLogs()->create(['successful' => false, 'message' => $exception->getMessage(),
|
||||
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
'successful' => true,
|
||||
'events' => count($periods),
|
||||
...$counts,
|
||||
'conflicts' => count($conflicts),
|
||||
'duration_ms' => $this->elapsed($startedAt),
|
||||
]);
|
||||
}
|
||||
|
||||
private function elapsed(float $startedAt): int
|
||||
{
|
||||
return (int) round((microtime(true) - $startedAt) * 1000);
|
||||
}
|
||||
}
|
||||
@@ -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 = [];
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Enums\ChannelBookingModel;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelExportRequest;
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Collection;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Whether the calendars of the connected portals are good enough to commit to a stay without a human looking.
|
||||
*
|
||||
* Two kinds of evidence, both taken from what the synchronisation already records:
|
||||
* - import: the last successful import of every importing channel is recent (otherwise one import is tried first);
|
||||
* - export: a channel that can book instantly (booking model portal booking / mixed) has fetched OUR feed after the
|
||||
* block was created. The feed is built from the database on every request, so a successful fetch of that channel's
|
||||
* own token after the block existed contains it. This proves delivery, not that the portal has processed it –
|
||||
* the remaining risk is documented in BOOKING-E2E-IMPLEMENTATION.md.
|
||||
*
|
||||
* Network access happens only in {@see refresh()} and never inside a database transaction.
|
||||
*/
|
||||
class CalendarClearance
|
||||
{
|
||||
public function __construct(private SyncChannel $sync) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Channel>
|
||||
*/
|
||||
public function staleImports(Property $property): Collection
|
||||
{
|
||||
$limit = now()->subMinutes((int) config('fewo.channels.fresh_within_minutes'));
|
||||
|
||||
return $property->channels()->active()->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->importsOccupations())
|
||||
->filter(fn (Channel $channel): bool => $channel->last_success_at === null || $channel->last_success_at->lessThan($limit))
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports the channels whose calendar is not recent (one attempt each); failures stay visible as stale.
|
||||
*/
|
||||
public function refresh(Property $property): void
|
||||
{
|
||||
foreach ($this->staleImports($property) as $channel) {
|
||||
try {
|
||||
$this->sync->handle($channel);
|
||||
} catch (Throwable) {
|
||||
// The sync log records the failure; the channel simply stays stale.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Instant-booking channels that have not fetched our feed since the block exists.
|
||||
*
|
||||
* @return Collection<int, Channel>
|
||||
*/
|
||||
public function unprovenInstantChannels(Property $property, CarbonInterface $blockedSince): Collection
|
||||
{
|
||||
return $property->channels()->active()->get()
|
||||
->filter(fn (Channel $channel): bool => $this->canBookInstantly($channel))
|
||||
->reject(fn (Channel $channel): bool => $channel->exportsOccupations() && $this->fetchedFeedSince($channel, $blockedSince))
|
||||
->values();
|
||||
}
|
||||
|
||||
public function canBookInstantly(Channel $channel): bool
|
||||
{
|
||||
return in_array($channel->booking_model, [ChannelBookingModel::PortalBooking, ChannelBookingModel::Mixed], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reasons (German, for the admin) why the calendar state cannot be trusted yet; empty = cleared.
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function reasons(Property $property, CarbonInterface $blockedSince): array
|
||||
{
|
||||
$reasons = [];
|
||||
|
||||
foreach ($this->staleImports($property) as $channel) {
|
||||
$reasons[] = "Kalenderstand von {$channel->name} ist nicht aktuell (letzter erfolgreicher Import: ".($channel->last_success_at?->format('d.m.Y, H:i') ?? 'nie').').';
|
||||
}
|
||||
|
||||
foreach ($this->unprovenInstantChannels($property, $blockedSince) as $channel) {
|
||||
$reasons[] = $channel->exportsOccupations()
|
||||
? "{$channel->name} (Sofortbuchung) hat unseren Kalender seit der Sperre noch nicht abgerufen."
|
||||
: "Der Kalenderexport an {$channel->name} (Sofortbuchung) ist nicht aktiv.";
|
||||
}
|
||||
|
||||
return $reasons;
|
||||
}
|
||||
|
||||
private function fetchedFeedSince(Channel $channel, CarbonInterface $blockedSince): bool
|
||||
{
|
||||
return ChannelExportRequest::query()
|
||||
->where('channel_id', $channel->id)
|
||||
->where('requested_at', '>=', $blockedSince->copy()->addSecond())
|
||||
->where('response_status', 200)
|
||||
->where('export_state', 'live')
|
||||
->exists();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?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, 'archived_booking' => $booking->archived_at !== null,
|
||||
'channel_id' => $booking->origin_channel_id ?? $booking->import_channel_id,
|
||||
'representations' => $booking->channel_representations_count,
|
||||
'mirrored_channels' => $booking->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
|
||||
'url' => BookingResource::getUrl('view', ['record' => $booking->id]),
|
||||
'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(), 'archived_booking' => false, 'channel_id' => $block->origin_channel_id ?? $block->channel_id, 'representations' => $block->channel_representations_count,
|
||||
'mirrored_channels' => $block->channelRepresentations->pluck('channel.name')->filter()->unique()->values()->all(),
|
||||
'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]),
|
||||
'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null,
|
||||
]);
|
||||
}
|
||||
|
||||
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];
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,7 @@ public function conflictsFor(BlockedPeriod $block): array
|
||||
->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)))
|
||||
|
||||
@@ -14,5 +14,7 @@ public function __construct(
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
public array $properties = [],
|
||||
public ?string $raw = null,
|
||||
) {}
|
||||
}
|
||||
@@ -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']];
|
||||
}
|
||||
}
|
||||
@@ -32,9 +32,11 @@ public static function settingsSchema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('settings.import_url')
|
||||
->label('iCal-Export-Adresse des Portals')
|
||||
->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),
|
||||
];
|
||||
}
|
||||
@@ -45,6 +47,17 @@ public function canImport(Channel $channel): bool
|
||||
}
|
||||
|
||||
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'));
|
||||
|
||||
@@ -55,9 +68,9 @@ public function fetchOccupations(Channel $channel): array
|
||||
->get($url)
|
||||
->throw();
|
||||
} catch (ConnectionException|RequestException $exception) {
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception);
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden. Netzwerkverbindung und Portaladresse prüfen.', previous: $exception);
|
||||
}
|
||||
|
||||
return $this->parser->parse($response->body());
|
||||
return $response->body();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Enums\ChannelExportMode;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -23,21 +24,32 @@ public function build(Channel $channel): string
|
||||
|
||||
$events = [];
|
||||
|
||||
foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) {
|
||||
$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);
|
||||
$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))
|
||||
->get();
|
||||
|
||||
foreach ($blocks as $block) {
|
||||
$events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at);
|
||||
->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');
|
||||
}
|
||||
|
||||
return implode("\r\n", [
|
||||
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',
|
||||
@@ -46,10 +58,12 @@ public function build(Channel $channel): string
|
||||
'X-WR-CALNAME:'.$this->escape($property->name),
|
||||
...$events,
|
||||
'END:VCALENDAR',
|
||||
])."\r\n";
|
||||
];
|
||||
|
||||
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): string
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified, array $properties): string
|
||||
{
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VEVENT',
|
||||
@@ -57,7 +71,7 @@ private function event(string $uid, CarbonInterface $start, CarbonInterface $end
|
||||
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
|
||||
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
|
||||
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
|
||||
'SUMMARY:Belegt',
|
||||
...array_map(fn (string $field, string $value): string => $field.':'.$this->escape($value), array_keys($properties), array_values($properties)),
|
||||
'TRANSP:OPAQUE',
|
||||
'END:VEVENT',
|
||||
]);
|
||||
@@ -65,6 +79,21 @@ private function event(string $uid, CarbonInterface $start, CarbonInterface $end
|
||||
|
||||
private function escape(string $text): string
|
||||
{
|
||||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -5,117 +5,240 @@
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Minimal RFC 5545 reader for availability feeds: VEVENTs with DTSTART/DTEND (date or date-time),
|
||||
* UID and SUMMARY. Cancelled events and events without a positive length are skipped.
|
||||
*/
|
||||
/** Complete non-recurring availability snapshots; damaged feeds never become deletions. */
|
||||
class ICalParser
|
||||
{
|
||||
/**
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
/** @return list<ExternalPeriod> */
|
||||
public function parse(string $ics): array
|
||||
{
|
||||
if (! str_contains($ics, 'BEGIN:VCALENDAR')) {
|
||||
throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.');
|
||||
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);
|
||||
}
|
||||
|
||||
$lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics)));
|
||||
|
||||
$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 = [];
|
||||
$event = null;
|
||||
$properties = [];
|
||||
$eventLines = [];
|
||||
$identities = [];
|
||||
$propertyIdentities = [];
|
||||
$started = false;
|
||||
$closed = false;
|
||||
foreach ($lines as $line) {
|
||||
$line = rtrim($line, "\r");
|
||||
|
||||
if ($line === 'BEGIN:VEVENT') {
|
||||
$event = [];
|
||||
|
||||
if (in_array('VEVENT', $stack, true)) {
|
||||
$eventLines[] = $line;
|
||||
}
|
||||
if ($line === '' && $stack === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line === 'END:VEVENT') {
|
||||
if ($event !== null && ($period = $this->toPeriod($event))) {
|
||||
$periods[] = $period;
|
||||
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.');
|
||||
}
|
||||
$event = null;
|
||||
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;
|
||||
}
|
||||
|
||||
if ($event !== null && str_contains($line, ':')) {
|
||||
[$nameWithParams, $value] = explode(':', $line, 2);
|
||||
$parts = explode(';', $nameWithParams);
|
||||
$event[strtoupper($parts[0])] = ['value' => $value, 'params' => array_slice($parts, 1)];
|
||||
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 $periods;
|
||||
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
|
||||
{
|
||||
if (! isset($event['DTSTART']) || strtoupper($event['STATUS']['value'] ?? '') === 'CANCELLED') {
|
||||
$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']);
|
||||
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay();
|
||||
|
||||
if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) {
|
||||
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;
|
||||
|
||||
$uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString());
|
||||
|
||||
return new ExternalPeriod($uid, $start, $end, $this->unescape($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
|
||||
/** @param array{value: string, params: list<string>} $property */
|
||||
private function toDate(array $property): CarbonImmutable
|
||||
{
|
||||
$value = trim($property['value']);
|
||||
|
||||
if (preg_match('/^\d{8}$/', $value)) {
|
||||
return CarbonImmutable::createFromFormat('!Ymd', $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.');
|
||||
}
|
||||
}
|
||||
|
||||
if (preg_match('/^(\d{8})T(\d{6})(Z?)$/', $value, $match)) {
|
||||
$timezone = $match[3] === 'Z' ? 'UTC' : $this->timezone($property['params']);
|
||||
|
||||
return CarbonImmutable::createFromFormat('YmdHis', $match[1].$match[2], $timezone)
|
||||
->setTimezone(config('app.timezone'))
|
||||
->startOfDay();
|
||||
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.');
|
||||
}
|
||||
|
||||
return null;
|
||||
throw new ChannelSyncException('Ungültiges Kalenderdatum.');
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $params
|
||||
*/
|
||||
/** @param list<string> $params */
|
||||
private function timezone(array $params): string
|
||||
{
|
||||
foreach ($params as $param) {
|
||||
if (str_starts_with(strtoupper($param), 'TZID=')) {
|
||||
$tz = trim(substr($param, 5), '"');
|
||||
$zone = trim(substr($param, 5), '"');
|
||||
if (! in_array($zone, timezone_identifiers_list(), true)) {
|
||||
throw new ChannelSyncException('Unbekannte Kalenderzeitzone.');
|
||||
}
|
||||
|
||||
return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone');
|
||||
return $zone;
|
||||
}
|
||||
}
|
||||
|
||||
return config('app.timezone');
|
||||
}
|
||||
|
||||
private function unescape(?string $text): ?string
|
||||
{
|
||||
return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
@@ -17,11 +18,31 @@ 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 filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
|
||||
return self::configuration() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,7 +53,11 @@ public static function isConfigured(): bool
|
||||
*/
|
||||
public function fetch(array $senders): array
|
||||
{
|
||||
$config = config('fewo.mailbox');
|
||||
$config = self::configuration();
|
||||
|
||||
if ($config === null) {
|
||||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||||
}
|
||||
|
||||
try {
|
||||
$client = (new ClientManager)->make([
|
||||
@@ -62,13 +87,13 @@ public function fetch(array $senders): array
|
||||
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
|
||||
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::LAST_SUCCESS_KEY, now()->toIso8601String());
|
||||
Cache::forget(self::LAST_ERROR_KEY);
|
||||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
}
|
||||
}
|
||||
@@ -5,24 +5,40 @@
|
||||
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 the mailbox and block recognised bookings immediately')]
|
||||
#[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.
|
||||
* 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): int
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail, TenantRunner $runner): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
|
||||
$runner->each(fn (Tenant $tenant) => $this->fetchForCurrentLandlord($reader, $processPortalMail, $tenant));
|
||||
|
||||
return self::SUCCESS;
|
||||
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()
|
||||
@@ -32,25 +48,23 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa
|
||||
->all();
|
||||
|
||||
if ($senders === []) {
|
||||
$this->line('Für kein Portal sind Absender hinterlegt.');
|
||||
$this->line("{$tenant->name}: für kein Portal sind Absender hinterlegt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$mails = $reader->fetch($senders);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
$this->error("{$tenant->name}: {$exception->getMessage()}");
|
||||
|
||||
return self::FAILURE;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($mails as $mail) {
|
||||
if ($record = $processPortalMail->handle($mail)) {
|
||||
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
$this->info("{$tenant->name} – {$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\CancellationPolicy;
|
||||
use App\Models\ContractTemplate;
|
||||
use App\Models\Property;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('contracts:install-fewo-direkt {--data=* : Wohnungsdaten als name=wert (z. B. wlan_passwort=…), werden nicht im Code gespeichert}')]
|
||||
#[Description('Legt den Mietvertrag für FeWo-direkt-Direktbuchungen (Text des Vermieters) als Vertragsvorlage an, falls noch nicht vorhanden')]
|
||||
class InstallFewoDirektContract extends Command
|
||||
{
|
||||
public const NAME = 'FeWo-direkt Direktbuchung';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(TenantRunner $runner): int
|
||||
{
|
||||
$data = [];
|
||||
foreach ((array) $this->option('data') as $pair) {
|
||||
[$name, $value] = array_pad(explode('=', (string) $pair, 2), 2, null);
|
||||
if (filled($name) && $value !== null && preg_match('/^[a-z0-9_]+$/', $name) === 1) {
|
||||
$data[$name] = $value;
|
||||
}
|
||||
}
|
||||
|
||||
$runner->each(function (Tenant $tenant) use ($data): void {
|
||||
if (ContractTemplate::query()->where('name', self::NAME)->exists()) {
|
||||
$this->info("{$tenant->name}: Vorlage „".self::NAME.'“ ist schon vorhanden – nichts geändert.');
|
||||
} else {
|
||||
ContractTemplate::query()->create([
|
||||
'name' => self::NAME,
|
||||
'version' => 1,
|
||||
'body' => self::body(),
|
||||
'annex_title' => 'Ergänzende Vereinbarung zum Mietvertrag für die Wohnung „Am Stadtwald“, Wohnung 3',
|
||||
'annex_body' => self::annex(),
|
||||
'texts' => ['cancellation' => self::cancellation()],
|
||||
'notes' => 'Übernommen aus dem Mietvertrag für FeWo-direkt-Direktbuchungen. Zugangsdaten stehen als Platzhalter {{ wohnung.… }}; Werte unter Wohnung › Vertragsdaten.',
|
||||
]);
|
||||
$this->info("{$tenant->name}: Vorlage „".self::NAME.'“ angelegt.');
|
||||
}
|
||||
|
||||
$policy = CancellationPolicy::query()->firstOrCreate(['name' => 'Direktbuchung Standard'], [
|
||||
'base' => CancellationPolicy::BASE_RENT,
|
||||
'tiers' => [['min_days' => 60, 'percent' => 0], ['min_days' => 30, 'percent' => 50], ['min_days' => 0, 'percent' => 100]],
|
||||
'replacement_fee' => 3500,
|
||||
'notes' => 'Staffel und Ersatzmieter-Gebühr aus § 13 des FeWo-direkt-Vertrags, berechnet vom Mietpreis. Bitte prüfen.',
|
||||
]);
|
||||
ContractTemplate::query()->where('name', self::NAME)->whereNull('cancellation_policy_id')->update(['cancellation_policy_id' => $policy->id]);
|
||||
|
||||
if ($data !== []) {
|
||||
$property = Property::query()->first();
|
||||
if ($property !== null) {
|
||||
$property->update(['contract_data' => [...(array) $property->contract_data, ...$data]]);
|
||||
$this->info("{$tenant->name}: ".count($data).' Vertragsdaten an der Wohnung gesetzt: '.implode(', ', array_keys($data)));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private static function body(): string
|
||||
{
|
||||
return <<<'HTML'
|
||||
<p>zwischen</p>
|
||||
<p>{{ mieter }} (Mieter)</p>
|
||||
<p>und</p>
|
||||
<p>Frau {{ vermieter }}, {{ vermieter_anschrift }} (Vermieter)</p>
|
||||
<p>wird folgender Mietvertrag geschlossen:</p>
|
||||
|
||||
<h3>§ 1 Mietgegenstand</h3>
|
||||
<p>Vermietet wird eine Zweizimmer-Ferienwohnung, bestehend aus einem Wohnzimmer mit integrierter Küche, einer Diele mit großem Schrank, einem separaten Schlafzimmer, einem Duschbad mit WC und einer Terrasse im Erdgeschoss des Hauses „Am Stadtwald“, Strandstr. 15, Wohnung Nr. 3 in 18225 Ostseebad Kühlungsborn. Zur Wohnung gehört während der Urlaubsdauer ein eigener Parkplatz (Nr. 3). Dieser Platz befindet sich hinter dem Haus, schräg gegenüber der Hauseingangstür.</p>
|
||||
|
||||
<h3>§ 2 Mietdauer, An- und Abreise</h3>
|
||||
<p>Die Räumlichkeiten werden vermietet an {{ personen }} erwachsene Personen von {{ anreise }} bis {{ abreise }}. Die reservierte Wohnung steht dem Gast ab {{ checkin }} Uhr am Anreisetag und bis {{ checkout }} Uhr am Abreisetag zur Verfügung.</p>
|
||||
<p>Die Schlüssel für Ihre Ferienwohnung erhalten Sie von der <strong>Firma BALU Dienstleistungen, Ostseeallee 36/37 in 18225 Kühlungsborn.</strong> Die Mitarbeiter und Mitarbeiterinnen sind auch Ihre Ansprechpartner, falls Sie Fragen oder Probleme haben sollten. Die Telefonnummer lautet:</p>
|
||||
<p><strong>038293-87 72 48.</strong></p>
|
||||
<p>Bitte rufen Sie dort <u>zwei bis drei Tage vor Ihrer Anreise bis 14:00 Uhr</u> an, um die Schlüsselübergabe abzusprechen.</p>
|
||||
|
||||
<h3>§ 3 Kurtaxe</h3>
|
||||
<p>Die Anmeldung in der Tourist-Information übernimmt ebenfalls die Fa. BALU. Dort werden Ihnen auch Ihre Kurkarten ausgehändigt. Die Kurabgabe beträgt derzeit in der Hauptsaison 3,00 €/Pers. und in der Nebensaison 1,60 €/Pers./Tag. Kinder bis 16 Jahre zahlen keine Kurabgabe. Das Geld dafür zahlen Sie direkt bei Schlüsselübergabe bzw. später, falls Sie außerhalb der Geschäftszeit anreisen.</p>
|
||||
|
||||
<h3>§ 4 Miete</h3>
|
||||
<p>Die Miete inkl. aller Verbrauchskosten in der Wohnung sowie die von Ihrer Betreuungsfirma BALU erhobenen Kosten für Endreinigung und Service für {{ naechte }} Nächte inkl. der Servicegebühr von fewo-direkt beträgt insgesamt <strong>{{ gesamtpreis }}.</strong> Die Servicegebühr Ihres Internetanbieters sowie die Anzahlung wurden bereits bei Buchung von {{ anzahlung }} über Ihre Kreditkarte eingezogen. Zur Zahlung der restlichen Miete wird Ihr Internetanbieter Sie zum vereinbarten Termin auffordern, Ihre Buchung zu bestätigen und den Restbetrag zu zahlen.</p>
|
||||
|
||||
<h3>§ 5 Vertragsbedingungen</h3>
|
||||
<p>Durch Ihre geleistete Anzahlung erklären sich die Mieter mit der Annahme des Vertrages einverstanden und verpflichten sich, Wohnung und Einrichtung pfleglich zu behandeln und eventuelle Schäden oder Bruch zu ersetzen bzw. durch deren Haftpflichtversicherung ersetzen zu lassen.</p>
|
||||
|
||||
<h3>§ 6 Bettwäsche und Wäschepakete/Sauna</h3>
|
||||
<p>Die Firma BALU bietet Bettwäsche und Handtuchpakete zum Gesamtpreis von 23,00 €/Pers. an. Sie können auch Einzelpakete buchen. In dem Fall beträgt der Preis für fertig überzogene Betten 14,00 €/Pers. und für das Handtuchpaket (Dusch- und Handtuch, Duschvorleger) 11,00 €/Pers..</p>
|
||||
<p>Wenn Sie eigene Wäsche mitbringen, entstehen für Sie keine weiteren Kosten.</p>
|
||||
<p>Ihre Wünsche teilen Sie im Bedarfsfall bitte rechtzeitig telefonisch der Firma BALU mit.</p>
|
||||
<p>Ein Geschirrtuch und ein Abwaschtuch werden generell zur Verfügung gestellt und sind im Mietpreis enthalten.</p>
|
||||
<p>Falls Sie das Schrankbett nutzen wollen, benötigen Sie ein <u>übergroßes Spannbettlaken</u> oder ein <u>einfaches Laken</u> ohne Gummizug (das normale Spannbetttuch ist zu klein). Unter das ausgeklappte Schrankbett stellen Sie bitte zur Stabilität rechts und links die Holzstützen.</p>
|
||||
<p>Bei geplanten Saunabesuchen vergessen Sie nicht, Saunatücher und zusätzliche Handtücher mit einzupacken. Empfehlenswert ist auch, für die Sauna 1 €-Münzen bereitzuhalten. Sollte der Saunabesuch wegen des Ansteckungsrisikos oder aus anderen Gründen nicht möglich sein, wird von Seiten der Vermieterin keine Haftung übernommen.</p>
|
||||
|
||||
<h3>§ 7 Schlüssel und Abfallentsorgung</h3>
|
||||
<p>Sie erhalten zwei gleiche Schlüssel für die Hauseingangs- und Wohnungstür, Waschküche, den Saunabereich sowie den Abfallcontainer. <strong>Wichtig</strong>: Beide Schlüssel müssen am Abreisetag bei der Firma BALU abgegeben oder in den dort vorhandenen Briefkasten geworfen werden. Die Kellertür ist mit einem Zahlenschloss gesichert. Der Code lautet <strong>{{ wohnung.kellercode }}</strong>.</p>
|
||||
|
||||
<h3>§ 8 Schlüsselübergabe durch die Firma BALU nach Dienstschluss</h3>
|
||||
<p>Bei Anreise außerhalb der Bürozeiten erfolgt die Schlüsselausgabe am Büro der Betreuungsfirma BALU. Ihr persönlicher Schlüsselsafe befindet sich im Foyer links hinter der Eingangstür. Beides ist mit einem Zifferncode zu öffnen. Die Bedienungsanleitung finden Sie direkt über der Tastatur links neben der Eingangstür von außen. Die entsprechenden Codes erfragen Sie bitte telefonisch vor Ort oder per SMS oder WhatsApp bei der Vermieterin.</p>
|
||||
|
||||
<h3>§ 9 Hausordnung</h3>
|
||||
<p>Die Mieter sind verpflichtet, sich an die im Flur aushängende Hausordnung zu halten.</p>
|
||||
|
||||
<h3>§ 10 Sorgfaltspflichten</h3>
|
||||
<p>Die Mieter haben die Räumlichkeiten und die Einrichtungsgegenstände pfleglich zu behandeln. Schuldhaft verursachte Schäden müssen von den Mietern ersetzt werden. Die Mieter sind verpflichtet, bei Bezug der Räumlichkeiten die Einrichtung auf ihre Vollständigkeit und ihre Gebrauchstauglichkeit hin zu überprüfen und eventuelle Beanstandungen <u>umgehend</u> bei Firma BALU oder der Eigentümerin zu melden. Zu spät eingegangene Beanstandungen werden nicht anerkannt und den Mietern angelastet. Während der Mietzeit eintretende Schäden haben die Mieter ebenfalls <u>unverzüglich</u> an die Firma BALU oder die Eigentümerin selbst zu melden. Kommen die Mieter diesen Pflichten nicht nach, steht ihnen eine Mietminderung wegen dieser zu beanstandenden Punkte nicht zu.</p>
|
||||
<p>Es wird darum gebeten, <strong><u>keinesfalls Desinfektionsmittel oder Raumspray zum Sprühen</u></strong> zu verwenden, da dieses Alkohol enthält und das Mobiliar und insbesondere die Ledergarnitur beschädigen kann.</p>
|
||||
<p>In der Wohnung darf nicht geraucht werden. Die Mieter werden gebeten, zum Rauchen auf die Terrasse zu gehen. Die Vermieterin kann jedoch nicht garantieren, dass das Rauchverbot auch in jedem Fall eingehalten wird. Eine Mietminderung steht den Mietern bei Nichteinhaltung des Verbots nicht zu.</p>
|
||||
|
||||
<h3>§ 11 Internet</h3>
|
||||
<p>Der Internetanschluss in der Wohnung wird kostenlos zur Verfügung gestellt. Bei Störungen der Leitung oder sonstigen Widrigkeiten und dadurch bedingtem Leistungsausfall kann eine Mietminderung ebenfalls nicht geltend gemacht werden.</p>
|
||||
|
||||
<h3>§ 12 Internet-Nutzungsbedingungen</h3>
|
||||
<p>Bestandteil dieses Vertrages ist die <em>„Ergänzende Vereinbarung zum Mietvertrag für die Wohnung „Am Stadtwald“, Wohnung 3““</em>. Die Vermieterin bittet um Bestätigung per eMail, dass der Inhalt zur Kenntnis genommen und akzeptiert wurde.</p>
|
||||
|
||||
<h3>§ 13 Rücktritt</h3>
|
||||
<p>Die Mieter sind berechtigt, vor Mietbeginn vom Vertrag zurückzutreten. Im Falle eines solchen Rücktritts wird eine Entschädigung geltend gemacht, und zwar wie folgt:</p>
|
||||
<ul>
|
||||
<li>Rücktritt bis 60 Tage vor Mietbeginn: 0% des Mietpreises</li>
|
||||
<li>Rücktritt 59 bis 30 Tage vor Mietbeginn: 50% des Mietpreises</li>
|
||||
<li>Rücktritt ab 29 Tage vor Mietbeginn bis Mietbeginn: 100% des Mietpreises.</li>
|
||||
</ul>
|
||||
<p>Den Mietern wird ausdrücklich der Nachweis gestattet, ein Schaden sei überhaupt nicht entstanden oder wesentlich niedriger als die Pauschale. Die Mieter haben das Recht, Ersatzmieter zu stellen, die die Wohnung in vollem Umfang übernehmen. Dafür kann eine Bearbeitungsgebühr von 35,00 € berechnet werden. Rücktrittsgebühren werden dann nicht erhoben.</p>
|
||||
|
||||
<h3>§ 14 Verlassen der Wohnung</h3>
|
||||
<p>Die Wohnung muss besenrein verlassen werden, da diese Arbeiten nicht in der Endreinigungspauschale enthalten sind. Dazu gehören u. a.</p>
|
||||
<ul>
|
||||
<li>die Entsorgung des Abfalls in die bereitstehenden Müllcontainer,</li>
|
||||
<li>das gespülte Geschirr in den Schrank einräumen und die Tür der geleerten Spülmaschine öffnen,</li>
|
||||
<li>Möbel und andere Gegenstände an ihren ursprünglichen Standort stellen.</li>
|
||||
</ul>
|
||||
|
||||
<h3>§ 15 Gerichtsstand</h3>
|
||||
<p>Gerichtsstand bei Streitigkeiten ist Dortmund. Es gilt deutsches Recht.</p>
|
||||
|
||||
<h3>§ 16 Schriftform</h3>
|
||||
<p>Änderungen und Ergänzungen dieses Vertrages bedürfen der Schriftform. Die schriftliche Form kann u. a. auch per E-Mail erfolgen.</p>
|
||||
|
||||
<h3>§ 17 Datenschutz</h3>
|
||||
<p>Ihre personenbezogenen Daten werden nur zum Erstellen der Mietunterlagen und zur Kommunikation mit Ihnen verarbeitet. Eine Übermittlung Ihrer persönlichen Daten an Dritte zu anderen, als den genannten Zwecken, findet nicht statt. Weitere Einzelheiten und die Datenschutzerklärung finden Sie auf meiner Website unter www.fewo-stommer.de unter dem Menüpunkt „Datenschutz“.</p>
|
||||
|
||||
<h3>§ 18 Salvatorische Klausel</h3>
|
||||
<p>Sollten einzelne Bestimmungen dieses Vertrages ganz oder teilweise unwirksam sein oder werden oder sollte sich im Vertrag eine Lücke befinden, so soll hierdurch die Gültigkeit der übrigen Bestimmungen nicht berührt werden. Anstelle der unwirksamen Bestimmung oder zur Ausfüllung der Lücke soll eine angemessene Regelung treten, die, soweit rechtlich möglich, dem am nächsten kommt, was die Vertragsparteien gewollt oder nach dem Sinn und Zweck dieses Vertrages gewollt haben dürften, wenn sie den Punkt bedacht hätten.</p>
|
||||
|
||||
<p>Dortmund, den {{ datum }}<br><em>(Die Unterschrift wurde maschinell erstellt und ist gültig)</em></p>
|
||||
HTML;
|
||||
}
|
||||
|
||||
private static function annex(): string
|
||||
{
|
||||
return <<<'HTML'
|
||||
<p>Der Vermieter stellt dem Mieter den Internetzugang per WLan kostenfrei zur Verfügung.</p>
|
||||
<p>Die Login-Daten für den WLan-Zugriff dürfen nicht an fremde Personen weitergegeben werden und sind vertraulich zu behandeln.</p>
|
||||
<p>Folgende Aktivitäten sind generell untersagt:</p>
|
||||
<ul>
|
||||
<li>Abrufen von kostenpflichtigen Dienstleistungen,</li>
|
||||
<li>Nutzung im Zusammenhang mit anstößigem oder strafrechtlich relevantem Inhalt,</li>
|
||||
<li>übermäßige Belastung durch große Datenmengen.</li>
|
||||
</ul>
|
||||
<p>Auch wenn der Mieter im Außenverhältnis für eine kostenpflichtige Nutzung haftet, stellt er den Vermieter vorsorglich von etwaigen Ansprüchen Dritter frei.</p>
|
||||
<p>Der Vermieter wird die Privatsphäre der Mieter wahren. Dazu gehört auch der Anspruch auf Vertraulichkeit der Nutzung der Online-Dienste.</p>
|
||||
<p>Der Vermieter verfügt jedoch über die Verkehrs-und Logdaten, welche festhalten, wann welche Verbindungen hergestellt worden sind. Bei begründetem Verdacht auf missbräuchliche Nutzung können diese Daten ausgewertet werden. Diese Daten werden nach drei Monaten gelöscht.</p>
|
||||
<h3>WLan-Netzwerk</h3>
|
||||
<p>Zugangsdaten für den Router sind:</p>
|
||||
<p>Benutzername: {{ wohnung.wlan_benutzer }}</p>
|
||||
<p>Passwort: {{ wohnung.wlan_passwort }}</p>
|
||||
<h3>Dunstabzugshaube</h3>
|
||||
<p>Damit die Dunstabzugshaube die Abluft gut abtransportieren kann, muss zusätzlich der Schalter „Lüfter“ betätigt und die Fenstertür geöffnet (schräg gestellt) werden.</p>
|
||||
<h3>Spülmaschine</h3>
|
||||
<p>Bitte beachten Sie das Hinweisschild in der Innenseite der Schranktür über der Spülmaschine. Die Spülmaschine enthält eine Besteckschublade (keinen Besteckkorb).</p>
|
||||
HTML;
|
||||
}
|
||||
|
||||
private static function cancellation(): string
|
||||
{
|
||||
return '<p>Die Mieter sind berechtigt, vor Mietbeginn vom Vertrag zurückzutreten. Im Falle eines solchen Rücktritts wird eine Entschädigung geltend gemacht, und zwar wie folgt:</p><ul><li>Rücktritt bis 60 Tage vor Mietbeginn: 0% des Mietpreises</li><li>Rücktritt 59 bis 30 Tage vor Mietbeginn: 50% des Mietpreises</li><li>Rücktritt ab 29 Tage vor Mietbeginn bis Mietbeginn: 100% des Mietpreises.</li></ul><p>Den Mietern wird ausdrücklich der Nachweis gestattet, ein Schaden sei überhaupt nicht entstanden oder wesentlich niedriger als die Pauschale. Die Mieter haben das Recht, Ersatzmieter zu stellen, die die Wohnung in vollem Umfang übernehmen. Dafür kann eine Bearbeitungsgebühr von 35,00 € berechnet werden. Rücktrittsgebühren werden dann nicht erhoben.</p>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('bookings:resend-confirmations')]
|
||||
#[Description('Retry booking confirmations whose mail failed (last three days) – once per landlord')]
|
||||
class ResendBookingConfirmations extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ConfirmBooking $confirmBooking, TenantRunner $runner): int
|
||||
{
|
||||
$runner->each(function (Tenant $tenant) use ($confirmBooking): void {
|
||||
$sent = 0;
|
||||
$failed = Booking::query()
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->whereNotNull('confirmation_failed_at')
|
||||
->where('confirmation_failed_at', '>=', now()->subDays(3))
|
||||
->whereNull('confirmation_sent_at')
|
||||
->get();
|
||||
|
||||
foreach ($failed as $booking) {
|
||||
$sent += $confirmBooking->resend($booking) ? 1 : 0;
|
||||
}
|
||||
|
||||
$this->info("{$tenant->name}: {$sent} von {$failed->count()} Bestätigung(en) nachgesendet.");
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\AutoOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\OfferMode;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Throwable;
|
||||
|
||||
#[Signature('bookings:auto-offers')]
|
||||
#[Description('Retry automatic offers of pending requests (e.g. once an instant-booking portal has fetched our calendar) – once per landlord')]
|
||||
class SendPendingAutoOffers extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(AutoOffer $autoOffer, TenantRunner $runner): int
|
||||
{
|
||||
$runner->each(function (Tenant $tenant) use ($autoOffer): void {
|
||||
$pending = Booking::query()
|
||||
->where('status', BookingStatus::Reserved)
|
||||
->where('offer_version', 0)
|
||||
->where('hold_expires_at', '>', now())
|
||||
->whereHas('property', fn ($query) => $query->where('offer_mode', OfferMode::Automatic)->where('pre_reservation_enabled', true))
|
||||
->with(['property', 'guest'])
|
||||
->get();
|
||||
|
||||
$sent = 0;
|
||||
foreach ($pending as $booking) {
|
||||
try {
|
||||
$sent += $autoOffer->handle($booking) === [] ? 1 : 0;
|
||||
} catch (Throwable) {
|
||||
// The request stays pending for the landlord; the next run tries again.
|
||||
}
|
||||
}
|
||||
|
||||
$this->info("{$tenant->name}: {$sent} von {$pending->count()} Angebot(e) automatisch versendet.");
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -4,18 +4,27 @@
|
||||
|
||||
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')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts – once per landlord')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console 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): int
|
||||
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))
|
||||
@@ -29,7 +38,5 @@ public function handle(SyncChannel $syncChannel): int
|
||||
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
|
||||
: $this->error("✗ {$channel->name}: {$log->message}");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
<?php
|
||||
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\CancellationPolicy;
|
||||
use App\Support\Money;
|
||||
|
||||
/**
|
||||
* Placeholders of contract documents, written as {{ name }} in the template text. Values are taken from the
|
||||
* booking and the facts of the property ({{ wohnung.wlan_passwort }}); they are HTML-escaped. A placeholder that
|
||||
* cannot be filled stays visible as [name?] so that it is never silently missing in a contract.
|
||||
*/
|
||||
class ContractPlaceholders
|
||||
{
|
||||
/** Placeholders whose value is already safe HTML. */
|
||||
private const RAW = ['storno_regel'];
|
||||
|
||||
private const PATTERN = '/\{\{\s*([a-z][a-z0-9_]*(?:\.[a-z0-9_]+)?)\s*\}\}/i';
|
||||
|
||||
/**
|
||||
* Placeholders with their meaning, for the template editor.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public static function catalog(): array
|
||||
{
|
||||
return [
|
||||
'mieter' => 'Name des Gastes',
|
||||
'mieter_anschrift' => 'Anschrift des Gastes',
|
||||
'mieter_email' => 'E-Mail des Gastes',
|
||||
'anreise' => 'Anreisetag mit Wochentag, z. B. Samstag, 07.11.2026',
|
||||
'abreise' => 'Abreisetag mit Wochentag',
|
||||
'anreise_datum' => 'Anreisedatum, z. B. 07.11.2026',
|
||||
'abreise_datum' => 'Abreisedatum',
|
||||
'naechte' => 'Anzahl der Nächte',
|
||||
'personen' => 'Anzahl der Personen',
|
||||
'gesamtpreis' => 'Gesamtpreis, z. B. 1.234,00 €',
|
||||
'anzahlung' => 'Anzahlung',
|
||||
'restzahlung' => 'Restzahlung',
|
||||
'restzahlung_faellig' => 'Fälligkeit der Restzahlung',
|
||||
'buchungsnummer' => 'Buchungs-/Angebotsnummer',
|
||||
'datum' => 'Datum des Vertrags',
|
||||
'vermieter' => 'Name des Vermieters',
|
||||
'vermieter_anschrift' => 'Anschrift des Vermieters',
|
||||
'wohnung' => 'Name der Wohnung',
|
||||
'wohnung_adresse' => 'Adresse der Wohnung',
|
||||
'checkin' => 'Anreisezeit (Uhr)',
|
||||
'checkout' => 'Abreisezeit (Uhr)',
|
||||
'portal' => 'Name des Portals (leer bei eigener Buchung)',
|
||||
'storno_regel' => 'Die Stornoregel dieser Vorlage als Aufzählung (Stufen und Prozent)',
|
||||
'wohnung.<name>' => 'Eigene Wohnungsdaten (Wohnung bearbeiten › Vertragsdaten), z. B. wohnung.wlan_passwort',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $propertyData facts of the property as frozen in the offer
|
||||
*/
|
||||
public static function render(string $html, Booking $booking, array $propertyData = []): string
|
||||
{
|
||||
$values = self::values($booking, $propertyData);
|
||||
|
||||
return (string) preg_replace_callback(self::PATTERN, function (array $match) use ($values): string {
|
||||
$key = strtolower($match[1]);
|
||||
|
||||
if (! array_key_exists($key, $values) || $values[$key] === null) {
|
||||
return '[<b>'.e($key).'?</b>]';
|
||||
}
|
||||
|
||||
return in_array($key, self::RAW, true) ? (string) $values[$key] : e((string) $values[$key]);
|
||||
}, $html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholders in the text that have no value for this booking.
|
||||
*
|
||||
* @param array<string, mixed> $propertyData
|
||||
* @return list<string>
|
||||
*/
|
||||
public static function missing(string $html, Booking $booking, array $propertyData = []): array
|
||||
{
|
||||
$values = self::values($booking, $propertyData);
|
||||
preg_match_all(self::PATTERN, $html, $found);
|
||||
|
||||
return array_values(array_unique(array_filter(array_map('strtolower', $found[1]), fn (string $key): bool => ! isset($values[$key]))));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $propertyData
|
||||
* @return array<string, ?string>
|
||||
*/
|
||||
private static function values(Booking $booking, array $propertyData): array
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property', 'importChannel', 'originChannel']);
|
||||
$guest = $booking->guest;
|
||||
$owner = OfferTerms::owner($booking);
|
||||
$property = $booking->property;
|
||||
$address = trim(implode(', ', array_filter([$guest?->street, trim(($guest?->postal_code ?? '').' '.($guest?->city ?? ''))])));
|
||||
|
||||
$values = [
|
||||
'mieter' => $guest?->full_name,
|
||||
'mieter_anschrift' => $address ?: null,
|
||||
'mieter_email' => $guest?->email,
|
||||
'anreise' => $booking->arrival->translatedFormat('l, d.m.Y'),
|
||||
'abreise' => $booking->departure->translatedFormat('l, d.m.Y'),
|
||||
'anreise_datum' => $booking->arrival->format('d.m.Y'),
|
||||
'abreise_datum' => $booking->departure->format('d.m.Y'),
|
||||
'naechte' => (string) $booking->nights(),
|
||||
'personen' => (string) $booking->guests,
|
||||
'gesamtpreis' => Money::format($booking->total),
|
||||
'anzahlung' => Money::format($booking->deposit),
|
||||
'restzahlung' => Money::format($booking->total - $booking->deposit),
|
||||
'restzahlung_faellig' => $booking->balance_due_on?->format('d.m.Y'),
|
||||
'buchungsnummer' => $booking->reference,
|
||||
'datum' => ($booking->confirmed_at ?? $booking->offer_sent_at ?? now())->format('d.m.Y'),
|
||||
'vermieter' => $owner['name'] ?? null,
|
||||
'vermieter_anschrift' => trim(($owner['street'] ?? '').', '.($owner['city'] ?? ''), ', ') ?: null,
|
||||
'wohnung' => $property->name,
|
||||
'wohnung_adresse' => $property->address,
|
||||
'checkin' => $property->check_in_time ? substr((string) $property->check_in_time, 0, 5) : null,
|
||||
'checkout' => $property->check_out_time ? substr((string) $property->check_out_time, 0, 5) : null,
|
||||
'portal' => ($booking->importChannel ?? $booking->originChannel)?->name ?? '',
|
||||
];
|
||||
|
||||
$policy = $booking->offer_terms['cancellation_policy'] ?? null;
|
||||
if (is_array($policy) && ! empty($policy['tiers'])) {
|
||||
$values['storno_regel'] = '<ul>'.collect(CancellationPolicy::describe($policy))->map(fn (string $line): string => '<li>'.e($line).'</li>')->implode('').'</ul>';
|
||||
}
|
||||
|
||||
foreach ($propertyData as $name => $value) {
|
||||
$values['wohnung.'.strtolower((string) $name)] = is_scalar($value) ? (string) $value : null;
|
||||
}
|
||||
|
||||
return $values;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
<?php
|
||||
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Enums\ChannelBookingModel;
|
||||
use App\Models\Booking;
|
||||
use App\Models\ContractAnnex;
|
||||
use App\Models\ContractTemplate;
|
||||
use App\Support\Content;
|
||||
use Filament\Forms\Components\RichEditor\RichContentRenderer;
|
||||
use Illuminate\Support\HtmlString;
|
||||
|
||||
/**
|
||||
* The terms of one offer version, frozen when the offer is made (bookings.offer_terms): contract texts,
|
||||
* payment period and landlord/bank data. Offer page, PDFs, acceptance and confirmation read from this snapshot,
|
||||
* so later changes of the website texts never alter an offer the guest already received.
|
||||
* Bookings without a snapshot (created before it existed) fall back to the live texts.
|
||||
*/
|
||||
class OfferTerms
|
||||
{
|
||||
/** Website text keys that form part of the contract. */
|
||||
public const TEXT_KEYS = [
|
||||
'contract.intro',
|
||||
'contract.terms',
|
||||
'contract.closing',
|
||||
'stay.cancellation',
|
||||
'stay.house_rules',
|
||||
'offer.contract_note',
|
||||
'offer.accept_note',
|
||||
'offer.accept_button',
|
||||
];
|
||||
|
||||
/**
|
||||
* @return array{captured_at: string, template: ?array{id: int, name: string, version: int}, texts: array<string, ?string>, deposit_due_days: int, owner: array<string, mixed>, bank: array<string, mixed>}
|
||||
*/
|
||||
public static function capture(?ContractTemplate $template = null, ?Booking $booking = null, ?array $annexIds = null): array
|
||||
{
|
||||
$overrides = $template?->overrides() ?? [];
|
||||
$annexes = $annexIds !== null
|
||||
? ContractAnnex::query()->whereIn('id', $annexIds)->orderBy('name')->get()
|
||||
: ($template !== null && $booking !== null ? $template->annexesFor($booking) : collect());
|
||||
|
||||
return [
|
||||
'captured_at' => now()->toIso8601String(),
|
||||
'template' => $template ? ['id' => $template->id, 'name' => $template->name, 'version' => $template->version] : null,
|
||||
'document' => $template?->hasDocument() ? ['body' => $template->body, 'annex_title' => $template->annex_title, 'annex_body' => $template->annex_body] : null,
|
||||
'annex_ids' => $annexes->pluck('id')->all(),
|
||||
'annexes' => $annexes->map(fn (ContractAnnex $annex): array => ['id' => $annex->id, 'name' => $annex->name, 'version' => $annex->version, 'title' => $annex->title, 'body' => $annex->body])->values()->all(),
|
||||
'cancellation_policy' => $template?->cancellationPolicy?->snapshot(),
|
||||
'property_data' => (array) ($booking?->property?->contract_data ?? []),
|
||||
'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => $overrides[$key] ?? Content::get($key)])->all(),
|
||||
'deposit_due_days' => (int) config('fewo.deposit_due_days'),
|
||||
'owner' => (array) config('fewo.owner'),
|
||||
'bank' => (array) config('fewo.bank'),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The contract template for a booking: chosen explicitly, else the portal's (for bookings that are binding at the
|
||||
* portal its reservation template, otherwise its offer template), else the property's.
|
||||
*/
|
||||
public static function templateFor(Booking $booking, int|string|null $explicitId = null): ?ContractTemplate
|
||||
{
|
||||
$channel = $booking->importChannel ?? $booking->originChannel;
|
||||
$portalId = $channel === null ? null : ($channel->booking_model === ChannelBookingModel::PortalBooking
|
||||
? ($channel->contract_template_reservation_id ?? $channel->contract_template_id)
|
||||
: $channel->contract_template_id);
|
||||
$id = filled($explicitId) ? (int) $explicitId : ($portalId ?? $booking->property->contract_template_id);
|
||||
|
||||
return $id ? ContractTemplate::query()->find($id) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The contract as a complete document (placeholders filled), or null when the offer uses the text blocks.
|
||||
*
|
||||
* @return array{body: string, annex_title: ?string, annex: ?string}|null
|
||||
*/
|
||||
public static function document(Booking $booking): ?array
|
||||
{
|
||||
$document = $booking->offer_terms['document'] ?? null;
|
||||
if (! is_array($document) || blank($document['body'] ?? null)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$data = (array) ($booking->offer_terms['property_data'] ?? []);
|
||||
$render = fn (?string $html): ?string => filled($html) ? (string) RichContentRenderer::make(ContractPlaceholders::render($html, $booking, $data))->toHtml() : null;
|
||||
|
||||
return ['body' => (string) $render($document['body']), 'annex_title' => $document['annex_title'] ?? null, 'annex' => $render($document['annex_body'] ?? null)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The annexes frozen in the offer, with placeholders filled.
|
||||
*
|
||||
* @return list<array{title: string, name: string, version: int, html: string}>
|
||||
*/
|
||||
public static function annexes(Booking $booking): array
|
||||
{
|
||||
$data = (array) ($booking->offer_terms['property_data'] ?? []);
|
||||
|
||||
return collect((array) ($booking->offer_terms['annexes'] ?? []))->map(fn (array $annex): array => [
|
||||
'title' => (string) $annex['title'],
|
||||
'name' => (string) $annex['name'],
|
||||
'version' => (int) $annex['version'],
|
||||
'html' => (string) RichContentRenderer::make(ContractPlaceholders::render((string) $annex['body'], $booking, $data))->toHtml(),
|
||||
])->values()->all();
|
||||
}
|
||||
|
||||
public static function text(Booking $booking, string $key): ?string
|
||||
{
|
||||
$texts = $booking->offer_terms['texts'] ?? null;
|
||||
|
||||
return is_array($texts) ? ($texts[$key] ?? null) : Content::get($key);
|
||||
}
|
||||
|
||||
public static function html(Booking $booking, string $key): HtmlString
|
||||
{
|
||||
$value = self::text($booking, $key);
|
||||
|
||||
return new HtmlString(filled($value) ? RichContentRenderer::make($value)->toHtml() : '');
|
||||
}
|
||||
|
||||
public static function depositDueDays(Booking $booking): int
|
||||
{
|
||||
return (int) ($booking->offer_terms['deposit_due_days'] ?? config('fewo.deposit_due_days'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function owner(Booking $booking): array
|
||||
{
|
||||
return $booking->offer_terms['owner'] ?? (array) config('fewo.owner');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
public static function bank(Booking $booking): array
|
||||
{
|
||||
return $booking->offer_terms['bank'] ?? (array) config('fewo.bank');
|
||||
}
|
||||
|
||||
/**
|
||||
* Fingerprint of everything the guest agrees to in this offer version. The validity (hold_expires_at) is
|
||||
* not part of it – the landlord may extend it – but is checked separately.
|
||||
*/
|
||||
public static function hash(Booking $booking): string
|
||||
{
|
||||
return hash('sha256', json_encode(self::canonical([
|
||||
'version' => $booking->offer_version,
|
||||
'arrival' => $booking->arrival->toDateString(),
|
||||
'departure' => $booking->departure->toDateString(),
|
||||
'guests' => $booking->guests,
|
||||
'quote' => $booking->quote,
|
||||
'total' => $booking->total,
|
||||
'deposit' => $booking->deposit,
|
||||
'balance_due_on' => $booking->balance_due_on->toDateString(),
|
||||
'terms' => $booking->offer_terms,
|
||||
]), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
||||
}
|
||||
|
||||
private static function canonical(mixed $value): mixed
|
||||
{
|
||||
if (! is_array($value)) {
|
||||
return $value;
|
||||
}
|
||||
|
||||
$value = array_map(self::canonical(...), $value);
|
||||
if (! array_is_list($value)) {
|
||||
ksort($value);
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Site;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
@@ -18,12 +19,29 @@ class RentalContract
|
||||
public function generate(Booking $booking, bool $draft = false): string
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$path = $draft
|
||||
$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);
|
||||
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking, 'draft' => $draft])->setPaper('a4')->output());
|
||||
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
|
||||
// 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);
|
||||
|
||||
// The final contract is a document of record: once stored it is never rewritten (confirmation resends reuse it).
|
||||
if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) {
|
||||
return $booking->contract_path;
|
||||
}
|
||||
|
||||
$document = OfferTerms::document($booking);
|
||||
$pdf = Pdf::loadView($document !== null ? 'pdf.contract-document' : 'pdf.contract', [
|
||||
'booking' => $booking,
|
||||
'draft' => $draft,
|
||||
'logo' => $logo,
|
||||
'document' => $document,
|
||||
])->setPaper('a4')->output();
|
||||
Storage::disk(self::DISK)->put($path, $pdf);
|
||||
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
+11
-9
@@ -2,13 +2,14 @@
|
||||
|
||||
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\BookingTasks\BookingTaskResource;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Filament\Resources\Guests\GuestResource;
|
||||
use App\Filament\Resources\Photos\PhotoResource;
|
||||
use App\Filament\Resources\Reviews\ReviewResource;
|
||||
use App\Filament\Resources\InboxMessages\InboxMessageResource;
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
@@ -21,18 +22,19 @@ enum AdminMode: string implements HasDescription, HasLabel
|
||||
case Expert = 'expert';
|
||||
|
||||
/**
|
||||
* Menu entries of the simple mode: day-to-day work with requests, bookings, contracts and the calendar.
|
||||
* Menu entries of the simple mode: the few things needed every day: calendar, bookings with their file, tasks, mailbox, guests and prices.
|
||||
*
|
||||
* @var list<class-string>
|
||||
*/
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
OccupancyCalendar::class,
|
||||
BookingResource::class,
|
||||
BookingTaskResource::class,
|
||||
ChannelTaskResource::class,
|
||||
InboxMessageResource::class,
|
||||
GuestResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
|
||||
public function getLabel(): string
|
||||
@@ -46,8 +48,8 @@ public function getLabel(): string
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Portal-Aufgaben, Bewertungen, Fotos',
|
||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Portale, Webseite, System',
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Mail\PaymentReminder;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What the landlord has to do about a booking. Payment tasks are created by the daily run; nothing is
|
||||
* sent to the guest until the landlord has checked the payment and chooses to send the mail.
|
||||
*/
|
||||
enum BookingTaskKind: string implements HasLabel
|
||||
{
|
||||
case DepositReminder = 'deposit_reminder';
|
||||
case BalanceRequest = 'balance_request';
|
||||
case BalanceReminder = 'balance_reminder';
|
||||
case CancellationRequest = 'cancellation_request';
|
||||
case CancellationFee = 'cancellation_fee';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::DepositReminder => 'Anzahlung überfällig – anmahnen',
|
||||
self::BalanceRequest => 'Restzahlung bald fällig – anfordern',
|
||||
self::BalanceReminder => 'Restzahlung überfällig – anmahnen',
|
||||
self::CancellationRequest => 'Stornierungswunsch des Gastes',
|
||||
self::CancellationFee => 'Stornokosten prüfen und abrechnen',
|
||||
};
|
||||
}
|
||||
|
||||
public function isPayment(): bool
|
||||
{
|
||||
return ! in_array($this, [self::CancellationRequest, self::CancellationFee], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* The mail kind (App\Mail\PaymentReminder) and the booking column that records its dispatch.
|
||||
*
|
||||
* @return array{0: string, 1: string}|null
|
||||
*/
|
||||
public function reminder(): ?array
|
||||
{
|
||||
return match ($this) {
|
||||
self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'],
|
||||
self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'],
|
||||
self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'],
|
||||
self::CancellationRequest, self::CancellationFee => null,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum BookingTaskStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
case Open = 'open';
|
||||
case Done = 'done';
|
||||
case Dismissed = 'dismissed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'Offen',
|
||||
self::Done => 'Erledigt',
|
||||
self::Dismissed => 'Verworfen',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'warning',
|
||||
self::Done => 'success',
|
||||
self::Dismissed => 'gray',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What the cancellation link in the booking confirmation does.
|
||||
*/
|
||||
enum CancellationMode: string implements HasLabel
|
||||
{
|
||||
/** The guest sends a request; the landlord decides and settles costs. */
|
||||
case Request = 'request';
|
||||
|
||||
/** The booking is cancelled at once and the dates are released. */
|
||||
case Instant = 'instant';
|
||||
|
||||
/** Cancelled at once while the stay is still far enough away (free cancellation), otherwise a request. */
|
||||
case InstantWhenFree = 'instant_when_free';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Request => 'Nur Stornierungswunsch – ich entscheide',
|
||||
self::Instant => 'Sofort stornieren (Ein-Klick)',
|
||||
self::InstantWhenFree => 'Sofort stornieren bis zur Frist der kostenfreien Stornierung, danach Wunsch',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* The parts of the daily/weekly summary a landlord can choose (System › Betrieb › Benachrichtigungen).
|
||||
*/
|
||||
enum DigestSection: string implements HasDescription, HasLabel
|
||||
{
|
||||
case Inbox = 'inbox';
|
||||
case Requests = 'requests';
|
||||
case News = 'news';
|
||||
case Stays = 'stays';
|
||||
case Payments = 'payments';
|
||||
case Portals = 'portals';
|
||||
case Reviews = 'reviews';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inbox => 'Postfach',
|
||||
self::Requests => 'Offene Anfragen und Angebote',
|
||||
self::News => 'Neu seit der letzten Übersicht',
|
||||
self::Stays => 'An- und Abreisen',
|
||||
self::Payments => 'Zahlungsaufgaben und Gästewünsche',
|
||||
self::Portals => 'Portale: Aufgaben und Klärungsfälle',
|
||||
self::Reviews => 'Bewertungen zur Freigabe',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inbox => 'Ungelesene Meldungen, z. B. mögliche Doppelbuchungen',
|
||||
self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist',
|
||||
self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen',
|
||||
self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage',
|
||||
self::Payments => 'Offene Aufgaben: fällige Zahlungen (nur wo Sie selbst mahnen) und Stornierungswünsche',
|
||||
self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler',
|
||||
self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string>|null $values stored choice; null = everything
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function chosen(?array $values): array
|
||||
{
|
||||
return $values === null ? self::cases() : array_values(array_filter(self::cases(), fn (self $section): bool => in_array($section->value, $values, true)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* What an inbox message is about.
|
||||
*/
|
||||
enum InboxMessageKind: string implements HasColor, HasLabel
|
||||
{
|
||||
case ChannelConflict = 'channel_conflict';
|
||||
case ConfirmationFailed = 'confirmation_failed';
|
||||
case OfferMailFailed = 'offer_mail_failed';
|
||||
case OfferRejected = 'offer_rejected';
|
||||
case SyncFailed = 'sync_failed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::ChannelConflict => 'Mögliche Doppelbuchung',
|
||||
self::ConfirmationFailed => 'Buchungsbestätigung nicht zugestellt',
|
||||
self::OfferMailFailed => 'Angebot nicht zugestellt',
|
||||
self::OfferRejected => 'Annahme abgewiesen',
|
||||
self::SyncFailed => 'Kalenderabgleich gestört',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::ChannelConflict, self::SyncFailed => 'danger',
|
||||
self::ConfirmationFailed, self::OfferMailFailed, self::OfferRejected => 'warning',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How requests for a property are turned into offers.
|
||||
*/
|
||||
enum OfferMode: string implements HasLabel
|
||||
{
|
||||
/** The landlord reviews every request and sends the offer. */
|
||||
case Manual = 'manual';
|
||||
|
||||
/** The offer is sent automatically when all release rules are met; otherwise the request waits for the landlord. */
|
||||
case Automatic = 'automatic';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Manual => 'Manuell – ich prüfe jede Anfrage und sende das Angebot',
|
||||
self::Automatic => 'Automatisch – Angebot sofort, wenn alle Prüfungen bestanden sind',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,16 @@ public static function offerOutdated(): self
|
||||
return new self('Zu dieser Anfrage gibt es inzwischen ein aktualisiertes Angebot. Bitte verwenden Sie den Link aus unserer neuesten E-Mail.');
|
||||
}
|
||||
|
||||
public static function offerChanged(): self
|
||||
{
|
||||
return new self('Dieses Angebot kann nicht angenommen werden, weil sich seine Angaben geändert haben. Bitte melden Sie sich bei uns – gern erstellen wir Ihnen ein neues Angebot.');
|
||||
}
|
||||
|
||||
public static function calendarUnverified(): self
|
||||
{
|
||||
return new self('Wir können die Verfügbarkeit gerade nicht sicher bestätigen, daher wurde Ihre Annahme noch nicht gespeichert. Bitte versuchen Sie es in einigen Minuten noch einmal oder rufen Sie uns an – wir kümmern uns darum.');
|
||||
}
|
||||
|
||||
public static function invalidTransition(string $statusLabel, string $action): self
|
||||
{
|
||||
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
|
||||
|
||||
@@ -0,0 +1,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();
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\Relation;
|
||||
|
||||
/**
|
||||
* Limits a resource list to the apartment chosen in the admin menu (CurrentProperty).
|
||||
* Records stay reachable by URL; opening one switches to its apartment (SelectsRecordProperty).
|
||||
*/
|
||||
trait ListsCurrentProperty
|
||||
{
|
||||
protected function getTableQuery(): Builder|Relation|null
|
||||
{
|
||||
$query = parent::getTableQuery();
|
||||
$property = app(CurrentProperty::class)->get();
|
||||
|
||||
return $query instanceof Builder && $property !== null ? $this->scopeToProperty($query, $property) : $query;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Builder<Model> $query
|
||||
* @return Builder<Model>
|
||||
*/
|
||||
protected function scopeToProperty(Builder $query, Property $property): Builder
|
||||
{
|
||||
return $query->where($query->qualifyColumn('property_id'), $property->id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Models\Property;
|
||||
use App\Support\CurrentProperty;
|
||||
use Closure;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* Opening a record of another apartment (e.g. from a notification e-mail) switches the admin to that apartment,
|
||||
* so the menu always shows the apartment the open record belongs to.
|
||||
*/
|
||||
trait SelectsRecordProperty
|
||||
{
|
||||
public static function resolveRecordRouteBinding(int|string $key, ?Closure $modifyQuery = null): ?Model
|
||||
{
|
||||
$record = parent::resolveRecordRouteBinding($key, $modifyQuery);
|
||||
$propertyId = $record !== null ? static::recordPropertyId($record) : null;
|
||||
|
||||
if ($propertyId !== null && $propertyId !== app(CurrentProperty::class)->id() && ($property = Property::query()->find($propertyId))) {
|
||||
app(CurrentProperty::class)->select($property);
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
public static function recordPropertyId(Model $record): ?int
|
||||
{
|
||||
$id = $record->getAttribute('property_id');
|
||||
|
||||
return $id !== null ? (int) $id : null;
|
||||
}
|
||||
}
|
||||
@@ -40,7 +40,8 @@ public static function optionLabel(Photo $photo): string
|
||||
? '<img src="'.e($thumbnail).'" alt="" loading="lazy" style="width:4.5rem;height:3rem;object-fit:cover;border-radius:.25rem;flex-shrink:0">'
|
||||
: '<span style="width:4.5rem;height:3rem;border-radius:.25rem;background:#e5e7eb;flex-shrink:0"></span>';
|
||||
$hidden = $photo->is_published ? '' : ' <em style="opacity:.6">(ausgeblendet)</em>';
|
||||
$seasons = $photo->appearanceNames() === [] ? '' : ' <em style="opacity:.75">· nur '.e(implode(', ', $photo->appearanceNames())).'</em>';
|
||||
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$hidden.'</span></span>';
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$seasons.$hidden.'</span></span>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
|
||||
/**
|
||||
* The service switches of the tenant form. They live in their own table, so the form state is read and
|
||||
* written separately from the landlord's own columns. Only wired services are written – a switch for a
|
||||
* service nothing asks about would promise something that does not happen.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantServices
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillServices(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data; // creating: there is nothing to read yet
|
||||
}
|
||||
|
||||
$stored = $tenant->services->keyBy('service');
|
||||
|
||||
$data['services'] = collect(TenantServiceKey::wired())
|
||||
->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [
|
||||
'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(),
|
||||
]])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeServices(array $data): array
|
||||
{
|
||||
$this->services = is_array($data['services'] ?? null) ? $data['services'] : [];
|
||||
|
||||
unset($data['services']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function saveServices(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (TenantServiceKey::wired() as $service) {
|
||||
$state = $this->services[$service->value] ?? [];
|
||||
|
||||
$tenant->services()->updateOrCreate(
|
||||
['service' => $service->value],
|
||||
['is_enabled' => (bool) ($state['is_enabled'] ?? false)],
|
||||
);
|
||||
}
|
||||
|
||||
$tenant->unsetRelation('services');
|
||||
app(TenantFeatures::class)->forget($tenant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
/**
|
||||
* Everything the operator sets up for a landlord that does not live in the tenants table itself:
|
||||
* the websites with their entry addresses, and the services that are unlocked.
|
||||
*/
|
||||
trait EditsTenantSetup
|
||||
{
|
||||
use EditsTenantServices;
|
||||
use EditsTenantWebsites;
|
||||
|
||||
/** @var array<string, array<string, mixed>> */
|
||||
public array $services = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $websites = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return $this->fillWebsites($this->fillServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SiteDomain;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* The websites of a landlord and the addresses they answer on. These belong to the operator: the webspace
|
||||
* and the hosting are the operator's, and a landlord must not be able to point an address at themselves.
|
||||
*
|
||||
* Wiring a new domain to this directory stays a manual step at the hoster. What is kept here is the other
|
||||
* half: which host belongs to which website, and through it to which landlord.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantWebsites
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillWebsites(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get()
|
||||
->map(fn (Site $site): array => [
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => $site->domains->pluck('host')->all(),
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeWebsites(array $data): array
|
||||
{
|
||||
$this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : [];
|
||||
|
||||
$this->normaliseWebsites();
|
||||
|
||||
unset($data['websites']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written.
|
||||
*/
|
||||
private function normaliseWebsites(): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach ($this->websites as $index => $website) {
|
||||
$hosts = [];
|
||||
|
||||
foreach ((array) ($website['hosts'] ?? []) as $host) {
|
||||
$host = SiteDomain::normalise(is_string($host) ? $host : null);
|
||||
|
||||
if ($host === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($host, $seen, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.',
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[] = $host;
|
||||
$hosts[] = $host;
|
||||
}
|
||||
|
||||
$this->websites[$index]['hosts'] = $hosts;
|
||||
}
|
||||
|
||||
$this->refuseForeignHosts($seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function refuseForeignHosts(array $hosts): void
|
||||
{
|
||||
$ownIds = collect($this->websites)->pluck('id')->filter()->all();
|
||||
|
||||
$taken = SiteDomain::query()
|
||||
->whereIn('host', $hosts)
|
||||
->whereNotIn('site_id', $ownIds ?: [0])
|
||||
->pluck('host');
|
||||
|
||||
if ($taken->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the websites. A website that is new gets an empty home page straight away, because a website
|
||||
* without one answers 404 and the landlord would have no way in.
|
||||
*/
|
||||
private function saveWebsites(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($tenant, function () use ($tenant): void {
|
||||
$keep = [];
|
||||
|
||||
foreach ($this->websites as $website) {
|
||||
$name = trim((string) ($website['name'] ?? ''));
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts = (array) ($website['hosts'] ?? []);
|
||||
$site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts);
|
||||
|
||||
$keep[] = $site->id;
|
||||
|
||||
$site->domains()->whereNotIn('host', $hosts ?: [''])->delete();
|
||||
|
||||
foreach ($hosts as $host) {
|
||||
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site
|
||||
{
|
||||
$site = $id ? Site::query()->whereKey($id)->first() : null;
|
||||
|
||||
if ($site !== null) {
|
||||
$site->update(['name' => $name, 'domain' => $hosts[0] ?? null]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
|
||||
$site = Site::query()->create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $name,
|
||||
'domain' => $hosts[0] ?? null,
|
||||
'is_default' => $tenant->sites()->count() === 0,
|
||||
'theme' => config('themes.base'),
|
||||
]);
|
||||
|
||||
Page::query()->create([
|
||||
'site_id' => $site->id,
|
||||
'slug' => Page::HOME,
|
||||
'title' => $name,
|
||||
'sections' => [],
|
||||
'is_published' => true,
|
||||
]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use BackedEnum;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* What applies to the whole installation: the limits every landlord is bound by, the delivery path, and
|
||||
* who opened whose admin. These values come from the server's .env and are deliberately not editable here –
|
||||
* they protect the system against the landlords, so a landlord's admin must not be able to reach them.
|
||||
*/
|
||||
class SystemOverview extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedServerStack;
|
||||
|
||||
protected static ?string $navigationLabel = 'System';
|
||||
|
||||
protected static ?string $title = 'System';
|
||||
|
||||
protected static ?string $slug = 'system';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected string $view = 'filament.operator.system-overview';
|
||||
|
||||
/**
|
||||
* The ceilings a landlord may tighten but never exceed.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function limits(): array
|
||||
{
|
||||
$config = app(TenantConfig::class);
|
||||
|
||||
$rows = [
|
||||
['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'],
|
||||
['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''],
|
||||
['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''],
|
||||
['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''],
|
||||
['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'],
|
||||
['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''],
|
||||
['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''],
|
||||
['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''],
|
||||
['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''],
|
||||
];
|
||||
|
||||
return array_map(fn (array $row): array => [
|
||||
'label' => $row[0],
|
||||
'value' => trim($config->baselineValue($row[1]).' '.$row[2]),
|
||||
'note' => $row[3],
|
||||
], $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Values that belong to the whole installation and to no landlord.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function global(): array
|
||||
{
|
||||
$redirect = config('fewo.mail_redirect_to');
|
||||
|
||||
return [
|
||||
[
|
||||
'label' => 'Anfragen aller Websites zusammen',
|
||||
'value' => config('fewo.spam.total_per_hour').' je Stunde',
|
||||
'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.',
|
||||
],
|
||||
[
|
||||
'label' => 'Harte Mail-Umleitung',
|
||||
'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt',
|
||||
'note' => filled($redirect)
|
||||
? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.'
|
||||
: 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.',
|
||||
],
|
||||
[
|
||||
'label' => 'Versandweg',
|
||||
'value' => (string) config('mail.default'),
|
||||
'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.',
|
||||
],
|
||||
[
|
||||
'label' => 'Datenbank-Sicherungen',
|
||||
'value' => config('fewo.backup.keep').' Stück',
|
||||
'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Tenant>
|
||||
*/
|
||||
public function tenants(): Collection
|
||||
{
|
||||
return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get();
|
||||
}
|
||||
|
||||
public function wiredServiceCount(): int
|
||||
{
|
||||
return count(TenantServiceKey::wired());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, TenantAccessLog>
|
||||
*/
|
||||
public function accessLog(): Collection
|
||||
{
|
||||
return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Support\SystemSettings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
/**
|
||||
* The settings of the whole installation. They are the baseline every landlord is bound by, and a
|
||||
* landlord's admin never reaches this page.
|
||||
*
|
||||
* Empty means: the value from the server's .env applies again. Database credentials and APP_KEY are not
|
||||
* here and cannot be – they are needed to open the database and to decrypt what is stored in it.
|
||||
*/
|
||||
class SystemSettingsPage extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
|
||||
|
||||
protected static ?string $navigationLabel = 'Einstellungen';
|
||||
|
||||
protected static ?string $title = 'Systemweite Einstellungen';
|
||||
|
||||
protected static ?string $slug = 'einstellungen';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$sections = collect(SystemSettings::EDITABLE)
|
||||
->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true)
|
||||
->map(fn ($group, string $section) => Section::make($section)
|
||||
->columns(2)
|
||||
->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all()));
|
||||
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'),
|
||||
...$sections->values()->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Form::make([EmbeddedSchema::make('form')])
|
||||
->id('form')
|
||||
->livewireSubmitHandler('save')
|
||||
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
SystemSettings::save(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null])
|
||||
->all());
|
||||
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Config keys contain dots, which Filament would read as nesting.
|
||||
*/
|
||||
private static function field(string $key): string
|
||||
{
|
||||
return str_replace('.', '__', $key);
|
||||
}
|
||||
|
||||
private function field_(string $key): TextInput|Select
|
||||
{
|
||||
[$label, $kind, , $help] = SystemSettings::EDITABLE[$key];
|
||||
$name = self::field($key);
|
||||
|
||||
if ($kind === 'mailer') {
|
||||
return Select::make($name)
|
||||
->label($label)
|
||||
->helperText($help)
|
||||
->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']);
|
||||
}
|
||||
|
||||
$field = TextInput::make($name)->label($label)->helperText($help);
|
||||
|
||||
return match ($kind) {
|
||||
'int' => $field->numeric()->integer()->minValue(0),
|
||||
'secret' => $field->password()->revealable()->autocomplete(false),
|
||||
default => $field,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Operator;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\ListTenants;
|
||||
@@ -10,14 +11,21 @@
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class TenantResource extends Resource
|
||||
{
|
||||
@@ -48,9 +56,50 @@ public static function form(Schema $schema): Schema
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(255),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv')
|
||||
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
|
||||
->default(true),
|
||||
->label('Zugang freigeschaltet')
|
||||
->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.')
|
||||
->default(true)
|
||||
->live(),
|
||||
Textarea::make('suspended_message')
|
||||
->label('Hinweis bei gesperrtem Zugang')
|
||||
->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.')
|
||||
->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.')
|
||||
->rows(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Einsprungsadressen')
|
||||
->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
Repeater::make('websites')
|
||||
->label('Websites')
|
||||
->addActionLabel('Weitere Website')
|
||||
->defaultItems(1)
|
||||
->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
TextInput::make('name')
|
||||
->label('Name der Website')
|
||||
->required()
|
||||
->maxLength(120),
|
||||
TagsInput::make('hosts')
|
||||
->label('Adressen')
|
||||
->placeholder('beispiel.de')
|
||||
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.')
|
||||
->nestedRecursiveRules(['string', 'max:190']),
|
||||
]),
|
||||
]),
|
||||
Section::make('Dienste')
|
||||
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled')
|
||||
->label($service->label())
|
||||
->helperText($service->description()), TenantServiceKey::wired()),
|
||||
Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map(
|
||||
fn (TenantServiceKey $service): string => $service->label(),
|
||||
array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())),
|
||||
)).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -60,6 +109,10 @@ public static function table(Table $table): Table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kurzname'),
|
||||
TextColumn::make('services_count')
|
||||
->label('Dienste frei')
|
||||
->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)])
|
||||
->suffix(' von '.count(TenantServiceKey::wired())),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
Loaded 100 of 522 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user