Compare commits
59
Commits
No files matched your search
@@ -73,3 +73,14 @@ FEWO_BANK_BIC=
|
||||
FEWO_BANK_NAME=
|
||||
FEWO_REVIEW_REQUEST_AFTER_DAYS=2
|
||||
FEWO_GUEST_RETENTION_YEARS=10
|
||||
FEWO_CHANNEL_STALE_AFTER_MINUTES=60
|
||||
FEWO_CHANNEL_TASK_REMINDER_AFTER_MINUTES=120
|
||||
FEWO_HEALTH_TOKEN=
|
||||
FEWO_AUTOMATION_WEBHOOK_URL=
|
||||
FEWO_AUTOMATION_SECRET=
|
||||
FEWO_MAILBOX_HOST=
|
||||
FEWO_MAILBOX_PORT=993
|
||||
FEWO_MAILBOX_ENCRYPTION=ssl
|
||||
FEWO_MAILBOX_USERNAME=
|
||||
FEWO_MAILBOX_PASSWORD=
|
||||
FEWO_MAILBOX_FOLDER=INBOX
|
||||
@@ -0,0 +1,65 @@
|
||||
# Production settings – copy to <DEPLOY_PATH>/shared/.env on the server and fill in.
|
||||
# Generate APP_KEY locally once: php artisan key:generate --show
|
||||
|
||||
APP_NAME="Ferienwohnung Stommer"
|
||||
APP_ENV=production
|
||||
APP_KEY=
|
||||
APP_DEBUG=false
|
||||
APP_URL=https://www.fewo-stommer.de
|
||||
APP_TIMEZONE=Europe/Berlin
|
||||
APP_LOCALE=de
|
||||
APP_FALLBACK_LOCALE=de
|
||||
APP_FAKER_LOCALE=de_DE
|
||||
APP_MAINTENANCE_DRIVER=file
|
||||
|
||||
LOG_CHANNEL=daily
|
||||
LOG_LEVEL=warning
|
||||
|
||||
# Strato MariaDB 11.8 (Kundenlogin › Datenbanken und Webspace › Datenbanken verwalten)
|
||||
DB_CONNECTION=mariadb
|
||||
DB_HOST=
|
||||
DB_PORT=3306
|
||||
DB_DATABASE=
|
||||
DB_USERNAME=
|
||||
DB_PASSWORD=
|
||||
|
||||
SESSION_DRIVER=database
|
||||
SESSION_LIFETIME=120
|
||||
SESSION_SECURE_COOKIE=true
|
||||
CACHE_STORE=database
|
||||
QUEUE_CONNECTION=sync
|
||||
FILESYSTEM_DISK=local
|
||||
|
||||
# Strato mailbox fewo@stommer.de
|
||||
MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.strato.de
|
||||
MAIL_PORT=465
|
||||
MAIL_SCHEME=smtps
|
||||
MAIL_USERNAME=info@fewo-stommer.de
|
||||
MAIL_PASSWORD=
|
||||
MAIL_FROM_ADDRESS="info@fewo-stommer.de"
|
||||
MAIL_FROM_NAME="${APP_NAME}"
|
||||
|
||||
FEWO_OWNER_NAME="Brigitte Stommer"
|
||||
FEWO_OWNER_EMAIL=fewo@stommer.de
|
||||
FEWO_NOTIFICATION_EMAIL=fewo@stommer.de
|
||||
# Harte Umleitung aller E-Mails (gilt immer). Normal leer lassen – Testbetrieb/Scharfschalten: Admin › System › Betrieb
|
||||
FEWO_MAIL_REDIRECT_TO=
|
||||
FEWO_BANK_ACCOUNT_HOLDER=
|
||||
FEWO_BANK_IBAN=
|
||||
FEWO_BANK_BIC=
|
||||
FEWO_BANK_NAME=
|
||||
|
||||
# Portal booking e-mails (fast path)
|
||||
FEWO_MAILBOX_HOST=imap.strato.de
|
||||
FEWO_MAILBOX_PORT=993
|
||||
FEWO_MAILBOX_ENCRYPTION=ssl
|
||||
FEWO_MAILBOX_USERNAME=fewo@stommer.de
|
||||
FEWO_MAILBOX_PASSWORD=
|
||||
FEWO_MAILBOX_FOLDER=INBOX
|
||||
|
||||
# Monitoring / automation (long random values, e.g. php -r "echo bin2hex(random_bytes(24));")
|
||||
FEWO_HEALTH_TOKEN=
|
||||
FEWO_SCHEDULER_TOKEN=
|
||||
FEWO_AUTOMATION_SECRET=
|
||||
FEWO_AUTOMATION_WEBHOOK_URL=
|
||||
@@ -0,0 +1,105 @@
|
||||
# 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
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
tags: ['v*']
|
||||
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'
|
||||
runs-on: ubuntu-latest
|
||||
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
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: npm
|
||||
|
||||
- name: SSH key
|
||||
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
|
||||
|
||||
- name: Deploy
|
||||
env:
|
||||
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 }}
|
||||
run: |
|
||||
export DEPLOY_SSH_KEY="$HOME/.ssh/deploy_key"
|
||||
bash scripts/deploy.sh "${{ inputs.environment || 'production' }}" deploy
|
||||
@@ -28,3 +28,7 @@ _ide_helper.php
|
||||
Homestead.json
|
||||
Homestead.yaml
|
||||
Thumbs.db
|
||||
|
||||
# Deployment settings with access data
|
||||
/scripts/deploy.*.env
|
||||
!/scripts/deploy.example.env
|
||||
@@ -1,6 +1,6 @@
|
||||
# Ferienwohnung Stommer
|
||||
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`.
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches, file ownership, deploy only from an up-to-date `main`).
|
||||
|
||||
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally.
|
||||
- UI and all user-facing texts are German; code, identifiers and PHPDoc are English.
|
||||
@@ -10,7 +10,14 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
|
||||
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – 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`.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Ferienwohnung Stommer
|
||||
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`.
|
||||
Website + booking management for a holiday apartment in Kühlungsborn. Concept and roadmap: `docs/KONZEPT.md`. **Current state and next steps: `docs/STATUS.md` – start there and update it after larger changes.** Parallel sessions (e.g. theme design on another machine): follow `docs/ZUSAMMENARBEIT.md` (branches, file ownership, deploy only from an up-to-date `main`).
|
||||
|
||||
- Hosting target: Strato shared webhosting (PHP + MySQL, no Node at runtime) – build assets locally.
|
||||
- UI and all user-facing texts are German; code, identifiers and PHPDoc are English.
|
||||
@@ -10,7 +10,14 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
|
||||
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – 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`.
|
||||
|
||||
@@ -1,58 +1,37 @@
|
||||
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
|
||||
# Ferienwohnung Stommer – Webseite und Vermietungsverwaltung
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
|
||||
</p>
|
||||
Webseite mit Buchungsanfrage und eine Verwaltung (Admin) für die Ferienwohnung Stommer, Strandstraße 15, 18225 Kühlungsborn. Ersetzt die bisherige WordPress-Seite www.fewo-stommer.de. Laravel 13, Filament 5, Livewire 4, Tailwind 4; Hosting bei Strato (Shared Webhosting, Hosting Pro).
|
||||
|
||||
## About Laravel
|
||||
**Testbetrieb:** https://stommer.info · Verwaltung: https://stommer.info/admin (Konto + Zwei-Faktor-Anmeldung, siehe docs/BETRIEB.md §7)
|
||||
|
||||
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
|
||||
## Wo steht was?
|
||||
|
||||
- [Simple, fast routing engine](https://laravel.com/docs/routing).
|
||||
- [Powerful dependency injection container](https://laravel.com/docs/container).
|
||||
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
|
||||
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
|
||||
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
|
||||
- [Robust background job processing](https://laravel.com/docs/queues).
|
||||
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
|
||||
| Dokument | Inhalt |
|
||||
|---|---|
|
||||
| [docs/STATUS.md](docs/STATUS.md) | **Aktueller Stand**: was fertig ist, was offen ist, nächste Schritte – hier anfangen |
|
||||
| [docs/ZUSAMMENARBEIT.md](docs/ZUSAMMENARBEIT.md) | Regeln für parallele Arbeit (z. B. Theme-Entwicklung auf einem anderen Rechner) – Branches, Dateibereiche, Ausliefern |
|
||||
| [docs/KONZEPT.md](docs/KONZEPT.md) | Fachliches Konzept und alle Entscheidungen (Buchungswege §6a, Festlegungen §6b) |
|
||||
| [docs/BETRIEB.md](docs/BETRIEB.md) | Server, Zugänge, Konfiguration, Konten/2FA, Backups, Löschfristen, bekannte Eigenheiten |
|
||||
| [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | Auslieferung auf Strato (Skript, Versionen, Gitea Actions) |
|
||||
| [docs/THEMES.md](docs/THEMES.md) | Theme-System: Architektur, Bausteine und ihre Daten (Vorlagen-Vertrag) |
|
||||
| [docs/THEME-ERSTELLUNG.md](docs/THEME-ERSTELLUNG.md) | **Verbindliche Anleitung für ein neues Theme** (Design-Sitzung) |
|
||||
| [docs/PORTALE.md](docs/PORTALE.md) | Buchungsportale, Kalenderabgleich, Portal-E-Mails |
|
||||
| [styles/README.md](styles/README.md) | Markenelemente (Logo, Favicon, Symbole, Wellenband) |
|
||||
| docs/DATENSCHUTZ-*, GAP-DELTA, GO-LIVE-CHECKLISTE, LOESCHKONZEPT, BUCHUNGSPROZESS, DATENMODELL-KONZEPT | Analyse eines Datenschutz-Agenten (Annahmen markiert; maßgeblich ist KONZEPT.md) |
|
||||
| [CLAUDE.md](CLAUDE.md) / [AGENTS.md](AGENTS.md) | Technische Leitplanken für KI-Assistenten (identisch) |
|
||||
|
||||
Laravel is accessible, powerful, and provides tools required for large, robust applications.
|
||||
|
||||
## Learning Laravel
|
||||
|
||||
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
|
||||
|
||||
In addition, [Laracasts](https://laracasts.com) contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
|
||||
|
||||
You can also watch bite-sized lessons with real-world projects on [Laravel Learn](https://laravel.com/learn), where you will be guided through building a Laravel application from scratch while learning PHP fundamentals.
|
||||
|
||||
## Agentic Development
|
||||
|
||||
Laravel's predictable structure and conventions make it ideal for AI coding agents like Claude Code, Cursor, and GitHub Copilot. Install [Laravel Boost](https://laravel.com/docs/ai) to supercharge your AI workflow:
|
||||
## Lokal starten
|
||||
|
||||
```bash
|
||||
composer require laravel/boost --dev
|
||||
|
||||
php artisan boost:install
|
||||
composer install && npm ci
|
||||
cp .env.example .env && php artisan key:generate
|
||||
touch database/database.sqlite # PowerShell: New-Item database/database.sqlite
|
||||
php artisan migrate:fresh --seed # Testdaten: Wohnung, Preise 2026, Seiten, Erscheinungsbilder
|
||||
npm run build # oder npm run dev
|
||||
php artisan serve # http://localhost:8000 · /admin: admin@example.com / password (2FA beim ersten Login)
|
||||
php artisan test --compact # alle Tests müssen grün sein
|
||||
```
|
||||
|
||||
Boost provides your agent 15+ tools and skills that help agents build Laravel applications while following best practices.
|
||||
## Ausliefern
|
||||
|
||||
## Contributing
|
||||
|
||||
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
|
||||
|
||||
## Security Vulnerabilities
|
||||
|
||||
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
|
||||
|
||||
## License
|
||||
|
||||
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
|
||||
`bash scripts/deploy.sh staging deploy` – baut den **letzten Commit** und spielt ihn auf stommer.info (Details und Regeln: docs/DEPLOYMENT.md, docs/ZUSAMMENARBEIT.md).
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest accepts the offer on the signed offer page: the booking is concluded. A record of what was
|
||||
* accepted is kept (offer version, time, fingerprints of price and terms – no IP address), then the booking
|
||||
* is confirmed as usual (contract + confirmation mail as electronic acknowledgement).
|
||||
*/
|
||||
class AcceptOffer
|
||||
{
|
||||
public function __construct(private ConfirmBooking $confirm) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
$this->ensureAcceptable($booking, $offerVersion);
|
||||
|
||||
$booking->update([
|
||||
'accepted_at' => now(),
|
||||
'acceptance' => [
|
||||
'offer_version' => $booking->offer_version,
|
||||
'accepted_at' => now()->toIso8601String(),
|
||||
'total' => $booking->total,
|
||||
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
|
||||
'terms_sha256' => hash('sha256', (string) Content::get('contract.terms').'|'.Content::get('stay.cancellation')),
|
||||
'via' => 'offer_link',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->confirm->handle($booking);
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function ensureAcceptable(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
if ($offerVersion !== $booking->offer_version) {
|
||||
throw ReservationException::offerOutdated();
|
||||
}
|
||||
|
||||
if ($booking->status !== BookingStatus::OfferSent) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'angenommen');
|
||||
}
|
||||
|
||||
if (! $booking->hold_expires_at?->isFuture()) {
|
||||
throw ReservationException::offerExpired();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,15 @@
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use App\Models\PortalEmail;
|
||||
|
||||
/**
|
||||
* Anonymises guests whose last stay ended longer ago than the retention period (GDPR storage limitation).
|
||||
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
|
||||
* guests who only ever sent requests/offers that never became binding (shorter period), and removes
|
||||
* operational extras that are no longer needed (portal e-mail excerpts, marketing attribution).
|
||||
* Booking records (dates, prices, payments) stay as accounting documents.
|
||||
*/
|
||||
class AnonymizeGuests
|
||||
{
|
||||
@@ -19,8 +24,32 @@ public function handle(): int
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereDate('departure', '>=', $cutoff))
|
||||
->get();
|
||||
|
||||
$guests->each->anonymize();
|
||||
$inquiryCutoff = now()->subMonths(config('fewo.retention.inquiry_months'));
|
||||
$inquiriesOnly = Guest::query()
|
||||
->whereNull('anonymized_at')
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereNotNull('confirmed_at'))
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->where('updated_at', '>=', $inquiryCutoff))
|
||||
->where('updated_at', '<', $inquiryCutoff)
|
||||
->get();
|
||||
|
||||
return $guests->count();
|
||||
$all = $guests->merge($inquiriesOnly)->unique('id');
|
||||
$all->each->anonymize();
|
||||
|
||||
$this->purgeOperationalData();
|
||||
|
||||
return $all->count();
|
||||
}
|
||||
|
||||
private function purgeOperationalData(): void
|
||||
{
|
||||
PortalEmail::query()
|
||||
->whereNotNull('excerpt')
|
||||
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
|
||||
->update(['excerpt' => null]);
|
||||
|
||||
Booking::query()
|
||||
->where('created_at', '<', now()->subMonths(config('fewo.retention.attribution_months')))
|
||||
->where(fn ($query) => $query->whereNotNull('referral_source')->orWhereNotNull('utm_source')->orWhereNotNull('utm_medium')->orWhereNotNull('utm_campaign'))
|
||||
->update(['referral_source' => null, 'utm_source' => null, 'utm_medium' => null, 'utm_campaign' => null]);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\BookingConfirmed;
|
||||
@@ -11,18 +12,23 @@
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* The landlord accepts a reservation. Expired reservations can still be confirmed while the dates are free.
|
||||
* Makes a booking binding: payment due dates are fixed, the rental contract is generated and sent with the
|
||||
* confirmation. Used when the guest accepts an offer (AcceptOffer) and when the landlord confirms directly
|
||||
* (e.g. a booking agreed on the phone). Expired requests/offers can still be confirmed while the dates are free.
|
||||
*/
|
||||
class ConfirmBooking
|
||||
{
|
||||
public function __construct(private AvailabilityChecker $availability) {}
|
||||
public function __construct(
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
{
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'bestätigt');
|
||||
}
|
||||
|
||||
@@ -35,9 +41,12 @@ public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
'status' => BookingStatus::Confirmed,
|
||||
'hold_expires_at' => null,
|
||||
'confirmed_at' => now(),
|
||||
'deposit_due_on' => today()->addDays(config('fewo.deposit_due_days'))->toDateString(),
|
||||
]);
|
||||
});
|
||||
|
||||
$this->contract->generate($booking);
|
||||
|
||||
if ($notifyGuest) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingConfirmed($booking));
|
||||
}
|
||||
|
||||
@@ -3,26 +3,40 @@
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Copies all seasons starting in a given year to the following year with the same calendar dates,
|
||||
* so a new price year only needs adjusting instead of re-entering.
|
||||
* Copies all seasons starting in a given year to the following year, so a new price year only needs adjusting
|
||||
* instead of re-entering. Optionally every season start is moved to the nearest given weekday (e.g. Saturday
|
||||
* as changeover day); seasons that were adjacent stay adjacent.
|
||||
*/
|
||||
class CopySeasonsToNextYear
|
||||
{
|
||||
/**
|
||||
* @param int|null $alignToWeekday ISO weekday (1 = Monday … 7 = Sunday) or null for the same calendar dates
|
||||
* @return array{created: int, skipped: int}
|
||||
*/
|
||||
public function handle(Property $property, int $year): array
|
||||
public function handle(Property $property, int $year, ?int $alignToWeekday = null): array
|
||||
{
|
||||
$created = 0;
|
||||
$skipped = 0;
|
||||
|
||||
$seasons = $property->seasons()->whereYear('starts_on', $year)->get();
|
||||
$seasons = $property->seasons()->whereYear('starts_on', $year)->orderBy('starts_on')->get();
|
||||
|
||||
// New start per old start date; an end that equals another season's start follows that start.
|
||||
$moved = [];
|
||||
foreach ($seasons as $season) {
|
||||
$moved[$season->starts_on->toDateString()] = $this->shift($season->starts_on, $alignToWeekday);
|
||||
}
|
||||
|
||||
foreach ($seasons as $season) {
|
||||
$startsOn = $season->starts_on->addYearNoOverflow();
|
||||
$endsOn = $season->ends_on->addYearNoOverflow();
|
||||
$startsOn = $moved[$season->starts_on->toDateString()];
|
||||
$endsOn = $moved[$season->ends_on->toDateString()] ?? $this->shift($season->ends_on, $alignToWeekday);
|
||||
if ($endsOn->lessThanOrEqualTo($startsOn)) {
|
||||
$skipped++;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($property->seasons()->overlapping($startsOn, $endsOn)->exists()) {
|
||||
$skipped++;
|
||||
@@ -40,4 +54,19 @@ public function handle(Property $property, int $year): array
|
||||
|
||||
return ['created' => $created, 'skipped' => $skipped];
|
||||
}
|
||||
|
||||
/**
|
||||
* One year later; with a weekday, moved to the nearest such day (at most 3 days earlier or later).
|
||||
*/
|
||||
private function shift(CarbonImmutable $date, ?int $weekday): CarbonImmutable
|
||||
{
|
||||
$next = $date->addYearNoOverflow();
|
||||
if ($weekday === null) {
|
||||
return $next;
|
||||
}
|
||||
|
||||
$difference = ($weekday - $next->isoWeekday() + 7) % 7;
|
||||
|
||||
return $difference <= 3 ? $next->addDays($difference) : $next->subDays(7 - $difference);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\Property;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Creates blocking/unblocking tasks for every portal that must be maintained by hand
|
||||
* (e.g. instant booking portals whose calendar import is too slow), notifies the landlord
|
||||
* and hands the task to an optional external automation.
|
||||
*/
|
||||
class CreateChannelTasks
|
||||
{
|
||||
/**
|
||||
* @return list<ChannelTask>
|
||||
*/
|
||||
public function handle(Property $property, CarbonInterface $startsOn, CarbonInterface $endsOn, ChannelTaskAction $action, string $reason, ?int $exceptChannelId = null): array
|
||||
{
|
||||
if ($endsOn->lessThanOrEqualTo(today())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$channels = $property->channels()->active()
|
||||
->where('requires_manual_blocking', true)
|
||||
->when($exceptChannelId, fn ($query) => $query->whereKeyNot($exceptChannelId))
|
||||
->get();
|
||||
|
||||
$tasks = $channels->map(fn (Channel $channel): ChannelTask => $channel->tasks()->create([
|
||||
'action' => $action,
|
||||
'starts_on' => $startsOn->toDateString(),
|
||||
'ends_on' => $endsOn->toDateString(),
|
||||
'reason' => $reason,
|
||||
]))->all();
|
||||
|
||||
if ($tasks === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks)));
|
||||
|
||||
foreach ($tasks as $task) {
|
||||
$this->sendToAutomation($task);
|
||||
}
|
||||
|
||||
return $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* POSTs the task to the automation webhook, signed with HMAC-SHA256 (header X-Signature).
|
||||
* The automation confirms via the signed callback URL contained in the payload.
|
||||
*/
|
||||
public function sendToAutomation(ChannelTask $task): void
|
||||
{
|
||||
$url = config('fewo.automation.webhook_url');
|
||||
$secret = config('fewo.automation.secret');
|
||||
if (blank($url) || blank($secret)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$body = json_encode([
|
||||
'task_id' => $task->id,
|
||||
'channel' => $task->channel->name,
|
||||
'connector' => $task->channel->connector,
|
||||
'action' => $task->action->value,
|
||||
'starts_on' => $task->starts_on->toDateString(),
|
||||
'ends_on' => $task->ends_on->toDateString(),
|
||||
'manage_url' => $task->channel->manage_url,
|
||||
'callback_url' => URL::route('channel-tasks.complete', $task),
|
||||
], JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
|
||||
|
||||
try {
|
||||
Http::timeout(10)
|
||||
->withHeaders(['X-Signature' => hash_hmac('sha256', $body, $secret)])
|
||||
->withBody($body, 'application/json')
|
||||
->post($url)
|
||||
->throw();
|
||||
|
||||
$task->update(['automation_sent_at' => now(), 'automation_error' => null]);
|
||||
} catch (Throwable $exception) {
|
||||
$task->update(['automation_error' => $exception->getMessage()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,10 @@
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Tenancy\TenantContextMissing;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
@@ -30,13 +34,32 @@ public function __construct(
|
||||
|
||||
/**
|
||||
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
||||
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution where the guest came from
|
||||
*
|
||||
* @throws QuoteException
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true): Booking
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): Booking
|
||||
{
|
||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source): Booking {
|
||||
$tenant = $property->tenant;
|
||||
|
||||
if ($tenant === null) {
|
||||
throw new TenantContextMissing(Property::class);
|
||||
}
|
||||
|
||||
return app(TenantContext::class)->run(
|
||||
$tenant,
|
||||
fn (): Booking => $this->create($property, $stay, $guestData, $message, $source, $sendMails, $attribution),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array{first_name: string, last_name: string, email: string, phone?: ?string, street?: ?string, postal_code?: ?string, city?: ?string, country?: ?string} $guestData
|
||||
* @param array{referral_source?: ?string, utm_source?: ?string, utm_medium?: ?string, utm_campaign?: ?string} $attribution
|
||||
*/
|
||||
private function create(Property $property, StayRequest $stay, array $guestData, ?string $message, string $source, bool $sendMails, array $attribution): Booking
|
||||
{
|
||||
$booking = DB::transaction(function () use ($property, $stay, $guestData, $message, $source, $attribution): Booking {
|
||||
Property::whereKey($property->getKey())->lockForUpdate()->first();
|
||||
|
||||
if (! $this->availability->isAvailable($property, $stay->arrival, $stay->departure)) {
|
||||
@@ -45,13 +68,13 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
||||
|
||||
$quote = $this->calculator->calculate($property, $stay);
|
||||
|
||||
$guest = Guest::firstOrNew(['email' => mb_strtolower($guestData['email'])]);
|
||||
$guest->fill($guestData)->fill(['email' => mb_strtolower($guestData['email'])])->save();
|
||||
[$guest, $differences] = $this->guestFor($guestData);
|
||||
|
||||
return $property->bookings()->create([
|
||||
'guest_id' => $guest->id,
|
||||
'status' => BookingStatus::Reserved,
|
||||
'source' => $source,
|
||||
...Arr::only(array_filter($attribution), ['referral_source', 'utm_source', 'utm_medium', 'utm_campaign']),
|
||||
'arrival' => $stay->arrival->toDateString(),
|
||||
'departure' => $stay->departure->toDateString(),
|
||||
'guests' => $stay->guests,
|
||||
@@ -63,6 +86,7 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
||||
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||
'hold_expires_at' => now()->addHours($property->hold_hours),
|
||||
'message' => $message,
|
||||
'internal_notes' => $differences !== [] ? "Abweichende Angaben in dieser Anfrage (Gästekartei nicht geändert):\n".implode("\n", $differences) : null,
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -73,6 +97,46 @@ public function handle(Property $property, StayRequest $stay, array $guestData,
|
||||
return $booking;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest record for the request. A known e-mail address never overwrites existing master data
|
||||
* (anybody can type somebody else's address); empty fields are completed, differing values are
|
||||
* returned so the landlord sees them with the request and can take them over in the offer.
|
||||
*
|
||||
* @param array<string, ?string> $guestData
|
||||
* @return array{0: Guest, 1: list<string>}
|
||||
*/
|
||||
private function guestFor(array $guestData): array
|
||||
{
|
||||
$email = mb_strtolower($guestData['email']);
|
||||
$guest = Guest::query()->where('email', $email)->first();
|
||||
|
||||
if ($guest === null) {
|
||||
return [Guest::create([
|
||||
...$guestData,
|
||||
'email' => $email,
|
||||
'tenant_id' => app(TenantContext::class)->id(),
|
||||
]), []];
|
||||
}
|
||||
|
||||
$labels = ['first_name' => 'Vorname', 'last_name' => 'Nachname', 'phone' => 'Telefon', 'street' => 'Straße', 'postal_code' => 'PLZ', 'city' => 'Ort', 'country' => 'Land'];
|
||||
$differences = [];
|
||||
foreach ($labels as $field => $label) {
|
||||
$value = trim((string) ($guestData[$field] ?? ''));
|
||||
if ($value === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (blank($guest->{$field})) {
|
||||
$guest->{$field} = $value;
|
||||
} elseif (mb_strtolower((string) $guest->{$field}) !== mb_strtolower($value)) {
|
||||
$differences[] = "{$label}: {$value} (Kartei: {$guest->{$field}})";
|
||||
}
|
||||
}
|
||||
$guest->save();
|
||||
|
||||
return [$guest, $differences];
|
||||
}
|
||||
|
||||
/**
|
||||
* A failing mail server must not lose the reservation; failures are reported and visible in the log.
|
||||
*/
|
||||
@@ -80,7 +144,7 @@ private function sendMails(Booking $booking): void
|
||||
{
|
||||
try {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ReservationReceived($booking));
|
||||
Mail::to(config('fewo.notification_email'))->send(new NewReservation($booking));
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReservation($booking));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ class DeclineBooking
|
||||
*/
|
||||
public function handle(Booking $booking, bool $notifyGuest = true): void
|
||||
{
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::Expired], true)) {
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Mail\ReservationExpired;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
@@ -16,7 +17,7 @@ class ExpireReservations
|
||||
public function handle(): int
|
||||
{
|
||||
$expired = Booking::query()
|
||||
->where('status', BookingStatus::Reserved)
|
||||
->whereIn('status', BookingStatus::holding())
|
||||
->where('hold_expires_at', '<=', now())
|
||||
->with(['guest', 'property'])
|
||||
->get();
|
||||
@@ -24,7 +25,7 @@ public function handle(): int
|
||||
foreach ($expired as $booking) {
|
||||
$booking->update(['status' => BookingStatus::Expired]);
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new ReservationExpired($booking));
|
||||
Mail::to(Settings::notificationRecipients())->send(new ReservationExpired($booking));
|
||||
}
|
||||
|
||||
return $expired->count();
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Mail\ChannelSyncAlert;
|
||||
use App\Mail\MailboxAlert;
|
||||
use App\Models\Channel;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Alerts the landlord once per incident when a portal import or the mailbox fast path fails
|
||||
* or has not succeeded for too long. The alert is reset by the next success.
|
||||
*/
|
||||
class MonitorChannels
|
||||
{
|
||||
private const MAILBOX_ALERTED_KEY = 'mailbox:alerted';
|
||||
|
||||
public function handle(): int
|
||||
{
|
||||
$channels = Channel::query()->active()->whereNull('alerted_at')->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->isStale());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
Mail::to(Settings::notificationRecipients())->send(new ChannelSyncAlert($channel));
|
||||
$channel->forceFill(['alerted_at' => now()])->save();
|
||||
}
|
||||
|
||||
return $channels->count() + $this->monitorMailbox();
|
||||
}
|
||||
|
||||
public static function mailboxIsStale(): bool
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
|
||||
|
||||
return $lastSuccess === null
|
||||
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
|
||||
}
|
||||
|
||||
private function monitorMailbox(): int
|
||||
{
|
||||
if (! self::mailboxIsStale()) {
|
||||
Cache::forget(self::MAILBOX_ALERTED_KEY);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (Cache::has(self::MAILBOX_ALERTED_KEY)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\Mail\ParsedPortalMail;
|
||||
use App\Channels\Mail\PortalMail;
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Fast path for portal bookings: the notification e-mail usually arrives within a minute, long before
|
||||
* the portal's calendar export is read. A recognised booking is blocked immediately; the later calendar
|
||||
* sync confirms the block. Anything not recognised with confidence is flagged for review – never guessed.
|
||||
*/
|
||||
class ProcessPortalMail
|
||||
{
|
||||
public function __construct(
|
||||
private PortalMailParser $parser,
|
||||
private ConflictDetector $conflictDetector,
|
||||
) {}
|
||||
|
||||
public function handle(PortalMail $mail): ?PortalEmail
|
||||
{
|
||||
if (PortalEmail::where('message_id', $mail->messageId)->exists()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$channel = $this->channelFor($mail->from);
|
||||
if ($channel === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parser->parse($mail->subject, $mail->text);
|
||||
$conflicts = [];
|
||||
|
||||
$record = DB::transaction(function () use ($mail, $channel, $parsed, &$conflicts): PortalEmail {
|
||||
[$status, $block, $note] = match ($parsed->type) {
|
||||
PortalEmailType::Booking => $this->block($channel, $parsed, $conflicts),
|
||||
PortalEmailType::Cancellation => $this->release($channel, $parsed),
|
||||
PortalEmailType::Inquiry => [PortalEmailStatus::Ignored, null, 'Anfrage – keine Sperre nötig.'],
|
||||
PortalEmailType::Unknown => [PortalEmailStatus::NeedsReview, null, 'Inhalt nicht erkannt.'],
|
||||
};
|
||||
|
||||
return PortalEmail::create([
|
||||
'channel_id' => $channel->id,
|
||||
'message_id' => $mail->messageId,
|
||||
'from' => mb_substr($mail->from, 0, 255),
|
||||
'subject' => mb_substr($mail->subject, 0, 255),
|
||||
'received_at' => $mail->receivedAt,
|
||||
'type' => $parsed->type,
|
||||
'status' => $status,
|
||||
'starts_on' => $parsed->startsOn?->toDateString(),
|
||||
'ends_on' => $parsed->endsOn?->toDateString(),
|
||||
'reference' => $parsed->reference,
|
||||
'blocked_period_id' => $block?->id,
|
||||
'excerpt' => mb_substr(trim(preg_replace('/\s+/u', ' ', strip_tags($mail->text))), 0, 500),
|
||||
'note' => $note,
|
||||
]);
|
||||
});
|
||||
|
||||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
||||
}
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
|
||||
}
|
||||
|
||||
return $record;
|
||||
}
|
||||
|
||||
/**
|
||||
* Channels list the sender addresses or domains of their notification e-mails in settings.email_senders.
|
||||
*/
|
||||
public function channelFor(string $from): ?Channel
|
||||
{
|
||||
$from = mb_strtolower($from);
|
||||
|
||||
return Channel::query()->active()->get()->first(function (Channel $channel) use ($from): bool {
|
||||
foreach ($this->senders($channel) as $sender) {
|
||||
if (str_contains($from, $sender)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
public function senders(Channel $channel): array
|
||||
{
|
||||
return array_values(array_filter(array_map(
|
||||
fn (string $sender): string => mb_strtolower(trim($sender)),
|
||||
explode(',', (string) $channel->setting('email_senders')),
|
||||
)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $conflicts
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
|
||||
{
|
||||
if (! $parsed->hasPeriod()) {
|
||||
return [PortalEmailStatus::NeedsReview, null, 'Buchung erkannt, aber An-/Abreise nicht sicher lesbar.'];
|
||||
}
|
||||
|
||||
$known = $channel->blockedPeriods()
|
||||
->whereDate('starts_on', $parsed->startsOn)
|
||||
->whereDate('ends_on', $parsed->endsOn)
|
||||
->first();
|
||||
if ($known) {
|
||||
return [PortalEmailStatus::AlreadyKnown, $known, null];
|
||||
}
|
||||
|
||||
$block = $channel->blockedPeriods()->create([
|
||||
'property_id' => $channel->property_id,
|
||||
'starts_on' => $parsed->startsOn->toDateString(),
|
||||
'ends_on' => $parsed->endsOn->toDateString(),
|
||||
'reason' => "{$channel->name} (E-Mail)".($parsed->reference ? ": {$parsed->reference}" : ''),
|
||||
'source' => 'email',
|
||||
'external_uid' => 'email:'.($parsed->reference ?? $parsed->startsOn->format('Ymd').'-'.$parsed->endsOn->format('Ymd')),
|
||||
]);
|
||||
|
||||
$conflicts = $this->conflictDetector->conflictsFor($block);
|
||||
|
||||
return [PortalEmailStatus::Blocked, $block, null];
|
||||
}
|
||||
|
||||
/**
|
||||
* Only blocks created from e-mails are released here; calendar blocks disappear with the next sync.
|
||||
*
|
||||
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
|
||||
*/
|
||||
private function release(Channel $channel, ParsedPortalMail $parsed): array
|
||||
{
|
||||
$emailBlocks = $channel->blockedPeriods()->where('source', 'email');
|
||||
|
||||
$block = match (true) {
|
||||
$parsed->reference !== null => (clone $emailBlocks)->where('external_uid', 'email:'.$parsed->reference)->first(),
|
||||
$parsed->hasPeriod() => (clone $emailBlocks)->whereDate('starts_on', $parsed->startsOn)->whereDate('ends_on', $parsed->endsOn)->first(),
|
||||
default => null,
|
||||
};
|
||||
|
||||
if ($block) {
|
||||
$block->delete();
|
||||
|
||||
return [PortalEmailStatus::Released, null, 'Sperre aus E-Mail aufgehoben.'];
|
||||
}
|
||||
|
||||
return [PortalEmailStatus::NeedsReview, null, 'Stornierung erkannt – bitte prüfen; Kalender-Sperren verschwinden mit dem nächsten Abgleich.'];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Payment;
|
||||
use Carbon\CarbonInterface;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* Records a received payment (or a refund with a negative amount) and moves the booking along:
|
||||
* Bestätigt → Anzahlung erhalten → Bezahlt.
|
||||
*/
|
||||
class RecordPayment
|
||||
{
|
||||
public function handle(Booking $booking, int $amount, CarbonInterface $paidOn, PaymentMethod $method = PaymentMethod::Transfer, ?string $note = null, ?string $recordedBy = null): Payment
|
||||
{
|
||||
return DB::transaction(function () use ($booking, $amount, $paidOn, $method, $note, $recordedBy): Payment {
|
||||
$payment = $booking->payments()->create([
|
||||
'amount' => $amount,
|
||||
'paid_on' => $paidOn->toDateString(),
|
||||
'method' => $method,
|
||||
'note' => $note,
|
||||
'recorded_by' => $recordedBy,
|
||||
]);
|
||||
|
||||
$booking->unsetRelation('payments');
|
||||
$this->updateStatus($booking);
|
||||
|
||||
return $payment;
|
||||
});
|
||||
}
|
||||
|
||||
public function updateStatus(Booking $booking): void
|
||||
{
|
||||
$paymentStatuses = [BookingStatus::Confirmed, BookingStatus::DepositPaid, BookingStatus::Paid];
|
||||
if (! in_array($booking->status, $paymentStatuses, true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$paid = $booking->paidAmount();
|
||||
$status = match (true) {
|
||||
$paid >= $booking->total => BookingStatus::Paid,
|
||||
$paid >= $booking->deposit && $paid > 0 => BookingStatus::DepositPaid,
|
||||
default => BookingStatus::Confirmed,
|
||||
};
|
||||
|
||||
if ($status !== $booking->status) {
|
||||
$booking->update(['status' => $status]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest declines the offer on the offer page: the dates are released and the landlord is informed.
|
||||
*/
|
||||
class RejectOffer
|
||||
{
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
if ($offerVersion !== $booking->offer_version) {
|
||||
throw ReservationException::offerOutdated();
|
||||
}
|
||||
|
||||
if ($booking->status !== BookingStatus::OfferSent) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt');
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::Declined,
|
||||
'declined_by' => 'guest',
|
||||
'hold_expires_at' => null,
|
||||
]);
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Reminds the landlord once about blocking tasks that are still open after the reminder time.
|
||||
*/
|
||||
class RemindChannelTasks
|
||||
{
|
||||
public function handle(): int
|
||||
{
|
||||
$tasks = ChannelTask::query()
|
||||
->open()
|
||||
->whereNull('reminded_at')
|
||||
->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes')))
|
||||
->with('channel')
|
||||
->get();
|
||||
|
||||
if ($tasks->isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks->all(), reminder: true));
|
||||
ChannelTask::whereKey($tasks->modelKeys())->update(['reminded_at' => now()]);
|
||||
|
||||
return $tasks->count();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Mail\ArrivalInformation;
|
||||
use App\Mail\PaymentReminder;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Daily booking workflow: payment requests and reminders, arrival information, completion after departure.
|
||||
* Every message is sent at most once per booking.
|
||||
*/
|
||||
class SendBookingReminders
|
||||
{
|
||||
private const BALANCE_REQUEST_DAYS_BEFORE = 7;
|
||||
|
||||
private const ARRIVAL_INFO_DAYS_BEFORE = 7;
|
||||
|
||||
/**
|
||||
* @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int}
|
||||
*/
|
||||
public function handle(): array
|
||||
{
|
||||
$today = today();
|
||||
$unpaid = [BookingStatus::Confirmed, BookingStatus::DepositPaid];
|
||||
|
||||
$depositOverdue = $this->bookings(fn (Builder $query) => $query
|
||||
->where('status', BookingStatus::Confirmed)
|
||||
->whereNull('deposit_reminded_at')
|
||||
->whereDate('deposit_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0);
|
||||
$this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at');
|
||||
|
||||
$balanceRequest = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
->whereNull('balance_requested_at')
|
||||
->whereDate('balance_due_on', '>=', $today)
|
||||
->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE)))
|
||||
->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid);
|
||||
$this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at');
|
||||
|
||||
$balanceOverdue = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', $unpaid)
|
||||
->whereNull('balance_reminded_at')
|
||||
->whereDate('balance_due_on', '<', $today))
|
||||
->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment()));
|
||||
$this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at');
|
||||
|
||||
$arrivals = $this->bookings(fn (Builder $query) => $query
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->whereNull('arrival_info_sent_at')
|
||||
->whereDate('arrival', '>=', $today)
|
||||
->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE)));
|
||||
foreach ($arrivals as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking));
|
||||
$booking->update(['arrival_info_sent_at' => now()]);
|
||||
}
|
||||
|
||||
$completed = Booking::query()
|
||||
->where('status', BookingStatus::Paid)
|
||||
->whereDate('departure', '<', $today)
|
||||
->get();
|
||||
$completed->each->update(['status' => BookingStatus::Completed]);
|
||||
|
||||
return [
|
||||
'deposit_overdue' => $depositOverdue->count(),
|
||||
'balance_request' => $balanceRequest->count(),
|
||||
'balance_overdue' => $balanceOverdue->count(),
|
||||
'arrival_info' => $arrivals->count(),
|
||||
'completed' => $completed->count(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(Builder<Booking>): Builder<Booking> $constraints
|
||||
* @return Collection<int, Booking>
|
||||
*/
|
||||
private function bookings(callable $constraints): Collection
|
||||
{
|
||||
return $constraints(Booking::query()->with(['guest', 'property', 'payments']))
|
||||
->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at'))
|
||||
->get()
|
||||
->toBase();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param Collection<int, Booking> $bookings
|
||||
*/
|
||||
private function remind(Collection $bookings, string $kind, string $sentAtColumn): void
|
||||
{
|
||||
foreach ($bookings as $booking) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind));
|
||||
$booking->update([$sentAtColumn => now()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferMade;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\QuoteLine;
|
||||
use App\Pricing\StayRequest;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Arr;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
/**
|
||||
* Booking path 1 (docs/KONZEPT.md §6a): the landlord turns a request into an offer. Dates, guests, promo
|
||||
* code, a manual price adjustment and the guest's contact data can be changed; the price is calculated again,
|
||||
* the contract draft is generated and the guest receives it with a signed link to accept or decline.
|
||||
* Sending again replaces the previous offer (links of older versions stop working).
|
||||
*/
|
||||
class SendOffer
|
||||
{
|
||||
public function __construct(
|
||||
private PriceCalculator $calculator,
|
||||
private AvailabilityChecker $availability,
|
||||
private RentalContract $contract,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, guest?: array<string, ?string>} $changes
|
||||
*
|
||||
* @throws QuoteException
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking
|
||||
{
|
||||
if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet');
|
||||
}
|
||||
|
||||
DB::transaction(function () use ($booking, $changes): void {
|
||||
$arrival = CarbonImmutable::parse($changes['arrival'] ?? $booking->arrival);
|
||||
$departure = CarbonImmutable::parse($changes['departure'] ?? $booking->departure);
|
||||
|
||||
if (! $this->availability->isAvailable($booking->property, $arrival, $departure, ignore: $booking)) {
|
||||
throw ReservationException::notAvailable();
|
||||
}
|
||||
|
||||
$promoCode = array_key_exists('promo_code', $changes) ? (filled($changes['promo_code']) ? trim((string) $changes['promo_code']) : null) : $booking->promo_code;
|
||||
$stay = new StayRequest($arrival, $departure, (int) ($changes['guests'] ?? $booking->guests), $booking->extras ?? [], $promoCode);
|
||||
$adjustment = (int) ($changes['price_adjustment'] ?? 0);
|
||||
$adjustmentLabel = trim((string) ($changes['price_adjustment_label'] ?? '')) ?: ($adjustment < 0 ? 'Nachlass' : 'Zuschlag');
|
||||
$quote = $this->quoteWithAdjustment($booking, $stay, $adjustment, $adjustmentLabel);
|
||||
|
||||
if (filled($changes['guest'] ?? null)) {
|
||||
$booking->guest->update(Arr::only(array_map(fn ($value) => filled($value) ? trim((string) $value) : null, $changes['guest']), ['first_name', 'last_name', 'phone', 'street', 'postal_code', 'city', 'country']));
|
||||
}
|
||||
|
||||
$booking->update([
|
||||
'status' => BookingStatus::OfferSent,
|
||||
'arrival' => $arrival->toDateString(),
|
||||
'departure' => $departure->toDateString(),
|
||||
'guests' => $stay->guests,
|
||||
'promo_code' => $quote->promoCodeApplied ? $promoCode : null,
|
||||
'price_adjustment' => $adjustment !== 0 ? $adjustment : null,
|
||||
'price_adjustment_label' => $adjustment !== 0 ? $adjustmentLabel : null,
|
||||
'quote' => $quote->toArray(),
|
||||
'total' => $quote->total(),
|
||||
'deposit' => $quote->deposit(),
|
||||
'balance_due_on' => $quote->balanceDueOn->toDateString(),
|
||||
'hold_expires_at' => filled($changes['valid_until'] ?? null) ? CarbonImmutable::parse($changes['valid_until']) : now()->addHours($booking->property->hold_hours),
|
||||
'offer_version' => $booking->offer_version + 1,
|
||||
'offer_sent_at' => now(),
|
||||
'offer_message' => $changes['offer_message'] ?? null,
|
||||
]);
|
||||
});
|
||||
|
||||
$booking->refresh();
|
||||
$this->contract->generate($booking, draft: true);
|
||||
|
||||
if ($sendMail) {
|
||||
Mail::to($booking->guest->email, $booking->guest->full_name)->send(new OfferMade($booking, $this->offerUrl($booking)));
|
||||
}
|
||||
|
||||
return $booking;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest's link to the offer page; valid while the offer is valid and only for this offer version.
|
||||
*/
|
||||
public function offerUrl(Booking $booking): string
|
||||
{
|
||||
$parameters = ['booking' => $booking, 'v' => $booking->offer_version];
|
||||
|
||||
return $booking->website()?->temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters)
|
||||
?? URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, $parameters);
|
||||
}
|
||||
|
||||
/**
|
||||
* Price for the (possibly changed) stay plus the manual adjustment; a reduction never makes the stay negative.
|
||||
*
|
||||
* @throws QuoteException
|
||||
*/
|
||||
private function quoteWithAdjustment(Booking $booking, StayRequest $stay, int $adjustment, string $label): PriceQuote
|
||||
{
|
||||
$quote = $this->calculator->calculate($booking->property, $stay);
|
||||
if ($adjustment === 0) {
|
||||
return $quote;
|
||||
}
|
||||
|
||||
$adjustment = max($adjustment, -$quote->rent());
|
||||
|
||||
return $quote->withLine(new QuoteLine(QuoteLineType::Adjustment, $label, 1, $adjustment, $adjustment));
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
use App\Mail\NewReview;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Review;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use RuntimeException;
|
||||
|
||||
@@ -32,7 +33,7 @@ public function handle(Booking $booking, array $data): Review
|
||||
'stayed_on' => $booking->arrival,
|
||||
]);
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new NewReview($review));
|
||||
Mail::to(Settings::notificationRecipients())->send(new NewReview($review));
|
||||
|
||||
return $review;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ConflictDetector;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelSyncLog;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
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).
|
||||
*/
|
||||
class SyncChannel
|
||||
{
|
||||
public function __construct(private ConflictDetector $conflictDetector = new ConflictDetector) {}
|
||||
|
||||
public function handle(Channel $channel): ChannelSyncLog
|
||||
{
|
||||
$startedAt = microtime(true);
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
$stale = $existing->reject(fn (BlockedPeriod $block, string $uid): bool => isset($seen[$uid]) || $block->ends_on->lessThanOrEqualTo($today));
|
||||
$stale->each->delete();
|
||||
$counts['removed'] = $stale->count();
|
||||
});
|
||||
|
||||
$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' => 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Free gaps in the calendar: runs of free nights with an occupied night (booking or block) directly
|
||||
* before and after. Open-ended free periods (nothing booked behind them yet) are not gaps.
|
||||
*/
|
||||
class GapFinder
|
||||
{
|
||||
/** How far around a stay we look for the neighbouring occupations. */
|
||||
private const LOOKAROUND_NIGHTS = 60;
|
||||
|
||||
public function __construct(private AvailabilityChecker $availability = new AvailabilityChecker) {}
|
||||
|
||||
/**
|
||||
* Length in nights of the gap that contains the whole stay, or null if the stay is not inside a gap
|
||||
* (because a night is occupied or the free period is not closed on both sides).
|
||||
*/
|
||||
public function gapContaining(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): ?int
|
||||
{
|
||||
$from = $arrival->subDays(self::LOOKAROUND_NIGHTS);
|
||||
$until = $departure->addDays(self::LOOKAROUND_NIGHTS);
|
||||
$occupied = $this->availability->occupiedNights($property, $from, $until);
|
||||
|
||||
for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) {
|
||||
if (isset($occupied[$night->toDateString()])) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$start = $arrival;
|
||||
while (! isset($occupied[$start->subDay()->toDateString()])) {
|
||||
$start = $start->subDay();
|
||||
if ($start->lessThanOrEqualTo($from)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$end = $departure;
|
||||
while (! isset($occupied[$end->toDateString()])) {
|
||||
$end = $end->addDay();
|
||||
if ($end->greaterThanOrEqualTo($until)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return (int) $start->diffInDays($end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gaps of 1 … $maxNights nights starting within [$from, $until), as [arrival, departure] pairs.
|
||||
*
|
||||
* @return list<array{0: CarbonImmutable, 1: CarbonImmutable}>
|
||||
*/
|
||||
public function gaps(Property $property, CarbonImmutable $from, CarbonImmutable $until, int $maxNights): array
|
||||
{
|
||||
$occupied = $this->availability->occupiedNights($property, $from->subDay(), $until->addDays($maxNights + 1));
|
||||
|
||||
$gaps = [];
|
||||
$night = $from;
|
||||
while ($night->lessThan($until)) {
|
||||
$isGapStart = ! isset($occupied[$night->toDateString()]) && isset($occupied[$night->subDay()->toDateString()]);
|
||||
if (! $isGapStart) {
|
||||
$night = $night->addDay();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$end = $night;
|
||||
while (! isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$end = $end->addDay();
|
||||
}
|
||||
|
||||
if (isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$gaps[] = [$night, $end];
|
||||
}
|
||||
|
||||
$night = $end->addDay();
|
||||
}
|
||||
|
||||
return $gaps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Resolves the connectors registered in config/channels.php.
|
||||
*/
|
||||
class ChannelRegistry
|
||||
{
|
||||
/**
|
||||
* @return array<string, class-string<ChannelConnector>>
|
||||
*/
|
||||
public function connectors(): array
|
||||
{
|
||||
return collect(config('channels.connectors'))
|
||||
->mapWithKeys(fn (string $class): array => [$class::key() => $class])
|
||||
->all();
|
||||
}
|
||||
|
||||
public function resolve(string $key): ChannelConnector
|
||||
{
|
||||
$class = $this->connectors()[$key] ?? throw new InvalidArgumentException("Unknown channel connector [{$key}].");
|
||||
|
||||
return app($class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
public function options(): array
|
||||
{
|
||||
return array_map(fn (string $class): string => $class::label(), $this->connectors());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use RuntimeException;
|
||||
|
||||
class ChannelSyncException extends RuntimeException {}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
|
||||
/**
|
||||
* Finds occupations from other sources that overlap a block reported by a portal
|
||||
* (a possible double booking). Blocks of the same portal never conflict with each other.
|
||||
*/
|
||||
class ConflictDetector
|
||||
{
|
||||
/**
|
||||
* @return list<string> human readable descriptions
|
||||
*/
|
||||
public function conflictsFor(BlockedPeriod $block): array
|
||||
{
|
||||
$property = $block->property;
|
||||
$channelName = $block->channel->name ?? 'Sperre';
|
||||
$period = $block->starts_on->format('d.m.Y').' – '.$block->ends_on->format('d.m.Y');
|
||||
|
||||
$bookings = $property->bookings()->occupying()->overlapping($block->starts_on, $block->ends_on)->with('guest')->get()
|
||||
->map(fn (Booking $booking): string => "{$channelName} meldet {$period}, überschneidet sich mit Buchung {$booking->reference} ({$booking->guest->full_name}, {$booking->arrival->format('d.m.Y')} – {$booking->departure->format('d.m.Y')})");
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
->overlapping($block->starts_on, $block->ends_on)
|
||||
->whereKeyNot($block->getKey())
|
||||
->when($block->channel_id, fn ($query) => $query->where(fn ($query) => $query->whereNull('channel_id')->orWhere('channel_id', '!=', $block->channel_id)))
|
||||
->with('channel')
|
||||
->get()
|
||||
->map(fn (BlockedPeriod $other): string => "{$channelName} meldet {$period}, überschneidet sich mit Sperre „".($other->channel->name ?? $other->reason ?? 'manuell')."“ ({$other->starts_on->format('d.m.Y')} – {$other->ends_on->format('d.m.Y')})");
|
||||
|
||||
return [...$bookings->all(), ...$blocks->all()];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Contracts;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use App\Models\Channel;
|
||||
use Filament\Schemas\Components\Component;
|
||||
|
||||
/**
|
||||
* Connects one kind of portal or channel manager. Register implementations in config/channels.php.
|
||||
*/
|
||||
interface ChannelConnector
|
||||
{
|
||||
/**
|
||||
* Stable identifier stored on the channel, e.g. "ical".
|
||||
*/
|
||||
public static function key(): string;
|
||||
|
||||
public static function label(): string;
|
||||
|
||||
/**
|
||||
* Admin form fields for the connector's settings; use state paths below "settings.".
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
public static function settingsSchema(): array;
|
||||
|
||||
/**
|
||||
* Whether occupations can currently be imported (e.g. an import URL is configured).
|
||||
*/
|
||||
public function canImport(Channel $channel): bool;
|
||||
|
||||
/**
|
||||
* All occupations the portal currently reports.
|
||||
*
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetchOccupations(Channel $channel): array;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An occupation reported by a portal: nights from startsOn up to (excluding) endsOn.
|
||||
*/
|
||||
final readonly class ExternalPeriod
|
||||
{
|
||||
public function __construct(
|
||||
public string $uid,
|
||||
public CarbonImmutable $startsOn,
|
||||
public CarbonImmutable $endsOn,
|
||||
public ?string $summary = null,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use App\Models\Channel;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Illuminate\Http\Client\ConnectionException;
|
||||
use Illuminate\Http\Client\RequestException;
|
||||
use Illuminate\Support\Facades\Http;
|
||||
|
||||
/**
|
||||
* Generic calendar connection that works with almost every portal: we read the portal's iCal export
|
||||
* and the portal reads our feed for this channel.
|
||||
*/
|
||||
class ICalConnector implements ChannelConnector
|
||||
{
|
||||
public function __construct(private ICalParser $parser) {}
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'ical';
|
||||
}
|
||||
|
||||
public static function label(): string
|
||||
{
|
||||
return 'Kalender-Abgleich (iCal)';
|
||||
}
|
||||
|
||||
public static function settingsSchema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('settings.import_url')
|
||||
->label('iCal-Export-Adresse des Portals')
|
||||
->helperText('Im Vermieterbereich des Portals unter „Kalender exportieren“. Leer lassen, wenn das Portal keinen Kalender anbietet.')
|
||||
->url()
|
||||
->maxLength(2048),
|
||||
];
|
||||
}
|
||||
|
||||
public function canImport(Channel $channel): bool
|
||||
{
|
||||
return filled($channel->setting('import_url'));
|
||||
}
|
||||
|
||||
public function fetchOccupations(Channel $channel): array
|
||||
{
|
||||
$url = preg_replace('#^webcals?://#i', 'https://', (string) $channel->setting('import_url'));
|
||||
|
||||
try {
|
||||
$response = Http::timeout(20)
|
||||
->retry(2, 1000)
|
||||
->withHeaders(['Accept' => 'text/calendar'])
|
||||
->get($url)
|
||||
->throw();
|
||||
} catch (ConnectionException|RequestException $exception) {
|
||||
throw new ChannelSyncException('Kalender konnte nicht abgerufen werden: '.$exception->getMessage(), previous: $exception);
|
||||
}
|
||||
|
||||
return $this->parser->parse($response->body());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Carbon\CarbonInterface;
|
||||
|
||||
/**
|
||||
* The calendar a portal imports from us: every occupation of the property except the ones that
|
||||
* came from this very portal (otherwise the portal would block its own bookings twice).
|
||||
* Events carry no guest data.
|
||||
*/
|
||||
class ICalFeed
|
||||
{
|
||||
public function build(Channel $channel): string
|
||||
{
|
||||
$property = $channel->property;
|
||||
$from = CarbonImmutable::today()->subDays(30);
|
||||
$until = CarbonImmutable::today()->addYears(2);
|
||||
$suffix = config('channels.uid_suffix');
|
||||
|
||||
$events = [];
|
||||
|
||||
foreach ($property->bookings()->occupying()->overlapping($from, $until)->get() as $booking) {
|
||||
/** @var Booking $booking */
|
||||
$events[] = $this->event("booking-{$booking->id}{$suffix}", $booking->arrival, $booking->departure, $booking->updated_at);
|
||||
}
|
||||
|
||||
$blocks = $property->blockedPeriods()
|
||||
->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);
|
||||
}
|
||||
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VCALENDAR',
|
||||
'VERSION:2.0',
|
||||
'PRODID:-//Ferienwohnung Stommer//Belegung//DE',
|
||||
'CALSCALE:GREGORIAN',
|
||||
'METHOD:PUBLISH',
|
||||
'X-WR-CALNAME:'.$this->escape($property->name),
|
||||
...$events,
|
||||
'END:VCALENDAR',
|
||||
])."\r\n";
|
||||
}
|
||||
|
||||
private function event(string $uid, CarbonInterface $start, CarbonInterface $end, ?CarbonInterface $modified): string
|
||||
{
|
||||
return implode("\r\n", [
|
||||
'BEGIN:VEVENT',
|
||||
"UID:{$uid}",
|
||||
'DTSTAMP:'.($modified ?? now())->utc()->format('Ymd\THis\Z'),
|
||||
'DTSTART;VALUE=DATE:'.$start->format('Ymd'),
|
||||
'DTEND;VALUE=DATE:'.$end->format('Ymd'),
|
||||
'SUMMARY:Belegt',
|
||||
'TRANSP:OPAQUE',
|
||||
'END:VEVENT',
|
||||
]);
|
||||
}
|
||||
|
||||
private function escape(string $text): string
|
||||
{
|
||||
return str_replace(['\\', ';', ',', "\n"], ['\\\\', '\\;', '\\,', '\\n'], $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\ICal;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\ExternalPeriod;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
class ICalParser
|
||||
{
|
||||
/**
|
||||
* @return list<ExternalPeriod>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function parse(string $ics): array
|
||||
{
|
||||
if (! str_contains($ics, 'BEGIN:VCALENDAR')) {
|
||||
throw new ChannelSyncException('Die Antwort ist kein iCal-Kalender.');
|
||||
}
|
||||
|
||||
$lines = explode("\n", preg_replace("/\r?\n[ \t]/", '', str_replace("\r\n", "\n", $ics)));
|
||||
|
||||
$periods = [];
|
||||
$event = null;
|
||||
foreach ($lines as $line) {
|
||||
$line = rtrim($line, "\r");
|
||||
|
||||
if ($line === 'BEGIN:VEVENT') {
|
||||
$event = [];
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($line === 'END:VEVENT') {
|
||||
if ($event !== null && ($period = $this->toPeriod($event))) {
|
||||
$periods[] = $period;
|
||||
}
|
||||
$event = null;
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
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)];
|
||||
}
|
||||
}
|
||||
|
||||
return $periods;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$start = $this->toDate($event['DTSTART']);
|
||||
$end = isset($event['DTEND']) ? $this->toDate($event['DTEND']) : $start?->addDay();
|
||||
|
||||
if ($start === null || $end === null || $end->lessThanOrEqualTo($start)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$uid = $event['UID']['value'] ?? sha1($start->toDateString().'|'.$end->toDateString());
|
||||
|
||||
return new ExternalPeriod($uid, $start, $end, $this->unescape($event['SUMMARY']['value'] ?? null));
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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), '"');
|
||||
|
||||
return in_array($tz, timezone_identifiers_list(), true) ? $tz : config('app.timezone');
|
||||
}
|
||||
}
|
||||
|
||||
return config('app.timezone');
|
||||
}
|
||||
|
||||
private function unescape(?string $text): ?string
|
||||
{
|
||||
return $text === null ? null : str_replace(['\\n', '\\N', '\\,', '\\;', '\\\\'], ["\n", "\n", ',', ';', '\\'], $text);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
use Webklex\PHPIMAP\ClientManager;
|
||||
use Webklex\PHPIMAP\Message;
|
||||
|
||||
/**
|
||||
* Reads recent e-mails of the given senders from the configured IMAP mailbox without marking them as read.
|
||||
* Works without the PHP imap extension.
|
||||
*/
|
||||
class MailboxReader
|
||||
{
|
||||
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
|
||||
|
||||
public const LAST_ERROR_KEY = 'mailbox:last_error';
|
||||
|
||||
public static function isConfigured(): bool
|
||||
{
|
||||
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $senders addresses or domains
|
||||
* @return list<PortalMail>
|
||||
*
|
||||
* @throws ChannelSyncException
|
||||
*/
|
||||
public function fetch(array $senders): array
|
||||
{
|
||||
$config = config('fewo.mailbox');
|
||||
|
||||
try {
|
||||
$client = (new ClientManager)->make([
|
||||
'host' => $config['host'],
|
||||
'port' => $config['port'],
|
||||
'encryption' => $config['encryption'],
|
||||
'validate_cert' => true,
|
||||
'username' => $config['username'],
|
||||
'password' => $config['password'],
|
||||
'protocol' => 'imap',
|
||||
]);
|
||||
$client->connect();
|
||||
$folder = $client->getFolderByPath($config['folder']);
|
||||
|
||||
$mails = [];
|
||||
foreach ($senders as $sender) {
|
||||
$messages = $folder->query()
|
||||
->whereSince(CarbonImmutable::today()->subDays($config['lookback_days']))
|
||||
->whereFrom($sender)
|
||||
->leaveUnread()
|
||||
->get();
|
||||
|
||||
foreach ($messages as $message) {
|
||||
$mails[] = $this->toPortalMail($message);
|
||||
}
|
||||
}
|
||||
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::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);
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
private function toPortalMail(Message $message): PortalMail
|
||||
{
|
||||
$text = $message->getTextBody();
|
||||
if (trim($text) === '') {
|
||||
$text = strip_tags(preg_replace('#<(br|p|div|tr|li)[^>]*>#i', "\n", $message->getHTMLBody()));
|
||||
}
|
||||
|
||||
$from = $message->getFrom()->first();
|
||||
$date = $message->getDate()->first();
|
||||
|
||||
return new PortalMail(
|
||||
messageId: (string) ($message->getMessageId()->first() ?: sha1($message->getSubject()->first().$date)),
|
||||
from: (string) ($from->mail ?? ''),
|
||||
subject: (string) $message->getSubject()->first(),
|
||||
text: $text,
|
||||
receivedAt: $date ? CarbonImmutable::instance($date) : CarbonImmutable::now(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Enums\PortalEmailType;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
final readonly class ParsedPortalMail
|
||||
{
|
||||
public function __construct(
|
||||
public PortalEmailType $type,
|
||||
public ?CarbonImmutable $startsOn = null,
|
||||
public ?CarbonImmutable $endsOn = null,
|
||||
public ?string $reference = null,
|
||||
) {}
|
||||
|
||||
public function hasPeriod(): bool
|
||||
{
|
||||
return $this->startsOn !== null && $this->endsOn !== null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An incoming e-mail as delivered by the mailbox reader or the n8n webhook.
|
||||
*/
|
||||
final readonly class PortalMail
|
||||
{
|
||||
public function __construct(
|
||||
public string $messageId,
|
||||
public string $from,
|
||||
public string $subject,
|
||||
public string $text,
|
||||
public CarbonImmutable $receivedAt,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
<?php
|
||||
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Enums\PortalEmailType;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Reads booking notifications of portals (German and English). It only extracts what it can find
|
||||
* with confidence; everything else is left empty so that the e-mail is flagged for review.
|
||||
*/
|
||||
class PortalMailParser
|
||||
{
|
||||
private const CANCELLATION = ['storniert', 'stornierung', 'cancelled', 'canceled', 'cancellation', 'abgesagt'];
|
||||
|
||||
private const BOOKING = ['neue buchung', 'buchung bestätigt', 'buchungsbestätigung', 'reservierung bestätigt', 'sofortbuchung', 'hat gebucht', 'ist gebucht', 'new booking', 'booking confirmed', 'reservation confirmed', 'instant booking', 'you have a new reservation', 'neue reservierung'];
|
||||
|
||||
/** Checked before bookings: "Neue Buchungsanfrage" is not a confirmed booking. */
|
||||
private const INQUIRY = ['buchungsanfrage', 'booking request', 'reservation request', 'anfrage', 'inquiry', 'enquiry'];
|
||||
|
||||
private const MONTHS = [
|
||||
'jan' => 1, 'januar' => 1, 'january' => 1,
|
||||
'feb' => 2, 'februar' => 2, 'february' => 2,
|
||||
'mär' => 3, 'märz' => 3, 'mrz' => 3, 'mar' => 3, 'march' => 3,
|
||||
'apr' => 4, 'april' => 4,
|
||||
'mai' => 5, 'may' => 5,
|
||||
'jun' => 6, 'juni' => 6, 'june' => 6,
|
||||
'jul' => 7, 'juli' => 7, 'july' => 7,
|
||||
'aug' => 8, 'august' => 8,
|
||||
'sep' => 9, 'sept' => 9, 'september' => 9,
|
||||
'okt' => 10, 'oktober' => 10, 'oct' => 10, 'october' => 10,
|
||||
'nov' => 11, 'november' => 11,
|
||||
'dez' => 12, 'dezember' => 12, 'dec' => 12, 'december' => 12,
|
||||
];
|
||||
|
||||
public function parse(string $subject, string $text): ParsedPortalMail
|
||||
{
|
||||
$content = $this->normalize($subject."\n".$text);
|
||||
|
||||
$type = $this->type(mb_strtolower($subject))
|
||||
?? $this->type(mb_strtolower($this->normalize($text)))
|
||||
?? PortalEmailType::Unknown;
|
||||
|
||||
[$startsOn, $endsOn] = $this->period($content);
|
||||
|
||||
return new ParsedPortalMail($type, $startsOn, $endsOn, $this->reference($content));
|
||||
}
|
||||
|
||||
/**
|
||||
* The subject decides first; the body only when the subject is not conclusive.
|
||||
*/
|
||||
private function type(string $text): ?PortalEmailType
|
||||
{
|
||||
return match (true) {
|
||||
$this->containsAny($text, self::CANCELLATION) => PortalEmailType::Cancellation,
|
||||
$this->containsAny($text, self::INQUIRY) => PortalEmailType::Inquiry,
|
||||
$this->containsAny($text, self::BOOKING) => PortalEmailType::Booking,
|
||||
default => null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{?CarbonImmutable, ?CarbonImmutable}
|
||||
*/
|
||||
private function period(string $content): array
|
||||
{
|
||||
$dates = $this->dates($content);
|
||||
|
||||
$arrival = $this->dateAfterLabel($content, $dates, '/\b(anreise|ankunft|check-?in|arrival)\b/iu');
|
||||
$departure = $this->dateAfterLabel($content, $dates, '/\b(abreise|check-?out|departure)\b/iu');
|
||||
|
||||
if ($arrival === null || $departure === null) {
|
||||
[$arrival, $departure] = $this->firstPlausiblePair($dates);
|
||||
}
|
||||
|
||||
if ($arrival === null || $departure === null || ! $this->isPlausible($arrival, $departure)) {
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
return [$arrival, $departure];
|
||||
}
|
||||
|
||||
/**
|
||||
* All dates in the text with their offsets, in order of appearance.
|
||||
*
|
||||
* @return list<array{offset: int, date: CarbonImmutable}>
|
||||
*/
|
||||
private function dates(string $content): array
|
||||
{
|
||||
$monthNames = implode('|', array_map(fn (string $name): string => preg_quote($name, '/'), array_keys(self::MONTHS)));
|
||||
$patterns = [
|
||||
'/\b(?<d>\d{1,2})\.(?<m>\d{1,2})\.(?<y>\d{4}|\d{2})\b/u',
|
||||
'/\b(?<y>\d{4})-(?<m>\d{2})-(?<d>\d{2})\b/u',
|
||||
'/\b(?<d>\d{1,2})\.?\s+(?<mn>'.$monthNames.')\.?\s+(?<y>\d{4})\b/iu',
|
||||
'/\b(?<mn>'.$monthNames.')\.?\s+(?<d>\d{1,2}),?\s+(?<y>\d{4})\b/iu',
|
||||
];
|
||||
|
||||
$dates = [];
|
||||
foreach ($patterns as $pattern) {
|
||||
preg_match_all($pattern, $content, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
|
||||
foreach ($matches as $match) {
|
||||
$month = isset($match['mn']) && $match['mn'][0] !== '' ? self::MONTHS[mb_strtolower($match['mn'][0])] ?? null : (int) $match['m'][0];
|
||||
$year = (int) $match['y'][0];
|
||||
$year = $year < 100 ? 2000 + $year : $year;
|
||||
|
||||
if ($month !== null && checkdate($month, (int) $match['d'][0], $year)) {
|
||||
$dates[] = ['offset' => $match[0][1], 'date' => CarbonImmutable::create($year, $month, (int) $match['d'][0])];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
usort($dates, fn (array $a, array $b): int => $a['offset'] <=> $b['offset']);
|
||||
|
||||
return $dates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{offset: int, date: CarbonImmutable}> $dates
|
||||
*/
|
||||
private function dateAfterLabel(string $content, array $dates, string $labelPattern): ?CarbonImmutable
|
||||
{
|
||||
if (! preg_match($labelPattern, $content, $label, PREG_OFFSET_CAPTURE)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$labelEnd = $label[0][1] + strlen($label[0][0]);
|
||||
foreach ($dates as $date) {
|
||||
if ($date['offset'] >= $labelEnd && $date['offset'] - $labelEnd <= 80) {
|
||||
return $date['date'];
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{offset: int, date: CarbonImmutable}> $dates
|
||||
* @return array{?CarbonImmutable, ?CarbonImmutable}
|
||||
*/
|
||||
private function firstPlausiblePair(array $dates): array
|
||||
{
|
||||
foreach ($dates as $index => $first) {
|
||||
foreach (array_slice($dates, $index + 1) as $second) {
|
||||
if ($this->isPlausible($first['date'], $second['date'])) {
|
||||
return [$first['date'], $second['date']];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [null, null];
|
||||
}
|
||||
|
||||
private function isPlausible(CarbonImmutable $arrival, CarbonImmutable $departure): bool
|
||||
{
|
||||
return $departure->greaterThan($arrival)
|
||||
&& $arrival->diffInDays($departure) <= 90
|
||||
&& $arrival->greaterThanOrEqualTo(CarbonImmutable::today()->subDays(2))
|
||||
&& $arrival->lessThanOrEqualTo(CarbonImmutable::today()->addYears(3));
|
||||
}
|
||||
|
||||
private function reference(string $content): ?string
|
||||
{
|
||||
if (preg_match('/\b(HA-[A-Z0-9]{5,})\b/', $content, $match)) {
|
||||
return $match[1];
|
||||
}
|
||||
|
||||
if (preg_match('/(?:buchungsnummer|buchungs-nr\.?|reservierungsnummer|reservation id|reservation number|booking id|booking number)\s*[:#]?\s*([A-Z0-9][A-Z0-9-]{4,})/iu', $content, $match)) {
|
||||
return $match[1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private function normalize(string $text): string
|
||||
{
|
||||
$text = html_entity_decode(strip_tags($text), ENT_QUOTES | ENT_HTML5, 'UTF-8');
|
||||
|
||||
return preg_replace('/[ \t\x{00A0}\x{202F}]+/u', ' ', $text);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $needles
|
||||
*/
|
||||
private function containsAny(string $haystack, array $needles): bool
|
||||
{
|
||||
foreach ($needles as $needle) {
|
||||
if (str_contains($haystack, $needle)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Throwable;
|
||||
|
||||
#[Signature('backup:database {--keep= : Anzahl aufbewahrter Sicherungen}')]
|
||||
#[Description('Write a compressed SQL dump of the database to storage/app/private/backups and keep the newest ones')]
|
||||
class BackupDatabase extends Command
|
||||
{
|
||||
public const DIRECTORY = 'backups';
|
||||
|
||||
/** Tables without lasting value; their content is not dumped (structure only). */
|
||||
private const SKIP_DATA = ['sessions', 'cache', 'cache_locks', 'jobs', 'job_batches', 'failed_jobs'];
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$keep = (int) ($this->option('keep') ?? config('fewo.backup.keep', 14));
|
||||
$file = self::DIRECTORY.'/fewo-'.now()->format('Ymd-His').'.sql.gz';
|
||||
$temp = tempnam(sys_get_temp_dir(), 'fewo-backup');
|
||||
$out = gzopen($temp, 'wb6');
|
||||
|
||||
try {
|
||||
gzwrite($out, '-- FeWo Stommer database backup '.now()->toIso8601String().' ('.DB::getDriverName().")\n");
|
||||
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=0;\nSET NAMES utf8mb4;\n" : "PRAGMA foreign_keys=OFF;\n");
|
||||
|
||||
foreach ($this->tables() as $table) {
|
||||
gzwrite($out, "\nDROP TABLE IF EXISTS ".$this->quoteName($table).";\n".$this->createStatement($table).";\n");
|
||||
if (! in_array($table, self::SKIP_DATA, true)) {
|
||||
$this->dumpRows($out, $table);
|
||||
}
|
||||
}
|
||||
|
||||
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=1;\n" : "PRAGMA foreign_keys=ON;\n");
|
||||
gzclose($out);
|
||||
|
||||
Storage::disk('local')->put($file, (string) file_get_contents($temp));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('Sicherung fehlgeschlagen: '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
} finally {
|
||||
@unlink($temp);
|
||||
}
|
||||
|
||||
$this->prune($keep);
|
||||
$this->info("Sicherung erstellt: storage/app/private/{$file} (".round(Storage::disk('local')->size($file) / 1024).' KB)');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function isMysql(): bool
|
||||
{
|
||||
return in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function tables(): array
|
||||
{
|
||||
return $this->isMysql()
|
||||
? array_map(fn (object $row): string => (string) array_values((array) $row)[0], DB::select('SHOW TABLES'))
|
||||
: array_map(fn (object $row): string => $row->name, DB::select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"));
|
||||
}
|
||||
|
||||
private function createStatement(string $table): string
|
||||
{
|
||||
if ($this->isMysql()) {
|
||||
return (string) array_values((array) DB::selectOne('SHOW CREATE TABLE '.$this->quoteName($table)))[1];
|
||||
}
|
||||
|
||||
return (string) DB::selectOne("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", [$table])->sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource $out
|
||||
*/
|
||||
private function dumpRows($out, string $table): void
|
||||
{
|
||||
$pdo = DB::connection()->getPdo();
|
||||
$offset = 0;
|
||||
|
||||
do {
|
||||
$rows = DB::table($table)->offset($offset)->limit(500)->get();
|
||||
foreach ($rows as $row) {
|
||||
$values = array_map(fn ($value): string => $value === null ? 'NULL' : (is_int($value) || is_float($value) ? (string) $value : $pdo->quote((string) $value)), (array) $row);
|
||||
gzwrite($out, 'INSERT INTO '.$this->quoteName($table).' ('.implode(', ', array_map($this->quoteName(...), array_keys((array) $row))).') VALUES ('.implode(', ', $values).");\n");
|
||||
}
|
||||
$offset += 500;
|
||||
} while ($rows->count() === 500);
|
||||
}
|
||||
|
||||
private function quoteName(string $name): string
|
||||
{
|
||||
return $this->isMysql() ? '`'.str_replace('`', '``', $name).'`' : '"'.str_replace('"', '""', $name).'"';
|
||||
}
|
||||
|
||||
private function prune(int $keep): void
|
||||
{
|
||||
collect(Storage::disk('local')->files(self::DIRECTORY))
|
||||
->filter(fn (string $path): bool => str_ends_with($path, '.sql.gz'))
|
||||
->sort()
|
||||
->reverse()
|
||||
->slice(max(1, $keep))
|
||||
->each(fn (string $path) => Storage::disk('local')->delete($path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeChecker;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('themes:check {theme? : Key des Themes (leer = alle)}')]
|
||||
#[Description('Check themes against the theme contract (docs/THEME-ERSTELLUNG.md): manifest, build, required markup, colours, contrast')]
|
||||
class CheckTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeChecker $checker): int
|
||||
{
|
||||
$key = $this->argument('theme');
|
||||
if ($key !== null && ! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$themes = $key !== null ? [$registry->all()[$key]] : array_values($registry->all());
|
||||
$failed = false;
|
||||
|
||||
foreach ($themes as $theme) {
|
||||
['errors' => $errors, 'warnings' => $warnings] = $checker->check($theme);
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$theme->name}</> ({$theme->key} {$theme->version}".($theme->parent ? ", Eltern-Theme {$theme->parent}" : '').')');
|
||||
|
||||
foreach ($errors as $error) {
|
||||
$this->line(" <fg=red>✗</> {$error}");
|
||||
}
|
||||
foreach ($warnings as $warning) {
|
||||
$this->line(" <fg=yellow>!</> {$warning}");
|
||||
}
|
||||
if ($errors === [] && $warnings === []) {
|
||||
$this->line(' <fg=green>✓</> Alles in Ordnung.');
|
||||
}
|
||||
|
||||
$failed = $failed || $errors !== [];
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
|
||||
use function Laravel\Prompts\password;
|
||||
use function Laravel\Prompts\select;
|
||||
use function Laravel\Prompts\text;
|
||||
|
||||
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content} {--tenant= : Kurzname des Mandanten}')]
|
||||
#[Description('Create an admin panel account (the password is entered interactively and never passed as an argument)')]
|
||||
class CreateUser extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$tenant = $this->resolveTenant();
|
||||
|
||||
if ($tenant === false) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$email = $this->argument('email') ?? text('E-Mail-Adresse', required: true, validate: ['email' => 'email']);
|
||||
$email = mb_strtolower(trim($email));
|
||||
|
||||
if (User::where('email', $email)->exists()) {
|
||||
$this->error("Es gibt bereits einen Benutzer mit {$email}.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$name = $this->option('name') ?? text('Name', required: true);
|
||||
|
||||
$role = $this->option('role') !== null
|
||||
? UserRole::tryFrom($this->option('role'))
|
||||
: UserRole::from(select('Rolle', collect(UserRole::cases())->mapWithKeys(fn (UserRole $role): array => [$role->value => "{$role->getLabel()} – {$role->getDescription()}"])->all(), default: UserRole::Admin->value));
|
||||
|
||||
if ($role === null) {
|
||||
$this->error('Unbekannte Rolle. Erlaubt: '.implode(', ', array_column(UserRole::cases(), 'value')));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$password = password('Passwort (mind. 12 Zeichen)', required: true, validate: ['password' => Password::min(12)]);
|
||||
|
||||
if (password('Passwort wiederholen', required: true) !== $password) {
|
||||
$this->error('Die Passwörter stimmen nicht überein.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$user = User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
|
||||
|
||||
if ($tenant instanceof Tenant) {
|
||||
app(TenantContext::class)->set($tenant);
|
||||
$user->attachCurrentRole($tenant);
|
||||
}
|
||||
|
||||
$this->info("Benutzer {$email} ({$role->getLabel()}) angelegt.");
|
||||
|
||||
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* One landlord is used automatically. Several landlords need --tenant. None is allowed:
|
||||
* the account exists and is attached later.
|
||||
*/
|
||||
private function resolveTenant(): Tenant|false|null
|
||||
{
|
||||
$slug = $this->option('tenant');
|
||||
|
||||
if (is_string($slug) && $slug !== '') {
|
||||
$tenant = Tenant::query()->where('slug', $slug)->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error("Kein Mandant mit dem Kurznamen {$slug}.");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
$count = Tenant::query()->count();
|
||||
|
||||
if ($count > 1) {
|
||||
$this->error('Es gibt mehrere Mandanten. Bitte --tenant=kurzname angeben.');
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return $count === 1 ? Tenant::query()->first() : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Models\Channel;
|
||||
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')]
|
||||
class FetchPortalMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$senders = Channel::query()->active()->get()
|
||||
->flatMap(fn (Channel $channel): array => $processPortalMail->senders($channel))
|
||||
->unique()
|
||||
->values()
|
||||
->all();
|
||||
|
||||
if ($senders === []) {
|
||||
$this->line('Für kein Portal sind Absender hinterlegt.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
try {
|
||||
$mails = $reader->fetch($senders);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
foreach ($mails as $mail) {
|
||||
if ($record = $processPortalMail->handle($mail)) {
|
||||
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -8,41 +8,111 @@
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
|
||||
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area}')]
|
||||
#[Description('Import all images of a folder as website photos (e.g. when migrating from the old website)')]
|
||||
#[Signature('photos:import {directory : Folder with JPG/PNG/WebP files} {--category=apartment : apartment, outdoor or area} {--manifest= : CSV "file;category;alt_text" with paths relative to the folder (chooses and describes the photos)}')]
|
||||
#[Description('Import images as website photos (e.g. when migrating from the old website); the source files are only read')]
|
||||
class ImportPhotos extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$directory = rtrim((string) $this->argument('directory'), '/\\');
|
||||
$entries = $this->option('manifest') !== null
|
||||
? $this->manifestEntries((string) $this->option('manifest'), $directory)
|
||||
: $this->folderEntries($directory);
|
||||
|
||||
if ($entries === null) {
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$propertyId = Property::query()->value('id');
|
||||
$sort = (int) Photo::max('sort_order');
|
||||
$imported = 0;
|
||||
|
||||
foreach ($entries as ['file' => $file, 'category' => $category, 'alt_text' => $altText]) {
|
||||
$source = str_replace('\\', '/', substr($file, strlen($directory) + 1));
|
||||
|
||||
if (! is_file($file)) {
|
||||
$this->warn("Fehlt: {$source}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if (Media::query()->where('collection_name', Photo::COLLECTION)->where('custom_properties->source', $source)->exists()) {
|
||||
$this->line("– bereits vorhanden: {$source}");
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$photo = Photo::create([
|
||||
'property_id' => $category === PhotoCategory::Area ? null : $propertyId,
|
||||
'category' => $category,
|
||||
'alt_text' => $altText,
|
||||
'sort_order' => ++$sort,
|
||||
]);
|
||||
$photo->addMedia($file)
|
||||
->preservingOriginal()
|
||||
->withCustomProperties(['source' => $source])
|
||||
->toMediaCollection(Photo::COLLECTION);
|
||||
|
||||
$imported++;
|
||||
$this->line("✓ {$photo->alt_text}");
|
||||
}
|
||||
|
||||
$this->info("{$imported} Bilder importiert.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
|
||||
*/
|
||||
private function folderEntries(string $directory): ?array
|
||||
{
|
||||
$category = PhotoCategory::tryFrom((string) $this->option('category'));
|
||||
if ($category === null) {
|
||||
$this->error('Unbekannte Kategorie. Erlaubt: '.implode(', ', array_column(PhotoCategory::cases(), 'value')));
|
||||
|
||||
return self::FAILURE;
|
||||
return null;
|
||||
}
|
||||
|
||||
$files = glob(rtrim((string) $this->argument('directory'), '/\\').'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
|
||||
$propertyId = $category === PhotoCategory::Area ? null : Property::query()->value('id');
|
||||
$sort = (int) Photo::max('sort_order');
|
||||
$files = glob($directory.'/*.{jpg,jpeg,png,webp,JPG,JPEG,PNG,WEBP}', GLOB_BRACE) ?: [];
|
||||
|
||||
foreach ($files as $file) {
|
||||
$photo = Photo::create([
|
||||
'property_id' => $propertyId,
|
||||
'category' => $category,
|
||||
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
|
||||
'sort_order' => ++$sort,
|
||||
]);
|
||||
$photo->addMedia($file)->preservingOriginal()->toMediaCollection(Photo::COLLECTION);
|
||||
return array_map(fn (string $file): array => [
|
||||
'file' => $file,
|
||||
'category' => $category,
|
||||
'alt_text' => str(pathinfo($file, PATHINFO_FILENAME))->replace(['_', '-'], ' ')->squish()->ucfirst()->toString(),
|
||||
], $files);
|
||||
}
|
||||
|
||||
$this->line("✓ {$photo->alt_text}");
|
||||
/**
|
||||
* @return list<array{file: string, category: PhotoCategory, alt_text: string}>|null
|
||||
*/
|
||||
private function manifestEntries(string $manifest, string $directory): ?array
|
||||
{
|
||||
if (! is_file($manifest)) {
|
||||
$this->error("Liste nicht gefunden: {$manifest}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$this->info(count($files).' Bilder importiert.');
|
||||
$entries = [];
|
||||
foreach (array_slice(file($manifest, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [], 1) as $number => $line) {
|
||||
[$file, $category, $altText] = array_pad(str_getcsv($line, ';', '"', ''), 3, '');
|
||||
$category = PhotoCategory::tryFrom(trim($category));
|
||||
|
||||
return self::SUCCESS;
|
||||
if ($category === null || trim($file) === '' || trim($altText) === '') {
|
||||
$this->error('Ungültige Zeile '.($number + 2).": {$line}");
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
$entries[] = ['file' => $directory.'/'.ltrim(trim($file), '/'), 'category' => $category, 'alt_text' => trim($altText)];
|
||||
}
|
||||
|
||||
return $entries;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeManifest;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
#[Signature('themes:make {key : Ordner/Key, z. B. ostsee-nacht} {--name= : Anzeigename} {--parent= : Eltern-Theme (Standard: Basis-Theme)} {--description= : Beschreibung für die Theme-Auswahl}')]
|
||||
#[Description('Create a new theme next to the existing ones (never overwrites) – inherits everything until views are added')]
|
||||
class MakeTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry): int
|
||||
{
|
||||
$key = (string) $this->argument('key');
|
||||
$parent = (string) ($this->option('parent') ?: config('themes.base'));
|
||||
$themesPath = rtrim((string) (config('themes.paths')[0] ?? resource_path('themes')), '/\\');
|
||||
$path = "{$themesPath}/{$key}";
|
||||
$folder = str_replace('\\', '/', ltrim(substr($path, strlen(base_path())), '/\\'));
|
||||
|
||||
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $key)) {
|
||||
$this->error('Key: nur Kleinbuchstaben, Ziffern und Bindestriche, z. B. ostsee-nacht.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (File::exists($path) || isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ gibt es schon – es wird nichts überschrieben.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (! isset($registry->all()[$parent])) {
|
||||
$this->error("Eltern-Theme „{$parent}“ ist nicht installiert.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$name = (string) ($this->option('name') ?: str($key)->replace('-', ' ')->title());
|
||||
$manifest = [
|
||||
'key' => $key,
|
||||
'name' => $name,
|
||||
'version' => '0.1.0',
|
||||
'parent' => $parent,
|
||||
'description' => (string) ($this->option('description') ?: "Neues Theme auf Basis von „{$registry->get($parent)->name}“."),
|
||||
'assets' => ['css' => "{$folder}/theme.css", 'js' => "{$folder}/theme.js"],
|
||||
'tokens' => $registry->tokens($parent),
|
||||
];
|
||||
|
||||
File::ensureDirectoryExists("{$path}/views/sections");
|
||||
File::ensureDirectoryExists("{$path}/views/partials");
|
||||
File::put("{$path}/views/sections/.gitkeep", '');
|
||||
File::put("{$path}/views/partials/.gitkeep", '');
|
||||
File::put("{$path}/theme.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n");
|
||||
File::put("{$path}/theme.css", $this->css($name, $parent, $path, $registry));
|
||||
File::put("{$path}/theme.js", $this->js($name, ThemeManifest::relativePath($path, $registry->get($parent)->path).'/theme.js'));
|
||||
File::put("{$path}/README.md", $this->readme($name, $key, $parent));
|
||||
|
||||
$this->info("Theme „{$name}“ angelegt: {$folder}");
|
||||
$this->line('Es erbt zunächst alles von „'.$parent.'“. Vorlagen nach views/ kopieren und umgestalten – Anleitung: docs/THEME-ERSTELLUNG.md');
|
||||
$this->line("Prüfen: php artisan themes:check {$key} · Bauen: npm run build · Auswählen: Admin › System › Websites › Theme (dort „Vorschau“).");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Child theme CSS: Tailwind, the reusable styles of the nearest ancestor that has a theme-base.css,
|
||||
* and the template sources of all ancestors, the booking forms and the theme itself.
|
||||
*/
|
||||
private function css(string $name, string $parent, string $path, ThemeRegistry $registry): string
|
||||
{
|
||||
$ancestors = $registry->chain($parent);
|
||||
$base = collect($ancestors)->first(fn (ThemeManifest $theme): bool => is_file($theme->path.'/theme-base.css')) ?? $ancestors[0];
|
||||
$import = ThemeManifest::relativePath($path, $base->path).'/theme-base.css';
|
||||
$sources = collect($ancestors)
|
||||
->map(fn (ThemeManifest $theme): string => "@source '".ThemeManifest::relativePath($path, $theme->viewsPath())."';")
|
||||
->push("@source '".ThemeManifest::relativePath($path, resource_path('views/livewire'))."';")
|
||||
->push("@source './views';")
|
||||
->implode("\n");
|
||||
|
||||
return <<<CSS
|
||||
/*
|
||||
* Theme „{$name}“ – Child von „{$parent}“ (Anleitung: docs/THEME-ERSTELLUNG.md).
|
||||
* theme-base.css des Eltern-Themes bringt Schriften, Token-Mapping und Basis-Klassen (.eyebrow,
|
||||
* .heading-display, .btn-primary, .btn-accent, .prose-theme, .reveal). Hier nur Abweichungen ergänzen.
|
||||
*/
|
||||
@import 'tailwindcss';
|
||||
@import '{$import}';
|
||||
|
||||
/* Eigene Schriften selbst hosten: npm install @fontsource/<schrift> und hier importieren, z. B.
|
||||
@import '@fontsource/fraunces/400.css';
|
||||
*/
|
||||
|
||||
/* Vorlagen, deren Klassen gebaut werden: geerbte, Buchungsformulare, eigene. */
|
||||
{$sources}
|
||||
|
||||
@theme inline {
|
||||
/* --font-display: 'Fraunces', Georgia, serif; */
|
||||
/* --font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif; */
|
||||
}
|
||||
|
||||
@layer components {
|
||||
}
|
||||
|
||||
CSS;
|
||||
}
|
||||
|
||||
private function js(string $name, string $import): string
|
||||
{
|
||||
return <<<JS
|
||||
/**
|
||||
* Theme „{$name}“: übernimmt Lightbox, Verfügbarkeitssuche und rollierende Angebote vom Eltern-Theme.
|
||||
* Eigene Verbesserungen darunter – alles muss auch ohne JavaScript funktionieren.
|
||||
*/
|
||||
import '{$import}';
|
||||
|
||||
JS;
|
||||
}
|
||||
|
||||
private function readme(string $name, string $key, string $parent): string
|
||||
{
|
||||
return <<<MD
|
||||
# Theme „{$name}“ (`{$key}`)
|
||||
|
||||
Child-Theme von `{$parent}`. Vorlagen, die hier fehlen, kommen vom Eltern-Theme.
|
||||
|
||||
- Anleitung und Vorlagen-Vertrag: `docs/THEME-ERSTELLUNG.md`, `docs/THEMES.md` §5
|
||||
- Prüfen: `php artisan themes:check {$key}`
|
||||
- Ansehen ohne Umschalten: Admin › System › Websites › Theme „{$name}“ wählen › „Vorschau“ (erst danach speichern)
|
||||
|
||||
## Eigene Vorlagen
|
||||
|
||||
| Datei | Zweck |
|
||||
|---|---|
|
||||
| | |
|
||||
|
||||
MD;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Themes\ThemeFactory;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
#[Signature('themes:preview {theme : Key des Themes} {--hours=24 : Gültigkeit der Links}')]
|
||||
#[Description('Print signed preview links: every page of the site with the theme, in every appearance – without switching the site')]
|
||||
class PreviewTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeFactory $factory): int
|
||||
{
|
||||
$key = (string) $this->argument('theme');
|
||||
if (! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$site = $factory->site();
|
||||
$expires = now()->addHours((int) $this->option('hours'));
|
||||
$pages = $site->exists ? $site->pages()->where('is_published', true)->orderBy('sort_order')->get() : collect();
|
||||
$appearances = $site->exists ? $site->appearances()->orderByDesc('is_default')->orderBy('starts_md')->get() : collect();
|
||||
|
||||
$this->info("Vorschau „{$registry->get($key)->name}“ für {$site->name} (gültig bis {$expires->format('d.m.Y H:i')}):");
|
||||
foreach ($pages as $page) {
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$page->title}</>");
|
||||
$this->line(' heute: '.$this->url($page, ['theme' => $key], $expires));
|
||||
foreach ($appearances as $appearance) {
|
||||
$this->line(str_pad(" {$appearance->name}:", 16).$this->url($page, ['theme' => $key, 'vorschau' => $appearance->id], $expires));
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $parameters
|
||||
*/
|
||||
private function url(Page $page, array $parameters, \DateTimeInterface $expires): string
|
||||
{
|
||||
return $page->isHome()
|
||||
? URL::temporarySignedRoute('home', $expires, $parameters)
|
||||
: URL::temporarySignedRoute('page', $expires, ['slug' => $page->slug, ...$parameters]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('users:promote-operator {email : E-Mail-Adresse}')]
|
||||
#[Description('Grant the operator flag. The account keeps its password, two-factor setup and any landlord role.')]
|
||||
class PromoteOperator extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$email = mb_strtolower(trim((string) $this->argument('email')));
|
||||
$user = User::query()->where('email', $email)->first();
|
||||
|
||||
if ($user === null) {
|
||||
$this->error('Kein Benutzer mit dieser E-Mail.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$user->forceFill(['is_operator' => true])->save();
|
||||
|
||||
$this->info("{$email} ist jetzt Betreiber. Eine bestehende Mandanten-Rolle bleibt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
#[Signature('mail:test {to? : Empfänger (Standard: Benachrichtigungsadresse)}')]
|
||||
#[Description('Send a test e-mail through the configured mailer and report delivery errors (e.g. SMTP login)')]
|
||||
class SendTestMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$to = (string) ($this->argument('to') ?: Settings::notificationRecipients()[0] ?? config('fewo.owner.email'));
|
||||
$mailer = (string) config('mail.default');
|
||||
$redirect = Settings::mailRedirect();
|
||||
|
||||
$this->line("Versandweg: {$mailer}".($mailer === 'smtp' ? ' ('.config('mail.mailers.smtp.host').':'.config('mail.mailers.smtp.port').')' : '').' · Absender: '.config('mail.from.address'));
|
||||
if (filled($redirect)) {
|
||||
$this->line("Umleitung aktiv: die Mail geht an {$redirect} statt an {$to}.");
|
||||
}
|
||||
if ($mailer === 'log') {
|
||||
$this->warn('Versandweg "log": es wird nichts zugestellt. Zum echten Versand MAIL_MAILER=smtp und MAIL_PASSWORD setzen (docs/BETRIEB.md §5a).');
|
||||
}
|
||||
|
||||
try {
|
||||
Mail::raw("Testmail der Ferienwohnung Stommer\n\nGesendet am ".now()->format('d.m.Y H:i:s').' von '.config('app.url').".\nWenn diese Mail ankommt, funktioniert der Versand.", function ($message) use ($to): void {
|
||||
$message->to($to)->subject('Testmail Ferienwohnung Stommer – '.now()->format('d.m.Y H:i'));
|
||||
});
|
||||
} catch (Throwable $exception) {
|
||||
$this->error('Versand fehlgeschlagen: '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if ($mailer === 'log') {
|
||||
$this->line('Mail erzeugt, aber nicht zugestellt (Versandweg "log").');
|
||||
} else {
|
||||
$this->info('Übergeben an den Mailserver – bitte Posteingang (und Spam-Ordner) prüfen.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Photo;
|
||||
use App\Support\StripImageMetadata;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
|
||||
#[Signature('photos:strip-metadata {--force : Auch bereits bereinigte Fotos erneut bearbeiten}')]
|
||||
#[Description('Remove metadata (GPS position, camera data) from all stored original photos – new uploads are cleaned automatically')]
|
||||
class StripPhotoMetadata extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$cleaned = Media::query()->where('collection_name', Photo::COLLECTION)->get()
|
||||
->filter(fn (Media $media): bool => StripImageMetadata::strip($media, (bool) $this->option('force')))
|
||||
->count();
|
||||
|
||||
$this->info("{$cleaned} Original-Foto(s) bereinigt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Models\Channel;
|
||||
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')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(SyncChannel $syncChannel): int
|
||||
{
|
||||
$channels = Channel::query()->active()
|
||||
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
|
||||
->get()
|
||||
->filter(fn (Channel $channel): bool => $channel->importsOccupations());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
$log = $syncChannel->handle($channel);
|
||||
|
||||
$log->successful
|
||||
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
|
||||
: $this->error("✗ {$channel->name}: {$log->message}");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
<?php
|
||||
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* The rental contract as PDF. As a draft it is part of the offer (offer_path, one file per offer version);
|
||||
* the final contract is generated at confirmation (contract_path). Both are stored, so later changes of
|
||||
* texts or prices do not alter a document the guest already received.
|
||||
*/
|
||||
class RentalContract
|
||||
{
|
||||
private const DISK = 'local';
|
||||
|
||||
public function generate(Booking $booking, bool $draft = false): string
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$path = $draft
|
||||
? "contracts/Angebot-{$booking->reference}-v{$booking->offer_version}.pdf"
|
||||
: "contracts/Mietvertrag-{$booking->reference}.pdf";
|
||||
|
||||
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]);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function absolutePath(Booking $booking, bool $draft = false): ?string
|
||||
{
|
||||
$path = $draft ? $booking->offer_path : $booking->contract_path;
|
||||
|
||||
return $path && Storage::disk(self::DISK)->exists($path) ? Storage::disk(self::DISK)->path($path) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Filament\Pages\PricesAndOffers;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
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 Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How much of the admin a user sees. It only shapes the menu – what a user may do is decided by the role.
|
||||
*/
|
||||
enum AdminMode: string implements HasDescription, HasLabel
|
||||
{
|
||||
case Simple = 'simple';
|
||||
case Expert = 'expert';
|
||||
|
||||
/**
|
||||
* Menu entries of the simple mode: day-to-day work with requests, bookings, contracts and the calendar.
|
||||
*
|
||||
* @var list<class-string>
|
||||
*/
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
BookingResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Einfache Ansicht',
|
||||
self::Expert => 'Expertenansicht',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Portal-Aufgaben, Bewertungen, Fotos',
|
||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Portale, Webseite, System',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource or page appears in the menu in this mode.
|
||||
*
|
||||
* @param class-string $class
|
||||
*/
|
||||
public function shows(string $class): bool
|
||||
{
|
||||
return $this === self::Expert || in_array($class, self::SIMPLE_NAVIGATION, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Label of the user menu entry that switches to this mode.
|
||||
*/
|
||||
public function switchLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Zur einfachen Ansicht wechseln',
|
||||
self::Expert => 'Zur Expertenansicht wechseln',
|
||||
};
|
||||
}
|
||||
|
||||
public function other(): self
|
||||
{
|
||||
return $this === self::Simple ? self::Expert : self::Simple;
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,13 @@
|
||||
|
||||
enum BookingStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** Guest request; the dates are held until hold_expires_at. */
|
||||
/** Non-binding guest request; the dates are held until hold_expires_at. */
|
||||
case Reserved = 'reserved';
|
||||
|
||||
/** The landlord sent an offer; the dates are held until hold_expires_at (= end of the offer's validity). */
|
||||
case OfferSent = 'offer_sent';
|
||||
|
||||
/** Binding booking: the guest accepted the offer (or the landlord confirmed directly). */
|
||||
case Confirmed = 'confirmed';
|
||||
case DepositPaid = 'deposit_paid';
|
||||
case Paid = 'paid';
|
||||
@@ -20,7 +25,8 @@ enum BookingStatus: string implements HasColor, HasLabel
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'Vorreserviert',
|
||||
self::Reserved => 'Anfrage (vorgemerkt)',
|
||||
self::OfferSent => 'Angebot gesendet',
|
||||
self::Confirmed => 'Bestätigt',
|
||||
self::DepositPaid => 'Anzahlung erhalten',
|
||||
self::Paid => 'Bezahlt',
|
||||
@@ -35,12 +41,23 @@ public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'warning',
|
||||
self::OfferSent => 'primary',
|
||||
self::Confirmed, self::DepositPaid => 'info',
|
||||
self::Paid, self::Completed => 'success',
|
||||
self::Declined, self::Expired, self::Cancelled => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar while their hold time (hold_expires_at) runs.
|
||||
*
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function holding(): array
|
||||
{
|
||||
return [self::Reserved, self::OfferSent];
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar regardless of any hold time.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskAction: string implements HasColor, HasLabel
|
||||
{
|
||||
case Block = 'block';
|
||||
case Unblock = 'unblock';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'Sperren',
|
||||
self::Unblock => 'Freigeben',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Block => 'danger',
|
||||
self::Unblock => 'success',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum ChannelTaskStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
case Open = 'open';
|
||||
case Done = 'done';
|
||||
case Dismissed = 'dismissed';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'Offen',
|
||||
self::Done => 'Erledigt',
|
||||
self::Dismissed => 'Verworfen',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Open => 'warning',
|
||||
self::Done => 'success',
|
||||
self::Dismissed => 'gray',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,9 @@ enum DiscountType: string implements HasLabel
|
||||
/** discount_value = number of cheapest nights that are free */
|
||||
case FreeNights = 'free_nights';
|
||||
|
||||
/** discount_value = package price in euro cents for all nights of the stay */
|
||||
case FixedStayPrice = 'fixed_stay_price';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
@@ -25,6 +28,12 @@ public function getLabel(): string
|
||||
self::AmountPerStay => 'Rabatt in € pro Aufenthalt',
|
||||
self::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
self::FreeNights => 'Gratis-Nächte',
|
||||
self::FixedStayPrice => 'Pauschalpreis für den Aufenthalt',
|
||||
};
|
||||
}
|
||||
|
||||
public function isMoney(): bool
|
||||
{
|
||||
return in_array($this, [self::AmountPerStay, self::NightlyRate, self::FixedStayPrice], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How an offer finds its stays. All kinds are priced by PriceCalculator and advertised by OfferShowcase.
|
||||
*/
|
||||
enum OfferKind: string implements HasDescription, HasLabel
|
||||
{
|
||||
/** Conditions only (last minute, early bird, from N nights, weekend …). */
|
||||
case Rule = 'rule';
|
||||
|
||||
/** One fixed arrival and departure (stay_from / stay_until), e.g. a week as a package. */
|
||||
case FixedDates = 'fixed_dates';
|
||||
|
||||
/** Free gaps of at most max_gap_nights between two occupations, found automatically. */
|
||||
case GapFiller = 'gap_filler';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Rabattaktion (nach Bedingungen)',
|
||||
self::FixedDates => 'Fester Termin',
|
||||
self::GapFiller => 'Lückenfüller (Kalenderlücken)',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Gilt für jeden Aufenthalt, der die Bedingungen erfüllt, z. B. Last Minute oder „ab 3 Nächten −10 %“.',
|
||||
self::FixedDates => 'Ein bestimmter Zeitraum, z. B. „7 Nächte vom 07. bis 14.11.“ – wird nur beworben, solange er frei ist.',
|
||||
self::GapFiller => 'Findet freie Lücken zwischen zwei Buchungen automatisch und bewirbt sie mit konkreten Terminen.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PaymentMethod: string implements HasLabel
|
||||
{
|
||||
case Transfer = 'transfer';
|
||||
case Cash = 'cash';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Transfer => 'Überweisung',
|
||||
self::Cash => 'Bar',
|
||||
self::Other => 'Sonstiges',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* What a role may do inside the current landlord. A new role is a new case on UserRole plus a list here.
|
||||
*/
|
||||
enum Permission: string
|
||||
{
|
||||
case Bookings = 'bookings';
|
||||
case Properties = 'properties';
|
||||
case Guests = 'guests';
|
||||
case Reviews = 'reviews';
|
||||
case Channels = 'channels';
|
||||
case Content = 'content';
|
||||
case Users = 'users';
|
||||
case Settings = 'settings';
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasColor;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** A new block was created from the e-mail. */
|
||||
case Blocked = 'blocked';
|
||||
|
||||
/** The period was already blocked (e.g. by the calendar sync). */
|
||||
case AlreadyKnown = 'already_known';
|
||||
|
||||
/** A cancellation released a block created from an e-mail. */
|
||||
case Released = 'released';
|
||||
|
||||
case NeedsReview = 'needs_review';
|
||||
case Reviewed = 'reviewed';
|
||||
case Ignored = 'ignored';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blocked => 'Gesperrt',
|
||||
self::AlreadyKnown => 'Bereits gesperrt',
|
||||
self::Released => 'Freigegeben',
|
||||
self::NeedsReview => 'Bitte prüfen',
|
||||
self::Reviewed => 'Geprüft',
|
||||
self::Ignored => 'Ignoriert',
|
||||
};
|
||||
}
|
||||
|
||||
public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Blocked, self::Released => 'success',
|
||||
self::AlreadyKnown, self::Reviewed, self::Ignored => 'gray',
|
||||
self::NeedsReview => 'danger',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
enum PortalEmailType: string implements HasLabel
|
||||
{
|
||||
case Booking = 'booking';
|
||||
case Cancellation = 'cancellation';
|
||||
case Inquiry = 'inquiry';
|
||||
case Unknown = 'unknown';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Booking => 'Buchung',
|
||||
self::Cancellation => 'Stornierung',
|
||||
self::Inquiry => 'Anfrage',
|
||||
self::Unknown => 'Unbekannt',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,14 @@ enum QuoteLineType: string
|
||||
case Extra = 'extra';
|
||||
case Discount = 'discount';
|
||||
|
||||
/** Manual price change by the landlord in an offer (negative = reduction). */
|
||||
case Adjustment = 'adjustment';
|
||||
|
||||
/**
|
||||
* Whether the line counts towards the rent on which the deposit is calculated.
|
||||
*/
|
||||
public function isRent(): bool
|
||||
{
|
||||
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount], true);
|
||||
return in_array($this, [self::Accommodation, self::ExtraGuest, self::Discount, self::Adjustment], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* "How did you find us?" – answered by the guest in the request form.
|
||||
*/
|
||||
enum ReferralSource: string implements HasLabel
|
||||
{
|
||||
case SearchEngine = 'search_engine';
|
||||
case FewoDirekt = 'fewo_direkt';
|
||||
case Ostseeklar = 'ostseeklar';
|
||||
case FerienUndWohnen = 'ferienundwohnen';
|
||||
case TouristInformation = 'tourist_information';
|
||||
case SocialMedia = 'social_media';
|
||||
case Recommendation = 'recommendation';
|
||||
case ReturningGuest = 'returning_guest';
|
||||
case Other = 'other';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::SearchEngine => 'Suchmaschine (z. B. Google)',
|
||||
self::FewoDirekt => 'FeWo-direkt',
|
||||
self::Ostseeklar => 'Ostseeklar',
|
||||
self::FerienUndWohnen => 'ferienundwohnen.de',
|
||||
self::TouristInformation => 'Tourist-Information Kühlungsborn',
|
||||
self::SocialMedia => 'Social Media',
|
||||
self::Recommendation => 'Empfehlung',
|
||||
self::ReturningGuest => 'Ich war schon Gast',
|
||||
self::Other => 'Sonstiges',
|
||||
};
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -14,7 +14,7 @@ enum UserRole: string implements HasDescription, HasLabel
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => 'Administrator',
|
||||
self::Admin => 'Mandanten-Administrator',
|
||||
self::Rentals => 'Vermietung',
|
||||
self::Content => 'Inhalte',
|
||||
};
|
||||
@@ -23,9 +23,37 @@ public function getLabel(): string
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => 'Alles, inklusive Benutzerverwaltung',
|
||||
self::Admin => 'Alles im eigenen Mandanten, inklusive Benutzerverwaltung',
|
||||
self::Rentals => 'Buchungen, Gäste, Preise, Angebote und Bewertungen',
|
||||
self::Content => 'Bilder, Texte, FAQ, Hinweise und Bewertungen',
|
||||
};
|
||||
}
|
||||
|
||||
public function grants(Permission $permission): bool
|
||||
{
|
||||
return in_array($permission, $this->permissions(), true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Abilities inside the current landlord. The operator is not a role here.
|
||||
*
|
||||
* @return list<Permission>
|
||||
*/
|
||||
public function permissions(): array
|
||||
{
|
||||
return match ($this) {
|
||||
self::Admin => Permission::cases(),
|
||||
self::Rentals => [
|
||||
Permission::Bookings,
|
||||
Permission::Properties,
|
||||
Permission::Guests,
|
||||
Permission::Reviews,
|
||||
Permission::Channels,
|
||||
],
|
||||
self::Content => [
|
||||
Permission::Content,
|
||||
Permission::Reviews,
|
||||
],
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,16 @@ public static function notAvailable(): self
|
||||
return new self('Der gewünschte Zeitraum ist leider nicht mehr frei.');
|
||||
}
|
||||
|
||||
public static function offerExpired(): self
|
||||
{
|
||||
return new self('Dieses Angebot ist nicht mehr gültig. Bitte melden Sie sich bei uns – gern erstellen wir Ihnen ein neues Angebot.');
|
||||
}
|
||||
|
||||
public static function offerOutdated(): self
|
||||
{
|
||||
return new self('Zu dieser Anfrage gibt es inzwischen ein aktualisiertes Angebot. Bitte verwenden Sie den Link aus unserer neuesten E-Mail.');
|
||||
}
|
||||
|
||||
public static function invalidTransition(string $statusLabel, string $action): self
|
||||
{
|
||||
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Enums\AdminMode;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Hides the menu entry in the simple admin mode unless it is part of AdminMode::SIMPLE_NAVIGATION.
|
||||
* The page stays reachable by URL; access is governed by the policies.
|
||||
*/
|
||||
trait FollowsAdminMode
|
||||
{
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
$mode = $user instanceof User ? $user->adminMode() : AdminMode::Expert;
|
||||
|
||||
return parent::shouldRegisterNavigation() && $mode->shows(static::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Forms\Components;
|
||||
|
||||
use App\Models\Photo;
|
||||
use Filament\Forms\Components\Select;
|
||||
|
||||
/**
|
||||
* Chooses website photos with a thumbnail next to each description, grouped by category,
|
||||
* so editors see what they insert.
|
||||
*/
|
||||
class PhotoSelect extends Select
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this
|
||||
->options(fn (): array => self::photoOptions())
|
||||
->allowHtml()
|
||||
->searchable()
|
||||
->native(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public static function photoOptions(): array
|
||||
{
|
||||
return Photo::query()->with('media')->orderBy('category')->orderBy('sort_order')->get()
|
||||
->groupBy(fn (Photo $photo): string => $photo->category->getLabel())
|
||||
->map(fn ($photos): array => $photos->mapWithKeys(fn (Photo $photo): array => [$photo->id => self::optionLabel($photo)])->all())
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function optionLabel(Photo $photo): string
|
||||
{
|
||||
$thumbnail = $photo->url('sm');
|
||||
$image = $thumbnail !== ''
|
||||
? '<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>';
|
||||
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$hidden.'</span></span>';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator;
|
||||
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\ListTenants;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class TenantResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Tenant::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice;
|
||||
|
||||
protected static ?string $modelLabel = 'Mandant';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Mandanten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Mandanten';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('slug')
|
||||
->label('Kurzname')
|
||||
->required()
|
||||
->alphaDash()
|
||||
->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),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kurzname'),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('openAdmin')
|
||||
->label('Im Admin öffnen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->action(function (Tenant $record) {
|
||||
TenantAccessLog::query()->create([
|
||||
'tenant_id' => $record->id,
|
||||
'user_id' => auth()->id(),
|
||||
]);
|
||||
|
||||
$domain = $record->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
|
||||
|
||||
return redirect(is_string($domain) && $domain !== '' ? 'https://'.$domain.'/admin' : url('/admin'));
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListTenants::route('/'),
|
||||
'create' => CreateTenant::route('/create'),
|
||||
'edit' => EditTenant::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListTenants extends ListRecords
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Photo;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Support\Content;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
@@ -29,6 +30,8 @@
|
||||
*/
|
||||
class EditContent extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPencilSquare;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
@@ -39,7 +42,7 @@ class EditContent extends Page
|
||||
|
||||
protected static ?string $slug = 'texte';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, ?string> */
|
||||
public array $data = [];
|
||||
@@ -120,10 +123,8 @@ private function field(string $key, array $field): TextInput|Textarea|RichEditor
|
||||
'richtext' => RichEditor::make($name)
|
||||
->label($field['label'])
|
||||
->toolbarButtons([['bold', 'italic', 'link'], ['h2', 'h3'], ['bulletList', 'orderedList'], ['undo', 'redo']]),
|
||||
'photo' => Select::make($name)
|
||||
'photo' => PhotoSelect::make($name)
|
||||
->label($field['label'])
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->searchable()
|
||||
->placeholder('Kein Bild gewählt')
|
||||
->helperText('Bilder verwalten Sie unter „Webseite › Bilder“.'),
|
||||
default => TextInput::make($name)->label($field['label'])->maxLength(255),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Support\Settings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Operating mode (test mode sends every e-mail to one test recipient only; live delivers to the real recipients)
|
||||
* and the addresses of the internal communication (notifications, contact/reply-to, sender). Administrators only.
|
||||
*/
|
||||
class Operations extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?string $navigationLabel = 'Betrieb';
|
||||
|
||||
protected static ?string $title = 'Betrieb';
|
||||
|
||||
protected static ?string $slug = 'betrieb';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
/** @var array<string, ?string> */
|
||||
public array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill([
|
||||
'mode' => Settings::get(Settings::MODE, Settings::MODE_TEST),
|
||||
'test_recipient' => Settings::get(Settings::TEST_RECIPIENT) ?? auth()->user()?->email,
|
||||
'notification_recipients' => Settings::notificationRecipients(),
|
||||
'contact_email' => config('fewo.owner.email'),
|
||||
'sender_name' => config('mail.from.name'),
|
||||
'sender_email' => config('mail.from.address'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Section::make('E-Mail-Versand')
|
||||
->description('Im Testbetrieb gehen alle E-Mails – Eingangsbestätigungen, Angebote, Bestätigungen, Erinnerungen, Benachrichtigungen – ausschließlich an die Testadresse, egal welche Adresse auf der Webseite eingetragen wurde.')
|
||||
->schema([
|
||||
Radio::make('mode')
|
||||
->label('Betriebsart')
|
||||
->options([
|
||||
Settings::MODE_TEST => 'Testbetrieb – alle E-Mails an die Testadresse',
|
||||
Settings::MODE_LIVE => 'Scharf geschaltet – E-Mails an Gäste und Vermieterin',
|
||||
])
|
||||
->required()
|
||||
->live(),
|
||||
TextInput::make('test_recipient')
|
||||
->label('Testadresse')
|
||||
->email()
|
||||
->required(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST)
|
||||
->visible(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST),
|
||||
Text::make(fn (): string => filled(config('fewo.mail_redirect_to'))
|
||||
? 'Hinweis: Auf diesem Server ist zusätzlich FEWO_MAIL_REDIRECT_TO='.config('fewo.mail_redirect_to').' gesetzt – diese Umleitung gilt immer, auch wenn hier scharf geschaltet ist.'
|
||||
: ''),
|
||||
]),
|
||||
Section::make('Adressen der internen Kommunikation')
|
||||
->description('Gelten sofort für alle E-Mails, die Webseite und den Mietvertrag. Im Testbetrieb gehen trotzdem alle E-Mails nur an die Testadresse.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TagsInput::make('notification_recipients')
|
||||
->label('Benachrichtigungen an')
|
||||
->helperText('Neue Anfragen, angenommene/abgelehnte Angebote, abgelaufene Fristen, Bewertungen, Portal-Mails und -Aufgaben, Kopie der Zahlungserinnerungen. Mehrere Adressen möglich (Enter nach jeder Adresse).')
|
||||
->placeholder('adresse@beispiel.de')
|
||||
->nestedRecursiveRules(['email'])
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('contact_email')
|
||||
->label('Kontakt- und Antwortadresse')
|
||||
->helperText('Steht auf der Webseite und im Mietvertrag; Antworten der Gäste auf unsere E-Mails gehen hierhin.')
|
||||
->email()
|
||||
->required(),
|
||||
TextInput::make('sender_name')
|
||||
->label('Absendername')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
TextInput::make('sender_email')
|
||||
->label('Absenderadresse')
|
||||
->helperText(fn (): string => 'Muss das Postfach sein, mit dem der Server versendet (SMTP-Anmeldung: '.(config('mail.mailers.smtp.username') ?: 'nicht gesetzt').') – sonst lehnt Strato den Versand ab.')
|
||||
->email()
|
||||
->required(),
|
||||
Text::make(fn (Get $get): string => filled(config('mail.mailers.smtp.username')) && filled($get('sender_email')) && strcasecmp((string) $get('sender_email'), (string) config('mail.mailers.smtp.username')) !== 0
|
||||
? '⚠ Die Absenderadresse weicht vom SMTP-Postfach ('.config('mail.mailers.smtp.username').') ab. Strato stellt solche E-Mails in der Regel nicht zu.'
|
||||
: '')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && Settings::get(Settings::MODE) !== Settings::MODE_LIVE) {
|
||||
Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send();
|
||||
} else {
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
Settings::save([
|
||||
Settings::MODE => $data['mode'],
|
||||
Settings::TEST_RECIPIENT => $data['test_recipient'] ?? Settings::get(Settings::TEST_RECIPIENT),
|
||||
Settings::NOTIFICATION_RECIPIENTS => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
|
||||
Settings::CONTACT_EMAIL => $data['contact_email'],
|
||||
Settings::SENDER_NAME => $data['sender_name'],
|
||||
Settings::SENDER_EMAIL => $data['sender_email'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
|
||||
use App\Models\Property;
|
||||
use BackedEnum;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Livewire;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Livewire\Attributes\Url;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* The yearly price work in one place, without the other apartment settings: seasons & prices,
|
||||
* special offers & promo codes, extras. Reuses the relation managers of the apartment.
|
||||
*/
|
||||
class PricesAndOffers extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCurrencyEuro;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $title = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $slug = 'preise-und-angebote';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
#[Url(as: 'wohnung')]
|
||||
public ?int $propertyId = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id');
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
$property = Property::find($this->propertyId);
|
||||
if ($property === null) {
|
||||
return $schema->components([Text::make('Es ist noch keine Wohnung angelegt (Expertenansicht › Wohnungen).')]);
|
||||
}
|
||||
|
||||
$context = ['ownerRecord' => $property, 'pageClass' => EditProperty::class];
|
||||
|
||||
return $schema->components([
|
||||
Select::make('propertyId')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->live()
|
||||
->afterStateUpdated(fn () => $this->redirect(static::getUrl(['wohnung' => $this->propertyId])))
|
||||
->visible(fn (): bool => Property::query()->count() > 1),
|
||||
Tabs::make('prices')
|
||||
->persistTabInQueryString()
|
||||
->tabs([
|
||||
Tab::make('Saisons & Preise')->icon(Heroicon::OutlinedCalendar)->schema([
|
||||
Livewire::make(SeasonsRelationManager::class, $context)->key("seasons-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Sonderangebote & Rabattcodes')->icon(Heroicon::OutlinedSparkles)->schema([
|
||||
Livewire::make(SpecialOffersRelationManager::class, $context)->key("offers-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Extras')->icon(Heroicon::OutlinedGift)->schema([
|
||||
Livewire::make(ExtrasRelationManager::class, $context)->key("extras-{$property->id}"),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Amenities;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Amenities\Pages\CreateAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\EditAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\ListAmenities;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class AmenityResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Amenity::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedListBullet;
|
||||
@@ -27,7 +30,7 @@ class AmenityResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Ausstattung';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Appearances\Pages\CreateAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\EditAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\ListAppearances;
|
||||
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
|
||||
use App\Filament\Resources\Appearances\Tables\AppearancesTable;
|
||||
use App\Models\Appearance;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class AppearanceResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Appearance::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
|
||||
protected static ?string $modelLabel = 'Erscheinungsbild';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Erscheinungsbilder';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return AppearanceForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return AppearancesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListAppearances::route('/'),
|
||||
'create' => CreateAppearance::route('/create'),
|
||||
'edit' => EditAppearance::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateAppearance extends CreateRecord
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditAppearance extends EditRecord
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Pages;
|
||||
|
||||
use App\Filament\Resources\Appearances\AppearanceResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListAppearances extends ListRecords
|
||||
{
|
||||
protected static string $resource = AppearanceResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Themes\SectionRegistry;
|
||||
use App\Themes\Sections\Section as SectionBlock;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Fieldset;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
class AppearanceForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Section::make('Zeitraum')
|
||||
->description('Wiederholt sich jedes Jahr. Überschneiden sich Zeiträume, gilt die höhere Priorität (z. B. Silvester vor Winter). Ohne Zeitraum greift das Standard-Erscheinungsbild.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->placeholder('z. B. Weihnachten')->required()->maxLength(60),
|
||||
Select::make('site_id')
|
||||
->label('Website')
|
||||
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Site::query()->where('is_default', true)->value('id'))
|
||||
->required(),
|
||||
self::dayField('starts_md', 'Von (TT.MM.)'),
|
||||
self::dayField('ends_md', 'Bis einschließlich (TT.MM.)'),
|
||||
TextInput::make('priority')->label('Priorität')->integer()->minValue(0)->default(10),
|
||||
Toggle::make('is_default')->label('Standard (wenn kein Zeitraum passt)')->inline(false),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
|
||||
]),
|
||||
Section::make('Titelbild')
|
||||
->description('Gilt für alle Titelbereiche und als Vorschaubild beim Teilen in sozialen Medien – einzelne Bausteine können unten ein eigenes Bild bekommen. Sonderangebote werden unabhängig vom Erscheinungsbild beworben (Wohnung › Sonderangebote).')
|
||||
->schema([
|
||||
PhotoSelect::make('hero_photo_id')
|
||||
->label('Titelbild')
|
||||
->placeholder('Bild der Seite verwenden'),
|
||||
]),
|
||||
Section::make('Bilder je Baustein')
|
||||
->description('Für jeden Baustein mit Bildern ein eigenes Saisonbild wählen. Leer = Bild aus der Seite. Neue Bilder laden Sie unter Webseite › Fotos hoch.')
|
||||
->collapsible()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => self::sectionPhotoFields($get('site_id'))),
|
||||
Section::make('Texte')
|
||||
->description('Leer lassen = Text der Seite bzw. kein Banner.')
|
||||
->columns(2)
|
||||
->collapsible()
|
||||
->schema(collect(Appearance::OVERRIDABLE)
|
||||
->map(fn (string $label, string $key) => TextInput::make('overrides.'.$key)->label($label)->maxLength(255))
|
||||
->values()
|
||||
->all()),
|
||||
Section::make('Farben')
|
||||
->description('Nur ändern, was anders aussehen soll; leere Felder übernehmen die Farben des Themes.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->schema(fn (Get $get): array => self::tokenFields($get('site_id'))),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* One group per page and one field set per placed section that has photo slots
|
||||
* (see Section::photoSlots); stored in section_photos[<section id>][<slot>].
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
public static function sectionPhotoFields(int|string|null $siteId): array
|
||||
{
|
||||
$registry = app(SectionRegistry::class);
|
||||
$pages = Page::query()->where('site_id', $siteId)->orderBy('sort_order')->get();
|
||||
|
||||
$groups = [];
|
||||
foreach ($pages as $page) {
|
||||
$fieldsets = [];
|
||||
foreach ($page->sections ?? [] as $stored) {
|
||||
$class = $registry->all()[$stored['type'] ?? ''] ?? null;
|
||||
$sectionId = $stored['data']['id'] ?? null;
|
||||
if ($class === null || blank($sectionId) || $class::photoSlots() === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = [];
|
||||
foreach ($class::photoSlots() as $slot => $definition) {
|
||||
$field = PhotoSelect::make("section_photos.{$sectionId}.{$slot}")
|
||||
->label($definition['label'])
|
||||
->placeholder('Standard (Bild aus der Seite)')
|
||||
->multiple($definition['type'] !== SectionBlock::SLOT_SINGLE);
|
||||
if (isset($definition['max'])) {
|
||||
$field->maxItems($definition['max']);
|
||||
}
|
||||
$fields[] = $field;
|
||||
|
||||
if ($definition['type'] === SectionBlock::SLOT_COLLECTION) {
|
||||
$fields[] = Radio::make("section_photos.{$sectionId}.mode")
|
||||
->label('Saisonbilder')
|
||||
->options(['replace' => 'ersetzen die Bilder des Bausteins', 'prepend' => 'kommen zuerst, danach die übrigen'])
|
||||
->default('replace')
|
||||
->inline();
|
||||
}
|
||||
}
|
||||
|
||||
$fieldsets[] = Fieldset::make(collect([$class::label(), $class::summary($stored['data'] ?? [])])->filter()->implode(' · '))
|
||||
->columns(1)
|
||||
->schema($fields);
|
||||
}
|
||||
|
||||
if ($fieldsets !== []) {
|
||||
$groups[] = Section::make($page->title)->compact()->collapsible()->schema($fieldsets);
|
||||
}
|
||||
}
|
||||
|
||||
return $groups ?: [Text::make('Auf den Seiten gibt es noch keine Bausteine mit Bildern.')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<ColorPicker>
|
||||
*/
|
||||
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens', ?string $themeKey = null): array
|
||||
{
|
||||
$theme = $themeKey ?: (Site::find($siteId)?->theme ?? config('themes.base'));
|
||||
|
||||
return collect(app(ThemeRegistry::class)->tokens($theme))
|
||||
->map(fn (array $token, string $key): ColorPicker => ColorPicker::make("{$statePath}.{$key}")->label($token['label'])->placeholder($token['default']))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* Day of the year entered as "TT.MM." and stored as "MM-DD".
|
||||
*/
|
||||
private static function dayField(string $name, string $label): TextInput
|
||||
{
|
||||
return TextInput::make($name)
|
||||
->label($label)
|
||||
->placeholder('24.12.')
|
||||
->formatStateUsing(fn (?string $state): ?string => $state ? substr($state, 3, 2).'.'.substr($state, 0, 2).'.' : null)
|
||||
->dehydrateStateUsing(fn (?string $state): ?string => self::toMonthDay($state))
|
||||
->rule(fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if (filled($value) && self::toMonthDay((string) $value) === null) {
|
||||
$fail('Bitte als TT.MM. eingeben, z. B. 24.12.');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private static function toMonthDay(?string $value): ?string
|
||||
{
|
||||
if (blank($value) || ! preg_match('/^\s*(\d{1,2})\.(\d{1,2})\.?\s*$/', $value, $match)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return checkdate((int) $match[2], (int) $match[1], 2024) ? sprintf('%02d-%02d', $match[2], $match[1]) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Tables;
|
||||
|
||||
use App\Models\Appearance;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class AppearancesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('priority', 'desc')
|
||||
->description('Die Webseite wechselt automatisch nach Datum. Mit „Vorschau“ sehen Sie ein Erscheinungsbild schon vorher.')
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Erscheinungsbild')->weight('medium'),
|
||||
TextColumn::make('period')
|
||||
->label('Zeitraum')
|
||||
->state(fn (Appearance $record): string => $record->is_default && ! $record->starts_md ? 'Standard' : self::day($record->starts_md).' – '.self::day($record->ends_md)),
|
||||
TextColumn::make('priority')->label('Priorität')->sortable(),
|
||||
IconColumn::make('current')
|
||||
->label('Jetzt aktiv')
|
||||
->boolean()
|
||||
->state(fn (Appearance $record): bool => $record->site?->appearanceOn(today())?->is($record) ?? false),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('preview')
|
||||
->label('Vorschau')
|
||||
->icon(Heroicon::OutlinedEye)
|
||||
->color('gray')
|
||||
->url(fn (Appearance $record): string => URL::temporarySignedRoute('home', now()->addDay(), ['vorschau' => $record->id]), shouldOpenInNewTab: true),
|
||||
EditAction::make(),
|
||||
DeleteAction::make()->visible(fn (Appearance $record): bool => ! $record->is_default),
|
||||
]);
|
||||
}
|
||||
|
||||
private static function day(?string $monthDay): string
|
||||
{
|
||||
return $monthDay ? substr($monthDay, 3, 2).'.'.substr($monthDay, 0, 2).'.' : '?';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Property;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* All blocked periods of all apartments in one place (own use, renovation, portal occupations).
|
||||
* Portal and e-mail blocks are maintained by the sync and can only be viewed here.
|
||||
*/
|
||||
class BlockedPeriodResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = BlockedPeriod::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedNoSymbol;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Sperrzeit';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sperrzeiten';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->where('is_active', true)->value('id'))
|
||||
->required()
|
||||
->columnSpanFull()
|
||||
->hidden(fn (): bool => Property::query()->count() <= 1)
|
||||
->dehydratedWhenHidden(),
|
||||
DatePicker::make('starts_on')->label('Von (erste gesperrte Nacht)')->required(),
|
||||
DatePicker::make('ends_on')->label('Bis (erster freier Tag)')->after('starts_on')->required(),
|
||||
TextInput::make('reason')
|
||||
->label('Grund')
|
||||
->placeholder('z. B. Eigennutzung, Renovierung')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->description('Zeiträume, in denen die Wohnung nicht vermietet wird. Belegungen aus Portalen erscheinen hier automatisch.')
|
||||
->defaultSort('starts_on')
|
||||
->columns([
|
||||
TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y')->sortable(),
|
||||
TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'),
|
||||
TextColumn::make('reason')->label('Grund')->placeholder('–'),
|
||||
TextColumn::make('property.name')->label('Wohnung')->visible(fn (): bool => Property::query()->count() > 1),
|
||||
TextColumn::make('source')
|
||||
->label('Quelle')
|
||||
->formatStateUsing(fn (string $state): string => match ($state) {
|
||||
'manual' => 'von Hand',
|
||||
'channel' => 'Portal-Kalender',
|
||||
'email' => 'Portal-E-Mail',
|
||||
default => $state,
|
||||
})
|
||||
->badge(),
|
||||
])
|
||||
->filters([
|
||||
Filter::make('upcoming')
|
||||
->label('Nur kommende')
|
||||
->default()
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ManageBlockedPeriods::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods\Pages;
|
||||
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
|
||||
class ManageBlockedPeriods extends ManageRecords
|
||||
{
|
||||
protected static string $resource = BlockedPeriodResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()->label('Zeitraum sperren')->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,11 @@
|
||||
namespace App\Filament\Resources\Bookings;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingForm;
|
||||
use App\Filament\Resources\Bookings\Schemas\BookingInfolist;
|
||||
use App\Filament\Resources\Bookings\Tables\BookingsTable;
|
||||
@@ -19,6 +21,8 @@
|
||||
|
||||
class BookingResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Booking::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
|
||||
@@ -63,6 +67,13 @@ public static function getNavigationBadgeColor(): string
|
||||
return 'warning';
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
PaymentsRelationManager::class,
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
|
||||
@@ -4,18 +4,31 @@
|
||||
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Actions\DeclineBooking;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property Booking $record
|
||||
@@ -32,14 +45,92 @@ public function getTitle(): string
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('confirm')
|
||||
->label('Bestätigen')
|
||||
->icon(Heroicon::OutlinedCheckCircle)
|
||||
Action::make('sendOffer')
|
||||
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden')
|
||||
->icon(Heroicon::OutlinedPaperAirplane)
|
||||
->color('success')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->modalHeading('Angebot an den Gast senden')
|
||||
->modalDescription('Der Gast erhält das Angebot mit Vertragsentwurf per E-Mail und kann es über einen Link annehmen oder ablehnen. Erst mit seiner Annahme ist die Buchung verbindlich.')
|
||||
->modalSubmitActionLabel('Angebot senden')
|
||||
->modalWidth('3xl')
|
||||
->fillForm(fn (): array => [
|
||||
'arrival' => $this->record->arrival->toDateString(),
|
||||
'departure' => $this->record->departure->toDateString(),
|
||||
'guests' => $this->record->guests,
|
||||
'promo_code' => $this->record->promo_code,
|
||||
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
|
||||
'price_adjustment_label' => $this->record->price_adjustment_label,
|
||||
'valid_until' => now()->addHours($this->record->property->hold_hours)->format('Y-m-d H:i'),
|
||||
'offer_message' => $this->record->offer_message,
|
||||
'guest' => $this->record->guest->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']),
|
||||
])
|
||||
->schema([
|
||||
Section::make('Termin')->columns(3)->schema([
|
||||
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
|
||||
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
|
||||
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
|
||||
]),
|
||||
Section::make('Preis')->columns(3)->schema([
|
||||
TextInput::make('promo_code')->label('Rabattcode')->helperText('Sonderkondition aus den Angeboten')->maxLength(50)->live(onBlur: true),
|
||||
TextInput::make('price_adjustment')
|
||||
->label('Preisanpassung')
|
||||
->helperText('Minus = Nachlass, z. B. -50')
|
||||
->numeric()
|
||||
->step(0.01)
|
||||
->suffix('€')
|
||||
->live(onBlur: true),
|
||||
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80),
|
||||
Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Gültigkeit & Nachricht')->columns(2)->schema([
|
||||
DateTimePicker::make('valid_until')
|
||||
->label('Angebot gültig bis')
|
||||
->helperText(fn (): string => 'Standard: '.$this->record->property->hold_hours.' Stunden (Einstellung der Wohnung). Bis dahin bleibt der Zeitraum reserviert.')
|
||||
->seconds(false)
|
||||
->after('now')
|
||||
->required(),
|
||||
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
|
||||
]),
|
||||
Section::make('Gast – so erscheint er im Mietvertrag')->columns(2)->collapsed()->schema([
|
||||
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
|
||||
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
|
||||
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
|
||||
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
|
||||
TextInput::make('guest.city')->label('Ort')->maxLength(100),
|
||||
TextInput::make('guest.phone')->label('Telefon')->maxLength(50),
|
||||
]),
|
||||
])
|
||||
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(
|
||||
fn () => $send->handle($this->record, $this->offerChanges($data)),
|
||||
'Angebot gesendet',
|
||||
)),
|
||||
Action::make('offerLink')
|
||||
->label('Angebotslink')
|
||||
->icon(Heroicon::OutlinedLink)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
|
||||
->modalHeading('Link zum Angebot')
|
||||
->modalDescription('Derselbe Link wie in der Angebots-E-Mail – z. B. zum Weitergeben per Messenger. Gültig bis zum Ende der Angebotsfrist.')
|
||||
->schema([
|
||||
TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable(),
|
||||
])
|
||||
->modalSubmitAction(false)
|
||||
->modalCancelActionLabel('Schließen'),
|
||||
Action::make('offerPdf')
|
||||
->label('Angebot (PDF)')
|
||||
->icon(Heroicon::OutlinedDocumentText)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
|
||||
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf")),
|
||||
Action::make('confirm')
|
||||
->label('Direkt bestätigen')
|
||||
->icon(Heroicon::OutlinedCheckCircle)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Buchung bestätigen')
|
||||
->modalDescription('Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
|
||||
->modalHeading('Buchung direkt bestätigen')
|
||||
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung bereits anders verbindlich vereinbart wurde (z. B. telefonisch). Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
|
||||
->schema([
|
||||
Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(true),
|
||||
])
|
||||
@@ -51,7 +142,7 @@ protected function getHeaderActions(): array
|
||||
->label('Ablehnen')
|
||||
->icon(Heroicon::OutlinedXCircle)
|
||||
->color('danger')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Anfrage ablehnen')
|
||||
->schema([
|
||||
@@ -65,7 +156,7 @@ protected function getHeaderActions(): array
|
||||
->label('Vormerkung verlängern')
|
||||
->icon(Heroicon::OutlinedClock)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved)
|
||||
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
|
||||
->schema([
|
||||
TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required(),
|
||||
])
|
||||
@@ -75,7 +166,23 @@ protected function getHeaderActions(): array
|
||||
|
||||
Notification::make()->title('Vorgemerkt bis '.$this->record->hold_expires_at->format('d.m.Y, H:i'))->success()->send();
|
||||
}),
|
||||
Action::make('contract')
|
||||
->label('Mietvertrag')
|
||||
->icon(Heroicon::OutlinedDocumentText)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->contract_path !== null)
|
||||
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")),
|
||||
ActionGroup::make([
|
||||
Action::make('regenerateContract')
|
||||
->label('Mietvertrag neu erzeugen')
|
||||
->icon(Heroicon::OutlinedArrowPath)
|
||||
->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true))
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Der Vertrag wird mit den aktuellen Texten neu erstellt. Der Gast erhält ihn nicht automatisch.')
|
||||
->action(function (RentalContract $contract): void {
|
||||
$contract->generate($this->record);
|
||||
Notification::make()->title('Mietvertrag neu erzeugt')->success()->send();
|
||||
}),
|
||||
Action::make('notes')
|
||||
->label('Interne Notiz bearbeiten')
|
||||
->icon(Heroicon::OutlinedPencilSquare)
|
||||
@@ -100,11 +207,45 @@ protected function getHeaderActions(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Form data of the offer modal as SendOffer changes (euro input → cents).
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function offerChanges(array $data): array
|
||||
{
|
||||
return [
|
||||
...$data,
|
||||
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Live price shown in the offer modal, calculated exactly like the offer itself.
|
||||
*/
|
||||
private function offerPricePreview(Get $get): string
|
||||
{
|
||||
try {
|
||||
$stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null);
|
||||
$quote = app(PriceCalculator::class)->calculate($this->record->property, $stay);
|
||||
} catch (QuoteException $exception) {
|
||||
return 'Preis: '.$exception->getMessage();
|
||||
} catch (Throwable) {
|
||||
return 'Preis: bitte Termin und Personen angeben.';
|
||||
}
|
||||
|
||||
$adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0;
|
||||
$promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : '';
|
||||
|
||||
return 'Gesamtpreis im Angebot: '.Money::format($quote->total() + $adjustment).' (bisher '.Money::format($this->record->total).')'.$promo;
|
||||
}
|
||||
|
||||
private function runWorkflow(callable $workflow, string $successTitle): void
|
||||
{
|
||||
try {
|
||||
$workflow();
|
||||
} catch (ReservationException $exception) {
|
||||
} catch (ReservationException|QuoteException $exception) {
|
||||
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Bookings\RelationManagers;
|
||||
|
||||
use App\Actions\RecordPayment;
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Filament\Forms\Components\EuroInput;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Payment;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
/**
|
||||
* @property Booking $ownerRecord
|
||||
*/
|
||||
class PaymentsRelationManager extends RelationManager
|
||||
{
|
||||
protected static string $relationship = 'payments';
|
||||
|
||||
protected static ?string $title = 'Zahlungen';
|
||||
|
||||
public function isReadOnly(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('amount')
|
||||
->description(fn (): string => 'Bezahlt: '.Money::format($this->ownerRecord->paidAmount()).' · offen: '.Money::format($this->ownerRecord->openAmount()))
|
||||
->columns([
|
||||
TextColumn::make('paid_on')->label('Eingang')->date('d.m.Y'),
|
||||
TextColumn::make('amount')->label('Betrag')->money('EUR', divideBy: 100, locale: 'de'),
|
||||
TextColumn::make('method')->label('Art'),
|
||||
TextColumn::make('note')->label('Notiz')->placeholder('–'),
|
||||
TextColumn::make('recorded_by')->label('Erfasst von')->placeholder('–'),
|
||||
])
|
||||
->headerActions([
|
||||
Action::make('record')
|
||||
->label('Zahlung erfassen')
|
||||
->icon(Heroicon::OutlinedBanknotes)
|
||||
->fillForm(fn (): array => [
|
||||
'amount' => number_format(($this->ownerRecord->openDeposit() ?: $this->ownerRecord->openAmount()) / 100, 2, '.', ''),
|
||||
'paid_on' => today(),
|
||||
'method' => PaymentMethod::Transfer,
|
||||
])
|
||||
->schema([
|
||||
EuroInput::make('amount')->label('Betrag')->helperText('Erstattungen mit Minus erfassen.')->minValue(null)->required(),
|
||||
DatePicker::make('paid_on')->label('Zahlungseingang')->required(),
|
||||
Select::make('method')->label('Art')->options(PaymentMethod::class)->required(),
|
||||
TextInput::make('note')->label('Notiz')->maxLength(255),
|
||||
])
|
||||
->action(function (array $data, RecordPayment $recordPayment): void {
|
||||
$recordPayment->handle(
|
||||
$this->ownerRecord,
|
||||
(int) $data['amount'],
|
||||
CarbonImmutable::parse($data['paid_on']),
|
||||
$data['method'] instanceof PaymentMethod ? $data['method'] : PaymentMethod::from($data['method']),
|
||||
$data['note'] ?: null,
|
||||
auth()->user()?->name,
|
||||
);
|
||||
|
||||
Notification::make()->title('Zahlung erfasst – Status: '.$this->ownerRecord->fresh()->status->getLabel())->success()->send();
|
||||
}),
|
||||
])
|
||||
->recordActions([
|
||||
DeleteAction::make()->after(fn (Payment $record) => app(RecordPayment::class)->updateStatus($this->ownerRecord->fresh())),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,9 @@ public static function configure(Schema $schema): Schema
|
||||
TextEntry::make('deposit')->label('Anzahlung')->money('EUR', divideBy: 100, locale: 'de'),
|
||||
TextEntry::make('balance')->label('Restzahlung')->state(fn (Booking $record): string => Money::format($record->total - $record->deposit)),
|
||||
TextEntry::make('balance_due_on')->label('Rest fällig am')->date('d.m.Y'),
|
||||
TextEntry::make('paid')->label('Bezahlt')->state(fn (Booking $record): string => Money::format($record->paidAmount())),
|
||||
TextEntry::make('open')->label('Offen')->state(fn (Booking $record): string => Money::format($record->openAmount()))->color(fn (Booking $record): string => $record->openAmount() > 0 ? 'danger' : 'success'),
|
||||
TextEntry::make('deposit_due_on')->label('Anzahlung fällig am')->date('d.m.Y')->placeholder('–'),
|
||||
]),
|
||||
]),
|
||||
Section::make('Nachricht des Gastes')
|
||||
@@ -66,6 +69,11 @@ public static function configure(Schema $schema): Schema
|
||||
TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null),
|
||||
TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'),
|
||||
TextEntry::make('source')->label('Quelle'),
|
||||
TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'),
|
||||
TextEntry::make('utm')
|
||||
->label('Kampagne (UTM)')
|
||||
->state(fn (Booking $record): ?string => collect([$record->utm_source, $record->utm_medium, $record->utm_campaign])->filter()->implode(' / ') ?: null)
|
||||
->visible(fn (Booking $record): bool => filled($record->utm_source)),
|
||||
]),
|
||||
Section::make('Gast')
|
||||
->schema([
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\ViewAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
@@ -16,7 +17,7 @@ class BookingsTable
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property']))
|
||||
->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments']))
|
||||
->defaultSort('created_at', 'desc')
|
||||
->columns([
|
||||
TextColumn::make('reference')
|
||||
@@ -46,7 +47,8 @@ public static function configure(Table $table): Table
|
||||
->label('Pers.'),
|
||||
TextColumn::make('total')
|
||||
->label('Gesamt')
|
||||
->money('EUR', divideBy: 100, locale: 'de'),
|
||||
->money('EUR', divideBy: 100, locale: 'de')
|
||||
->description(fn (Booking $record): ?string => in_array($record->status, BookingStatus::occupying(), true) && $record->openAmount() > 0 ? 'offen '.Money::format($record->openAmount()) : null),
|
||||
TextColumn::make('source')
|
||||
->label('Quelle')
|
||||
->toggleable(isToggledHiddenByDefault: true),
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
|
||||
use App\Filament\Resources\ChannelTasks\Tables\ChannelTasksTable;
|
||||
use App\Models\ChannelTask;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class ChannelTaskResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = ChannelTask::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Portal-Aufgabe';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Portal-Aufgaben';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return ChannelTasksTable::configure($table);
|
||||
}
|
||||
|
||||
public static function canCreate(): bool
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
public static function getNavigationBadge(): ?string
|
||||
{
|
||||
$open = ChannelTask::query()->open()->count();
|
||||
|
||||
return $open > 0 ? (string) $open : null;
|
||||
}
|
||||
|
||||
public static function getNavigationBadgeColor(): string
|
||||
{
|
||||
return 'danger';
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListChannelTasks::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Pages;
|
||||
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListChannelTasks extends ListRecords
|
||||
{
|
||||
protected static string $resource = ChannelTaskResource::class;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks\Tables;
|
||||
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\ChannelTask;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\SelectFilter;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class ChannelTasksTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->defaultSort('created_at', 'desc')
|
||||
->description('Diese Portale werden zusätzlich von Hand gepflegt. Bitte die Änderung im Portal vornehmen und hier abhaken.')
|
||||
->columns([
|
||||
TextColumn::make('channel.name')->label('Portal')->weight('medium'),
|
||||
TextColumn::make('action')->label('Aktion')->badge(),
|
||||
TextColumn::make('period')->label('Zeitraum')->state(fn (ChannelTask $record): string => $record->period()),
|
||||
TextColumn::make('reason')->label('Anlass')->wrap(),
|
||||
TextColumn::make('status')->label('Status')->badge()
|
||||
->description(fn (ChannelTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null),
|
||||
TextColumn::make('created_at')->label('Seit')->since(),
|
||||
TextColumn::make('automation_error')->label('Automatisierung')->placeholder('–')->limit(40)->toggleable(isToggledHiddenByDefault: true),
|
||||
])
|
||||
->filters([
|
||||
SelectFilter::make('status')
|
||||
->label('Status')
|
||||
->options(ChannelTaskStatus::class)
|
||||
->default(ChannelTaskStatus::Open->value),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('openPortal')
|
||||
->label('Portal öffnen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->color('gray')
|
||||
->url(fn (ChannelTask $record): ?string => $record->channel->manage_url, shouldOpenInNewTab: true)
|
||||
->visible(fn (ChannelTask $record): bool => filled($record->channel->manage_url)),
|
||||
Action::make('done')
|
||||
->label('Erledigt')
|
||||
->icon(Heroicon::OutlinedCheck)
|
||||
->color('success')
|
||||
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
|
||||
->action(fn (ChannelTask $record) => $record->complete(auth()->user()->name)),
|
||||
Action::make('dismiss')
|
||||
->label('Verwerfen')
|
||||
->icon(Heroicon::OutlinedXMark)
|
||||
->color('gray')
|
||||
->requiresConfirmation()
|
||||
->visible(fn (ChannelTask $record): bool => $record->status === ChannelTaskStatus::Open)
|
||||
->action(fn (ChannelTask $record) => $record->update(['status' => ChannelTaskStatus::Dismissed])),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Faqs;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Faqs\Pages\CreateFaq;
|
||||
use App\Filament\Resources\Faqs\Pages\EditFaq;
|
||||
use App\Filament\Resources\Faqs\Pages\ListFaqs;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class FaqResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Faq::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedQuestionMarkCircle;
|
||||
@@ -27,7 +30,7 @@ class FaqResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Häufige Fragen';
|
||||
|
||||
protected static ?int $navigationSort = 4;
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Guests;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Guests\Pages\CreateGuest;
|
||||
use App\Filament\Resources\Guests\Pages\EditGuest;
|
||||
use App\Filament\Resources\Guests\Pages\ListGuests;
|
||||
@@ -18,6 +19,8 @@
|
||||
|
||||
class GuestResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Guest::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Notices;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Notices\Pages\CreateNotice;
|
||||
use App\Filament\Resources\Notices\Pages\EditNotice;
|
||||
use App\Filament\Resources\Notices\Pages\ListNotices;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class NoticeResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Notice::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMegaphone;
|
||||
@@ -27,7 +30,7 @@ class NoticeResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Hinweis-Banner';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
protected static ?int $navigationSort = 6;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Pages\Pages\CreatePage;
|
||||
use App\Filament\Resources\Pages\Pages\EditPage;
|
||||
use App\Filament\Resources\Pages\Pages\ListPages;
|
||||
use App\Filament\Resources\Pages\Schemas\PageForm;
|
||||
use App\Filament\Resources\Pages\Tables\PagesTable;
|
||||
use App\Models\Page;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
class PageResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Page::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentDuplicate;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
|
||||
protected static ?string $modelLabel = 'Seite';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Seiten';
|
||||
|
||||
protected static ?int $navigationSort = 0;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return PageForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return PagesTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getRelations(): array
|
||||
{
|
||||
return [
|
||||
//
|
||||
];
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListPages::route('/'),
|
||||
'create' => CreatePage::route('/create'),
|
||||
'edit' => EditPage::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreatePage extends CreateRecord
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditPage extends EditRecord
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Pages;
|
||||
|
||||
use App\Filament\Resources\Pages\PageResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPages extends ListRecords
|
||||
{
|
||||
protected static string $resource = PageResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Schemas;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Themes\SectionRegistry;
|
||||
use Filament\Forms\Components\Builder;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Validation\Rules\Unique;
|
||||
|
||||
class PageForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(3)
|
||||
->components([
|
||||
Section::make('Bausteine')
|
||||
->description('Die Seite besteht aus Bausteinen. Reihenfolge per Ziehen, Inhalte je Baustein. Wie sie aussehen, bestimmt das Theme.')
|
||||
->columnSpan(2)
|
||||
->schema([
|
||||
Builder::make('sections')
|
||||
->hiddenLabel()
|
||||
->blocks(fn (): array => app(SectionRegistry::class)->blocks())
|
||||
->addActionLabel('Baustein hinzufügen')
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
->cloneable()
|
||||
->blockNumbers(false)
|
||||
->blockPickerColumns(2),
|
||||
]),
|
||||
Section::make('Seite')
|
||||
->columnSpan(1)
|
||||
->schema([
|
||||
Hidden::make('site_id')->default(fn (): ?int => Site::query()->where('is_default', true)->value('id') ?? Site::query()->value('id')),
|
||||
TextInput::make('title')->label('Titel')->required()->maxLength(120),
|
||||
TextInput::make('slug')
|
||||
->label('Adresse')
|
||||
->prefix('/')
|
||||
->helperText('Die Startseite heißt „start“.')
|
||||
->required()
|
||||
->alphaDash()
|
||||
->maxLength(80)
|
||||
->disabled(fn (?Page $record): bool => $record?->isHome() ?? false)
|
||||
->dehydrated()
|
||||
->unique(ignoreRecord: true, modifyRuleUsing: fn (Unique $rule, callable $get) => $rule->where('site_id', $get('site_id'))),
|
||||
TextInput::make('menu_label')->label('Name im Menü (optional)')->maxLength(60),
|
||||
Select::make('menu_location')->label('Menü')->options(Page::MENU_LOCATIONS)->default('main')->required(),
|
||||
Toggle::make('is_published')->label('Veröffentlicht')->default(true),
|
||||
]),
|
||||
Section::make('Suchmaschinen')
|
||||
->columnSpan(1)
|
||||
->collapsed()
|
||||
->schema([
|
||||
TextInput::make('seo_title')->label('Seitentitel (Google)')->maxLength(70),
|
||||
Textarea::make('seo_description')->label('Beschreibung (Google)')->rows(3)->maxLength(170),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Pages\Tables;
|
||||
|
||||
use App\Models\Page;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class PagesTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->reorderable('sort_order')
|
||||
->defaultSort('sort_order')
|
||||
->paginated(false)
|
||||
->description('Reihenfolge per Ziehen = Reihenfolge im Menü.')
|
||||
->columns([
|
||||
TextColumn::make('title')->label('Seite')->weight('medium')->description(fn (Page $record): string => $record->isHome() ? '/' : '/'.$record->slug),
|
||||
TextColumn::make('menu_location')->label('Menü')->formatStateUsing(fn (string $state): string => Page::MENU_LOCATIONS[$state] ?? $state)->badge(),
|
||||
TextColumn::make('sections')->label('Bausteine')->state(fn (Page $record): int => count($record->sections ?? [])),
|
||||
ToggleColumn::make('is_published')->label('Veröffentlicht'),
|
||||
])
|
||||
->recordActions([
|
||||
Action::make('open')
|
||||
->label('Ansehen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->color('gray')
|
||||
->url(fn (Page $record): string => $record->url(), shouldOpenInNewTab: true),
|
||||
EditAction::make(),
|
||||
DeleteAction::make()->visible(fn (Page $record): bool => ! $record->isHome()),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Photos;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Photos\Pages\CreatePhoto;
|
||||
use App\Filament\Resources\Photos\Pages\EditPhoto;
|
||||
use App\Filament\Resources\Photos\Pages\ListPhotos;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class PhotoResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Photo::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPhoto;
|
||||
@@ -27,7 +30,7 @@ class PhotoResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Bilder';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\PortalEmails\Pages;
|
||||
|
||||
use App\Filament\Resources\PortalEmails\PortalEmailResource;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListPortalEmails extends ListRecords
|
||||
{
|
||||
protected static string $resource = PortalEmailResource::class;
|
||||
}
|
||||
Loaded 100 of 495 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user