Compare commits
63
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92ccf40312 | ||
|
|
6d8f1d6692 | ||
|
|
abf0e9004b | ||
|
|
3a0bb6e40f | ||
|
|
361acfa12a | ||
|
|
c459f7f83c | ||
|
|
4e66add1f0 | ||
|
|
f686996122 | ||
|
|
2c5b5fc2d7 | ||
|
|
9cd39f791f | ||
|
|
c55937d20e | ||
|
|
c2cf632ad5 | ||
|
|
f2e78446a8 | ||
|
|
03ad4667ac | ||
|
|
d9383cf3e5 | ||
|
|
e0e8c1d856 | ||
|
|
2f2aceb3bd | ||
|
|
2e3f2ca938 | ||
|
|
fd2a7f7ded | ||
|
|
220ec6bfdb | ||
|
|
afffa79289 | ||
|
|
f143a4f5f4 | ||
|
|
e6d4d89141 | ||
|
|
12e4079126 | ||
|
|
1871c04507 | ||
|
|
dfd3f77a5d | ||
|
|
f7cbc66451 | ||
|
|
04b5189bd8 | ||
|
|
9b8a851ce9 | ||
|
|
b3114cdfe3 | ||
|
|
faf2133232 | ||
|
|
d2f53ceb84 | ||
|
|
ab1dffc72f | ||
|
|
fc61369c4a | ||
|
|
cec49da1be | ||
|
|
8ebc1a3878 | ||
|
|
d9e52c4789 | ||
|
|
3621f7e924 | ||
|
|
6930d3ab0f | ||
|
|
c215da0590 | ||
|
|
e49f160496 | ||
|
|
bc2b175556 | ||
|
|
5416b37dfc | ||
|
|
30e9aa7b26 | ||
|
|
4951f227f1 | ||
|
|
a9ad4dbf0b | ||
|
|
e276cd0548 | ||
|
|
0c98d82cf2 | ||
|
|
749537342e | ||
|
|
b681327d3a | ||
|
|
bde99657cf | ||
|
|
d018c97be4 | ||
|
|
fdcb68d578 | ||
|
|
70a8c5072b | ||
|
|
20235b9139 | ||
|
|
565eee4325 | ||
|
|
fd744edf8c | ||
|
|
7a6ee316cd | ||
|
|
6690beafe6 | ||
|
|
4f69b426a4 | ||
|
|
82698f8eda | ||
|
|
7d0bc93abc | ||
|
|
bc77b64ea7 |
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(git merge *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -35,14 +35,16 @@ MAIL_MAILER=smtp
|
||||
MAIL_HOST=smtp.strato.de
|
||||
MAIL_PORT=465
|
||||
MAIL_SCHEME=smtps
|
||||
MAIL_USERNAME=fewo@stommer.de
|
||||
MAIL_USERNAME=info@fewo-stommer.de
|
||||
MAIL_PASSWORD=
|
||||
MAIL_FROM_ADDRESS="fewo@stommer.de"
|
||||
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=
|
||||
|
||||
@@ -36,11 +36,37 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
- name: Runner-Umgebung prüfen
|
||||
shell: bash
|
||||
run: |
|
||||
uname -m
|
||||
cat /etc/os-release
|
||||
id
|
||||
if command -v php >/dev/null 2>&1; then
|
||||
php --version
|
||||
else
|
||||
echo 'PHP ist noch nicht im PATH.'
|
||||
fi
|
||||
if command -v apt-cache >/dev/null 2>&1; then
|
||||
apt-cache policy php8.4 php8.4-cli php8.4-dev
|
||||
fi
|
||||
if [ "$(id -u)" = 0 ]; then
|
||||
echo 'Runner läuft als root.'
|
||||
elif command -v sudo >/dev/null 2>&1 && sudo -n true; then
|
||||
echo 'Passwortloses sudo ist verfügbar.'
|
||||
else
|
||||
echo '::error::setup-php benötigt auf diesem Host passwortloses sudo; der Runner hat es nicht.'
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# act_runner v0.2.11 supports Node 20; newer setup-php releases require Node 24.
|
||||
- uses: shivammathur/setup-php@2.36.0
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, pdo_sqlite, sqlite3, pdo_mysql, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
env:
|
||||
runner: self-hosted
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
@@ -56,7 +82,7 @@ jobs:
|
||||
php artisan key:generate
|
||||
|
||||
- name: Tests (SQLite)
|
||||
run: php artisan test --compact
|
||||
run: php artisan test --compact --testsuite=Feature
|
||||
|
||||
- name: Tests (MariaDB 11.8, wie auf Strato)
|
||||
env:
|
||||
@@ -66,7 +92,7 @@ jobs:
|
||||
DB_DATABASE: fewo_test
|
||||
DB_USERNAME: root
|
||||
DB_PASSWORD: test
|
||||
run: php artisan test --compact
|
||||
run: php artisan test --compact --testsuite=Feature
|
||||
|
||||
deploy:
|
||||
needs: test
|
||||
@@ -75,11 +101,14 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: shivammathur/setup-php@v2
|
||||
# Keep the runtime compatible with the test job and the installed act_runner.
|
||||
- uses: shivammathur/setup-php@2.36.0
|
||||
with:
|
||||
php-version: '8.4'
|
||||
extensions: mbstring, intl, gd, exif, zip, fileinfo, openssl
|
||||
tools: composer:v2
|
||||
env:
|
||||
runner: self-hosted
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
|
||||
@@ -32,3 +32,4 @@ Thumbs.db
|
||||
# Deployment settings with access data
|
||||
/scripts/deploy.*.env
|
||||
!/scripts/deploy.example.env
|
||||
storage/app/private/exports/
|
||||
@@ -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,11 +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. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). 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 admins via `RequireTwoFactorForAdmins`.
|
||||
- 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,11 +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. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). 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 admins via `RequireTwoFactorForAdmins`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- 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]);
|
||||
}
|
||||
}
|
||||
@@ -12,9 +12,9 @@
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* The landlord accepts a reservation: the booking becomes binding, payment due dates are fixed,
|
||||
* the rental contract is generated and sent with the confirmation.
|
||||
* 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
|
||||
{
|
||||
@@ -28,7 +28,7 @@ public function __construct(
|
||||
*/
|
||||
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');
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
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;
|
||||
@@ -45,7 +46,7 @@ public function handle(Property $property, CarbonInterface $startsOn, CarbonInte
|
||||
return [];
|
||||
}
|
||||
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelTasksNotification($tasks)));
|
||||
|
||||
foreach ($tasks as $task) {
|
||||
$this->sendToAutomation($task);
|
||||
|
||||
@@ -13,6 +13,9 @@
|
||||
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;
|
||||
@@ -37,6 +40,24 @@ public function __construct(
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Property $property, StayRequest $stay, array $guestData, ?string $message = null, string $source = 'website', bool $sendMails = true, array $attribution = []): 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();
|
||||
@@ -47,8 +68,7 @@ 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,
|
||||
@@ -66,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,
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -76,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.
|
||||
*/
|
||||
@@ -83,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();
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
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;
|
||||
@@ -24,7 +25,7 @@ public function handle(): int
|
||||
->filter(fn (Channel $channel): bool => $channel->isStale());
|
||||
|
||||
foreach ($channels as $channel) {
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelSyncAlert($channel));
|
||||
Mail::to(Settings::notificationRecipients())->send(new ChannelSyncAlert($channel));
|
||||
$channel->forceFill(['alerted_at' => now()])->save();
|
||||
}
|
||||
|
||||
@@ -37,7 +38,7 @@ public static function mailboxIsStale(): bool
|
||||
return false;
|
||||
}
|
||||
|
||||
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
|
||||
$lastSuccess = Cache::get(MailboxReader::key(MailboxReader::LAST_SUCCESS_KEY));
|
||||
|
||||
return $lastSuccess === null
|
||||
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
|
||||
@@ -55,7 +56,7 @@ private function monitorMailbox(): int
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
|
||||
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::key(MailboxReader::LAST_ERROR_KEY))));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
|
||||
@@ -8,11 +8,14 @@
|
||||
use App\Channels\Mail\PortalMailParser;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Mail\ChannelConflict;
|
||||
use App\Mail\PortalMailNotification;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -39,6 +42,11 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
return null;
|
||||
}
|
||||
|
||||
// The fast path is a service of its own: a landlord without it keeps the mail unprocessed.
|
||||
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $channel->tenant)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = $this->parser->parse($mail->subject, $mail->text);
|
||||
$conflicts = [];
|
||||
|
||||
@@ -68,11 +76,11 @@ public function handle(PortalMail $mail): ?PortalEmail
|
||||
});
|
||||
|
||||
if (in_array($record->status, [PortalEmailStatus::Blocked, PortalEmailStatus::Released, PortalEmailStatus::NeedsReview], true)) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new PortalMailNotification($record)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new PortalMailNotification($record)));
|
||||
}
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
|
||||
}
|
||||
|
||||
return $record;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Mail\ChannelTasksNotification;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
@@ -24,7 +25,7 @@ public function handle(): int
|
||||
return 0;
|
||||
}
|
||||
|
||||
Mail::to(config('fewo.notification_email'))->send(new ChannelTasksNotification($tasks->all(), reminder: true));
|
||||
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,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;
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
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;
|
||||
@@ -64,7 +65,8 @@ public function handle(Channel $channel): ChannelSyncLog
|
||||
'property_id' => $channel->property_id,
|
||||
'starts_on' => $period->startsOn->toDateString(),
|
||||
'ends_on' => $period->endsOn->toDateString(),
|
||||
'reason' => "{$channel->name}".($period->summary ? ": {$period->summary}" : ''),
|
||||
// The portal's SUMMARY is not stored: it may contain guest names (data minimisation).
|
||||
'reason' => $channel->name,
|
||||
'source' => 'channel',
|
||||
];
|
||||
|
||||
@@ -108,7 +110,7 @@ public function handle(Channel $channel): ChannelSyncLog
|
||||
])->save();
|
||||
|
||||
if ($conflicts !== []) {
|
||||
rescue(fn () => Mail::to(config('fewo.notification_email'))->send(new ChannelConflict($channel, $conflicts)));
|
||||
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
|
||||
}
|
||||
|
||||
return $channel->syncLogs()->create([
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Channels\Mail;
|
||||
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Throwable;
|
||||
@@ -17,11 +18,31 @@ class MailboxReader
|
||||
{
|
||||
public const LAST_SUCCESS_KEY = 'mailbox:last_success_at';
|
||||
|
||||
/**
|
||||
* The state of one landlord's mailbox. Without the landlord in the key, two landlords would report
|
||||
* each other's last success and alerts would be raised for the wrong one.
|
||||
*/
|
||||
public static function key(string $base): string
|
||||
{
|
||||
return $base.':'.(Settings::tenant()?->id ?? 0);
|
||||
}
|
||||
|
||||
public const LAST_ERROR_KEY = 'mailbox:last_error';
|
||||
|
||||
/**
|
||||
* The mailbox of the current landlord. Each landlord reads their own; an empty one means the fast path
|
||||
* is off for them.
|
||||
*
|
||||
* @return array<string, mixed>|null
|
||||
*/
|
||||
public static function configuration(): ?array
|
||||
{
|
||||
return Settings::tenant()?->mailbox();
|
||||
}
|
||||
|
||||
public static function isConfigured(): bool
|
||||
{
|
||||
return filled(config('fewo.mailbox.host')) && filled(config('fewo.mailbox.username'));
|
||||
return self::configuration() !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -32,7 +53,11 @@ public static function isConfigured(): bool
|
||||
*/
|
||||
public function fetch(array $senders): array
|
||||
{
|
||||
$config = config('fewo.mailbox');
|
||||
$config = self::configuration();
|
||||
|
||||
if ($config === null) {
|
||||
throw new ChannelSyncException('Für diesen Mandanten ist kein Postfach hinterlegt.');
|
||||
}
|
||||
|
||||
try {
|
||||
$client = (new ClientManager)->make([
|
||||
@@ -62,13 +87,13 @@ public function fetch(array $senders): array
|
||||
|
||||
$client->disconnect();
|
||||
} catch (Throwable $exception) {
|
||||
Cache::forever(self::LAST_ERROR_KEY, $exception->getMessage());
|
||||
Cache::forever(self::key(self::LAST_ERROR_KEY), $exception->getMessage());
|
||||
|
||||
throw new ChannelSyncException('Postfach konnte nicht gelesen werden: '.$exception->getMessage(), previous: $exception);
|
||||
}
|
||||
|
||||
Cache::forever(self::LAST_SUCCESS_KEY, now()->toIso8601String());
|
||||
Cache::forget(self::LAST_ERROR_KEY);
|
||||
Cache::forever(self::key(self::LAST_SUCCESS_KEY), now()->toIso8601String());
|
||||
Cache::forget(self::key(self::LAST_ERROR_KEY));
|
||||
|
||||
return $mails;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,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,71 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\ImageWorlds\ImageWorldManifest;
|
||||
use App\ImageWorlds\ImageWorldRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('image-worlds:check')]
|
||||
#[Description('Check every picture world: does each slot in the manifest have its SVG file?')]
|
||||
class CheckImageWorlds extends Command
|
||||
{
|
||||
/**
|
||||
* A slot without a file is not an error at runtime – templates simply get no decoration. That makes it
|
||||
* easy to miss, so it is reported here instead of silently leaving a page bare.
|
||||
*/
|
||||
public function handle(ImageWorldRegistry $registry): int
|
||||
{
|
||||
$worlds = $registry->all();
|
||||
|
||||
if ($worlds === []) {
|
||||
$this->warn('Keine Bildwelt gefunden.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$incomplete = 0;
|
||||
|
||||
foreach ($worlds as $world) {
|
||||
$missing = $world->missingFiles();
|
||||
|
||||
if ($missing === []) {
|
||||
$this->info(sprintf('✓ %s (%s): %d Plätze', $world->name, $world->key, count($world->slots)));
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$incomplete++;
|
||||
$this->error(sprintf('✗ %s (%s): ohne Datei – %s', $world->name, $world->key, implode(', ', $missing)));
|
||||
}
|
||||
|
||||
$this->newLine();
|
||||
$this->line($this->slotOverview($worlds));
|
||||
|
||||
return $incomplete === 0 ? self::SUCCESS : self::FAILURE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which slot is filled by which world – so a template author sees what they may rely on.
|
||||
*
|
||||
* @param array<string, ImageWorldManifest> $worlds
|
||||
*/
|
||||
private function slotOverview(array $worlds): string
|
||||
{
|
||||
$slots = [];
|
||||
|
||||
foreach ($worlds as $world) {
|
||||
foreach (array_keys($world->slots) as $slot) {
|
||||
$slots[$slot][] = $world->key;
|
||||
}
|
||||
}
|
||||
|
||||
ksort($slots);
|
||||
|
||||
return collect($slots)
|
||||
->map(fn (array $keys, string $slot): string => sprintf(' %-18s %s', $slot, implode(', ', $keys)))
|
||||
->implode(PHP_EOL);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,9 @@
|
||||
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;
|
||||
@@ -13,7 +15,7 @@
|
||||
use function Laravel\Prompts\select;
|
||||
use function Laravel\Prompts\text;
|
||||
|
||||
#[Signature('users:create {email? : E-Mail-Adresse} {--name= : Name} {--role= : admin, rentals oder content}')]
|
||||
#[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
|
||||
{
|
||||
@@ -22,6 +24,12 @@ class CreateUser extends 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));
|
||||
|
||||
@@ -51,14 +59,48 @@ public function handle(): int
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
User::create(['name' => $name, 'email' => $email, 'role' => $role, 'password' => $password]);
|
||||
$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.");
|
||||
|
||||
if ($role === UserRole::Admin) {
|
||||
$this->line('Bei der ersten Anmeldung wird die Zwei-Faktor-Anmeldung mit einer Authenticator-App eingerichtet.');
|
||||
}
|
||||
$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,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
use function Laravel\Prompts\confirm;
|
||||
|
||||
#[Signature('tenants:delete {slug : Kurzname des Mandanten} {--keep-export : Nicht vorher exportieren} {--force : Ohne Rückfrage}')]
|
||||
#[Description('Export a landlord and then remove them with all their data and files')]
|
||||
class DeleteTenant extends Command
|
||||
{
|
||||
/**
|
||||
* Exports first, unless told otherwise: a deletion that cannot be undone should leave something behind.
|
||||
*/
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $this->option('keep-export')) {
|
||||
$path = $archive->export($tenant, storage_path('app/private/exports'));
|
||||
$this->info('Export geschrieben: '.$path);
|
||||
}
|
||||
|
||||
if (! $this->option('force') && ! confirm('Mandant '.$tenant->name.' mit allen Daten und Dateien endgültig löschen?', default: false)) {
|
||||
$this->line('Abgebrochen.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$removed = $archive->delete($tenant);
|
||||
|
||||
foreach ($removed as $table => $count) {
|
||||
$this->line(sprintf(' %-22s %d', $table, $count));
|
||||
}
|
||||
|
||||
$this->info('Mandant '.$tenant->name.' gelöscht.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -3,22 +3,26 @@
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Actions\ExpireReservations;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('bookings:expire-holds')]
|
||||
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord')]
|
||||
#[Description('Mark reservations with an elapsed hold time as expired and notify the landlord – once per landlord')]
|
||||
class ExpireReservationHolds extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ExpireReservations $expireReservations): int
|
||||
public function handle(ExpireReservations $expireReservations, TenantRunner $runner): int
|
||||
{
|
||||
$count = $expireReservations->handle();
|
||||
$runner->each(function (Tenant $tenant) use ($expireReservations): void {
|
||||
$count = $expireReservations->handle();
|
||||
|
||||
$this->info("{$count} Vormerkung(en) abgelaufen.");
|
||||
$this->info("{$tenant->name}: {$count} Vormerkung(en) abgelaufen.");
|
||||
});
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantArchive;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('tenants:export {slug : Kurzname des Mandanten} {--to= : Zielordner, sonst storage/app/private/exports}')]
|
||||
#[Description('Write all data and files of one landlord into a zip archive')]
|
||||
class ExportTenant extends Command
|
||||
{
|
||||
public function handle(TenantArchive $archive): int
|
||||
{
|
||||
$tenant = Tenant::query()->where('slug', $this->argument('slug'))->first();
|
||||
|
||||
if ($tenant === null) {
|
||||
$this->error('Kein Mandant mit dem Kurznamen '.$this->argument('slug').'.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$path = $archive->export($tenant, (string) ($this->option('to') ?: storage_path('app/private/exports')));
|
||||
|
||||
$this->info('Export von '.$tenant->name.': '.$path.' ('.$this->size($path).')');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function size(string $path): string
|
||||
{
|
||||
$bytes = (int) (filesize($path) ?: 0);
|
||||
|
||||
return $bytes > 1048576
|
||||
? round($bytes / 1048576, 1).' MB'
|
||||
: round($bytes / 1024).' KB';
|
||||
}
|
||||
}
|
||||
@@ -5,24 +5,40 @@
|
||||
use App\Actions\ProcessPortalMail;
|
||||
use App\Channels\ChannelSyncException;
|
||||
use App\Channels\Mail\MailboxReader;
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:fetch-mail')]
|
||||
#[Description('Read booking notifications of the portals from the mailbox and block recognised bookings immediately')]
|
||||
#[Description('Read booking notifications of the portals from each landlord\'s mailbox and block recognised bookings immediately')]
|
||||
class FetchPortalMail extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Execute the console command. Every landlord has their own mailbox, so every landlord gets their own
|
||||
* run – one landlord's credentials are never used to read another one's mail.
|
||||
*/
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail): int
|
||||
public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMail, TenantRunner $runner): int
|
||||
{
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line('Kein Postfach konfiguriert (FEWO_MAILBOX_HOST).');
|
||||
$runner->each(fn (Tenant $tenant) => $this->fetchForCurrentLandlord($reader, $processPortalMail, $tenant));
|
||||
|
||||
return self::SUCCESS;
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function fetchForCurrentLandlord(MailboxReader $reader, ProcessPortalMail $processPortalMail, Tenant $tenant): void
|
||||
{
|
||||
if (! app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail, $tenant)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (! MailboxReader::isConfigured()) {
|
||||
$this->line("{$tenant->name}: kein Postfach hinterlegt.");
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$senders = Channel::query()->active()->get()
|
||||
@@ -32,25 +48,23 @@ public function handle(MailboxReader $reader, ProcessPortalMail $processPortalMa
|
||||
->all();
|
||||
|
||||
if ($senders === []) {
|
||||
$this->line('Für kein Portal sind Absender hinterlegt.');
|
||||
$this->line("{$tenant->name}: für kein Portal sind Absender hinterlegt.");
|
||||
|
||||
return self::SUCCESS;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$mails = $reader->fetch($senders);
|
||||
} catch (ChannelSyncException $exception) {
|
||||
$this->error($exception->getMessage());
|
||||
$this->error("{$tenant->name}: {$exception->getMessage()}");
|
||||
|
||||
return self::FAILURE;
|
||||
return;
|
||||
}
|
||||
|
||||
foreach ($mails as $mail) {
|
||||
if ($record = $processPortalMail->handle($mail)) {
|
||||
$this->info("{$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
$this->info("{$tenant->name} – {$record->channel->name}: {$record->type->getLabel()} → {$record->status->getLabel()} ({$record->subject})");
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -4,18 +4,27 @@
|
||||
|
||||
use App\Actions\SyncChannel;
|
||||
use App\Models\Channel;
|
||||
use App\Tenancy\TenantRunner;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('channels:sync {channel? : ID of a single channel}')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts')]
|
||||
#[Description('Import the occupations of all active portals (or one) and report conflicts – once per landlord')]
|
||||
class SyncChannels extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
* Execute the console command. Runs per landlord so that conflict mails carry the right sender and
|
||||
* reach the right people.
|
||||
*/
|
||||
public function handle(SyncChannel $syncChannel): int
|
||||
public function handle(SyncChannel $syncChannel, TenantRunner $runner): int
|
||||
{
|
||||
$runner->each(fn () => $this->syncCurrentLandlord($syncChannel));
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function syncCurrentLandlord(SyncChannel $syncChannel): void
|
||||
{
|
||||
$channels = Channel::query()->active()
|
||||
->when($this->argument('channel'), fn ($query, $id) => $query->whereKey($id))
|
||||
@@ -29,7 +38,5 @@ public function handle(SyncChannel $syncChannel): int
|
||||
? $this->info("✓ {$channel->name}: {$log->events} Belegungen, +{$log->added} ~{$log->changed} -{$log->removed}, Konflikte: {$log->conflicts}")
|
||||
: $this->error("✗ {$channel->name}: {$log->message}");
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -3,32 +3,44 @@
|
||||
namespace App\Documents;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Site;
|
||||
use Barryvdh\DomPDF\Facade\Pdf;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
/**
|
||||
* The rental contract as PDF. It is generated once at confirmation and stored, so later changes
|
||||
* of texts or prices do not alter a contract the guest already received.
|
||||
* 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): string
|
||||
public function generate(Booking $booking, bool $draft = false): string
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$path = "contracts/Mietvertrag-{$booking->reference}.pdf";
|
||||
$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])->setPaper('a4')->output());
|
||||
$booking->update(['contract_path' => $path]);
|
||||
// The logo is embedded as a file: the PDF is rendered on the server and must not depend on
|
||||
// fetching anything over the network. Each website has its own (A14).
|
||||
$logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO);
|
||||
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', [
|
||||
'booking' => $booking,
|
||||
'draft' => $draft,
|
||||
'logo' => $logo,
|
||||
])->setPaper('a4')->output());
|
||||
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function absolutePath(Booking $booking): ?string
|
||||
public function absolutePath(Booking $booking, bool $draft = false): ?string
|
||||
{
|
||||
return $booking->contract_path && Storage::disk(self::DISK)->exists($booking->contract_path)
|
||||
? Storage::disk(self::DISK)->path($booking->contract_path)
|
||||
: null;
|
||||
$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.
|
||||
*
|
||||
|
||||
@@ -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,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';
|
||||
}
|
||||
@@ -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,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
/**
|
||||
* Services the operator unlocks per landlord. `isWired()` says whether the application really asks before
|
||||
* it acts – a service that nothing asks for must not be offered as a switch, because switching it would
|
||||
* promise something that does not happen.
|
||||
*/
|
||||
enum TenantServiceKey: string
|
||||
{
|
||||
case PortalSync = 'portal_sync';
|
||||
case PortalMail = 'portal_mail';
|
||||
case AiOffers = 'ai_offers';
|
||||
case AiMarketing = 'ai_marketing';
|
||||
case AiGuestMail = 'ai_guest_mail';
|
||||
|
||||
public function label(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync => 'Portal-Abgleich (iCal)',
|
||||
self::PortalMail => 'Portal-Postfach (Schnellweg)',
|
||||
self::AiOffers => 'KI: Angebotsentwürfe',
|
||||
self::AiMarketing => 'KI: Vermarktungsassistent',
|
||||
self::AiGuestMail => 'KI: Gästekommunikation',
|
||||
};
|
||||
}
|
||||
|
||||
public function description(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync => 'Belegungen der Portale über iCal einlesen und den eigenen Kalender als Feed anbieten.',
|
||||
self::PortalMail => 'Buchungsmails der Portale aus dem Postfach lesen und Termine sofort sperren.',
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => 'Noch nicht gebaut.',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the application asks this switch before it acts. Only wired services are offered for switching.
|
||||
*/
|
||||
public function isWired(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::PortalSync, self::PortalMail => true,
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* What applies to a landlord the operator has not decided about yet. The portal services were part of
|
||||
* the product before there were landlords, so switching tenancy on must not silently stop them.
|
||||
*/
|
||||
public function enabledByDefault(): bool
|
||||
{
|
||||
return $this->isWired();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the landlord's own API key is of any use. Nothing calls out yet, so no service has one.
|
||||
*/
|
||||
public function usesApiKey(): bool
|
||||
{
|
||||
return match ($this) {
|
||||
self::AiOffers, self::AiMarketing, self::AiGuestMail => true,
|
||||
self::PortalSync, self::PortalMail => false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function wired(): array
|
||||
{
|
||||
return array_values(array_filter(self::cases(), fn (self $service): bool => $service->isWired()));
|
||||
}
|
||||
}
|
||||
+30
-2
@@ -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,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
|
||||
/**
|
||||
* The service switches of the tenant form. They live in their own table, so the form state is read and
|
||||
* written separately from the landlord's own columns. Only wired services are written – a switch for a
|
||||
* service nothing asks about would promise something that does not happen.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantServices
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillServices(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data; // creating: there is nothing to read yet
|
||||
}
|
||||
|
||||
$stored = $tenant->services->keyBy('service');
|
||||
|
||||
$data['services'] = collect(TenantServiceKey::wired())
|
||||
->mapWithKeys(fn (TenantServiceKey $service): array => [$service->value => [
|
||||
'is_enabled' => $stored->get($service->value)?->is_enabled ?? $service->enabledByDefault(),
|
||||
]])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeServices(array $data): array
|
||||
{
|
||||
$this->services = is_array($data['services'] ?? null) ? $data['services'] : [];
|
||||
|
||||
unset($data['services']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function saveServices(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (TenantServiceKey::wired() as $service) {
|
||||
$state = $this->services[$service->value] ?? [];
|
||||
|
||||
$tenant->services()->updateOrCreate(
|
||||
['service' => $service->value],
|
||||
['is_enabled' => (bool) ($state['is_enabled'] ?? false)],
|
||||
);
|
||||
}
|
||||
|
||||
$tenant->unsetRelation('services');
|
||||
app(TenantFeatures::class)->forget($tenant);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
/**
|
||||
* Everything the operator sets up for a landlord that does not live in the tenants table itself:
|
||||
* the websites with their entry addresses, and the services that are unlocked.
|
||||
*/
|
||||
trait EditsTenantSetup
|
||||
{
|
||||
use EditsTenantServices;
|
||||
use EditsTenantWebsites;
|
||||
|
||||
/** @var array<string, array<string, mixed>> */
|
||||
public array $services = [];
|
||||
|
||||
/** @var list<array<string, mixed>> */
|
||||
public array $websites = [];
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
return $this->fillWebsites($this->fillServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeCreate(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
return $this->takeWebsites($this->takeServices($data));
|
||||
}
|
||||
|
||||
protected function afterCreate(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
|
||||
protected function afterSave(): void
|
||||
{
|
||||
$this->saveServices();
|
||||
$this->saveWebsites();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Concerns;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SiteDomain;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
|
||||
/**
|
||||
* The websites of a landlord and the addresses they answer on. These belong to the operator: the webspace
|
||||
* and the hosting are the operator's, and a landlord must not be able to point an address at themselves.
|
||||
*
|
||||
* Wiring a new domain to this directory stays a manual step at the hoster. What is kept here is the other
|
||||
* half: which host belongs to which website, and through it to which landlord.
|
||||
*
|
||||
* Holds no Filament hooks; EditsTenantSetup calls these.
|
||||
*/
|
||||
trait EditsTenantWebsites
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function fillWebsites(array $data): array
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['websites'] = $tenant->sites()->withoutGlobalScope('tenant')->with('domains')->get()
|
||||
->map(fn (Site $site): array => [
|
||||
'id' => $site->id,
|
||||
'name' => $site->name,
|
||||
'hosts' => $site->domains->pluck('host')->all(),
|
||||
])
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function takeWebsites(array $data): array
|
||||
{
|
||||
$this->websites = is_array($data['websites'] ?? null) ? array_values($data['websites']) : [];
|
||||
|
||||
$this->normaliseWebsites();
|
||||
|
||||
unset($data['websites']);
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cleans the entered addresses and refuses what already belongs elsewhere, before anything is written.
|
||||
*/
|
||||
private function normaliseWebsites(): void
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
foreach ($this->websites as $index => $website) {
|
||||
$hosts = [];
|
||||
|
||||
foreach ((array) ($website['hosts'] ?? []) as $host) {
|
||||
$host = SiteDomain::normalise(is_string($host) ? $host : null);
|
||||
|
||||
if ($host === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (in_array($host, $seen, true)) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Die Adresse '.$host.' ist mehrfach eingetragen.',
|
||||
]);
|
||||
}
|
||||
|
||||
$seen[] = $host;
|
||||
$hosts[] = $host;
|
||||
}
|
||||
|
||||
$this->websites[$index]['hosts'] = $hosts;
|
||||
}
|
||||
|
||||
$this->refuseForeignHosts($seen);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function refuseForeignHosts(array $hosts): void
|
||||
{
|
||||
$ownIds = collect($this->websites)->pluck('id')->filter()->all();
|
||||
|
||||
$taken = SiteDomain::query()
|
||||
->whereIn('host', $hosts)
|
||||
->whereNotIn('site_id', $ownIds ?: [0])
|
||||
->pluck('host');
|
||||
|
||||
if ($taken->isNotEmpty()) {
|
||||
throw ValidationException::withMessages([
|
||||
'data.websites' => 'Gehört bereits zu einer anderen Website: '.$taken->implode(', '),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the websites. A website that is new gets an empty home page straight away, because a website
|
||||
* without one answers 404 and the landlord would have no way in.
|
||||
*/
|
||||
private function saveWebsites(): void
|
||||
{
|
||||
$tenant = $this->record;
|
||||
|
||||
if (! $tenant instanceof Tenant) {
|
||||
return;
|
||||
}
|
||||
|
||||
app(TenantContext::class)->run($tenant, function () use ($tenant): void {
|
||||
$keep = [];
|
||||
|
||||
foreach ($this->websites as $website) {
|
||||
$name = trim((string) ($website['name'] ?? ''));
|
||||
|
||||
if ($name === '') {
|
||||
continue;
|
||||
}
|
||||
|
||||
$hosts = (array) ($website['hosts'] ?? []);
|
||||
$site = $this->siteFor($tenant, $website['id'] ?? null, $name, $hosts);
|
||||
|
||||
$keep[] = $site->id;
|
||||
|
||||
$site->domains()->whereNotIn('host', $hosts ?: [''])->delete();
|
||||
|
||||
foreach ($hosts as $host) {
|
||||
SiteDomain::query()->updateOrCreate(['host' => $host], ['site_id' => $site->id]);
|
||||
}
|
||||
}
|
||||
|
||||
$tenant->sites()->whereNotIn('id', $keep ?: [0])->each(fn (Site $site) => $site->delete());
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $hosts
|
||||
*/
|
||||
private function siteFor(Tenant $tenant, mixed $id, string $name, array $hosts): Site
|
||||
{
|
||||
$site = $id ? Site::query()->whereKey($id)->first() : null;
|
||||
|
||||
if ($site !== null) {
|
||||
$site->update(['name' => $name, 'domain' => $hosts[0] ?? null]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
|
||||
$site = Site::query()->create([
|
||||
'tenant_id' => $tenant->id,
|
||||
'name' => $name,
|
||||
'domain' => $hosts[0] ?? null,
|
||||
'is_default' => $tenant->sites()->count() === 0,
|
||||
'theme' => config('themes.base'),
|
||||
]);
|
||||
|
||||
Page::query()->create([
|
||||
'site_id' => $site->id,
|
||||
'slug' => Page::HOME,
|
||||
'title' => $name,
|
||||
'sections' => [],
|
||||
'is_published' => true,
|
||||
]);
|
||||
|
||||
return $site;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use BackedEnum;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* What applies to the whole installation: the limits every landlord is bound by, the delivery path, and
|
||||
* who opened whose admin. These values come from the server's .env and are deliberately not editable here –
|
||||
* they protect the system against the landlords, so a landlord's admin must not be able to reach them.
|
||||
*/
|
||||
class SystemOverview extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedServerStack;
|
||||
|
||||
protected static ?string $navigationLabel = 'System';
|
||||
|
||||
protected static ?string $title = 'System';
|
||||
|
||||
protected static ?string $slug = 'system';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
protected string $view = 'filament.operator.system-overview';
|
||||
|
||||
/**
|
||||
* The ceilings a landlord may tighten but never exceed.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function limits(): array
|
||||
{
|
||||
$config = app(TenantConfig::class);
|
||||
|
||||
$rows = [
|
||||
['Gästedaten löschen nach', 'fewo.guest_retention_years', 'Jahre', 'Ein Mandant kann kürzer löschen, nicht länger aufbewahren.'],
|
||||
['Nicht gebuchte Anfragen löschen nach', 'fewo.retention.inquiry_months', 'Monate', ''],
|
||||
['Portal-Mail-Auszug löschen nach', 'fewo.retention.portal_email_excerpt_days', 'Tage', ''],
|
||||
['Herkunftsangaben löschen nach', 'fewo.retention.attribution_months', 'Monate', ''],
|
||||
['Bot-Schutz: Mindestzeit im Formular', 'fewo.spam.min_seconds', 'Sekunden', 'Ein Mandant kann länger warten lassen, nicht kürzer.'],
|
||||
['Bot-Schutz: Anfragen je IP und Stunde', 'fewo.spam.per_ip_per_hour', '', ''],
|
||||
['Bot-Schutz: Anfragen je E-Mail und Tag', 'fewo.spam.per_email_per_day', '', ''],
|
||||
['Bot-Schutz: offene Anfragen je E-Mail', 'fewo.spam.open_requests_per_email', '', ''],
|
||||
['Bot-Schutz: Links im Text', 'fewo.spam.max_links', '', ''],
|
||||
];
|
||||
|
||||
return array_map(fn (array $row): array => [
|
||||
'label' => $row[0],
|
||||
'value' => trim($config->baselineValue($row[1]).' '.$row[2]),
|
||||
'note' => $row[3],
|
||||
], $rows);
|
||||
}
|
||||
|
||||
/**
|
||||
* Values that belong to the whole installation and to no landlord.
|
||||
*
|
||||
* @return list<array{label: string, value: string, note: string}>
|
||||
*/
|
||||
public function global(): array
|
||||
{
|
||||
$redirect = config('fewo.mail_redirect_to');
|
||||
|
||||
return [
|
||||
[
|
||||
'label' => 'Anfragen aller Websites zusammen',
|
||||
'value' => config('fewo.spam.total_per_hour').' je Stunde',
|
||||
'note' => 'Flutgrenze über alle Mandanten. Kein Mandant kann sie anheben.',
|
||||
],
|
||||
[
|
||||
'label' => 'Harte Mail-Umleitung',
|
||||
'value' => filled($redirect) ? (string) $redirect : 'nicht gesetzt',
|
||||
'note' => filled($redirect)
|
||||
? 'FEWO_MAIL_REDIRECT_TO: jede E-Mail dieses Servers geht hierhin, auch bei scharf geschalteten Mandanten.'
|
||||
: 'Ohne Umleitung entscheidet die Betriebsart des jeweiligen Mandanten.',
|
||||
],
|
||||
[
|
||||
'label' => 'Versandweg',
|
||||
'value' => (string) config('mail.default'),
|
||||
'note' => 'SMTP-Zugang und Datenbank sind Infrastruktur und liegen in der .env des Servers.',
|
||||
],
|
||||
[
|
||||
'label' => 'Datenbank-Sicherungen',
|
||||
'value' => config('fewo.backup.keep').' Stück',
|
||||
'note' => 'Eine Sicherung der ganzen Datenbank, über alle Mandanten.',
|
||||
],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, Tenant>
|
||||
*/
|
||||
public function tenants(): Collection
|
||||
{
|
||||
return Tenant::query()->withCount(['services' => fn ($query) => $query->where('is_enabled', true)])->orderBy('name')->get();
|
||||
}
|
||||
|
||||
public function wiredServiceCount(): int
|
||||
{
|
||||
return count(TenantServiceKey::wired());
|
||||
}
|
||||
|
||||
/**
|
||||
* @return Collection<int, TenantAccessLog>
|
||||
*/
|
||||
public function accessLog(): Collection
|
||||
{
|
||||
return TenantAccessLog::query()->with(['tenant', 'user'])->latest('created_at')->limit(20)->get();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Pages;
|
||||
|
||||
use App\Support\SystemSettings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
/**
|
||||
* The settings of the whole installation. They are the baseline every landlord is bound by, and a
|
||||
* landlord's admin never reaches this page.
|
||||
*
|
||||
* Empty means: the value from the server's .env applies again. Database credentials and APP_KEY are not
|
||||
* here and cannot be – they are needed to open the database and to decrypt what is stored in it.
|
||||
*/
|
||||
class SystemSettingsPage extends Page
|
||||
{
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedAdjustmentsHorizontal;
|
||||
|
||||
protected static ?string $navigationLabel = 'Einstellungen';
|
||||
|
||||
protected static ?string $title = 'Systemweite Einstellungen';
|
||||
|
||||
protected static ?string $slug = 'einstellungen';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
/** @var array<string, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [self::field($key) => SystemSettings::get($key)])
|
||||
->all());
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
$sections = collect(SystemSettings::EDITABLE)
|
||||
->groupBy(fn (array $definition): string => $definition[2], preserveKeys: true)
|
||||
->map(fn ($group, string $section) => Section::make($section)
|
||||
->columns(2)
|
||||
->schema($group->keys()->map(fn (string $key) => $this->field_($key))->all()));
|
||||
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Text::make('Leer lassen heißt: der Wert aus der .env des Servers gilt wieder. Datenbank-Zugang und APP_KEY stehen bewusst nicht hier – sie werden gebraucht, um die Datenbank überhaupt zu öffnen und das Gespeicherte zu entschlüsseln.'),
|
||||
...$sections->values()->all(),
|
||||
]);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Form::make([EmbeddedSchema::make('form')])
|
||||
->id('form')
|
||||
->livewireSubmitHandler('save')
|
||||
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
SystemSettings::save(collect(SystemSettings::EDITABLE)
|
||||
->mapWithKeys(fn (array $definition, string $key): array => [$key => $data[self::field($key)] ?? null])
|
||||
->all());
|
||||
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
/**
|
||||
* Config keys contain dots, which Filament would read as nesting.
|
||||
*/
|
||||
private static function field(string $key): string
|
||||
{
|
||||
return str_replace('.', '__', $key);
|
||||
}
|
||||
|
||||
private function field_(string $key): TextInput|Select
|
||||
{
|
||||
[$label, $kind, , $help] = SystemSettings::EDITABLE[$key];
|
||||
$name = self::field($key);
|
||||
|
||||
if ($kind === 'mailer') {
|
||||
return Select::make($name)
|
||||
->label($label)
|
||||
->helperText($help)
|
||||
->options(['smtp' => 'SMTP (echter Versand)', 'log' => 'Nur Logdatei (kein Versand)', 'array' => 'Verwerfen (nur für Tests)']);
|
||||
}
|
||||
|
||||
$field = TextInput::make($name)->label($label)->helperText($help);
|
||||
|
||||
return match ($kind) {
|
||||
'int' => $field->numeric()->integer()->minValue(0),
|
||||
'secret' => $field->password()->revealable()->autocomplete(false),
|
||||
default => $field,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\ListTenants;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class TenantResource extends Resource
|
||||
{
|
||||
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('Zugang freigeschaltet')
|
||||
->helperText('Ausgeschaltet sehen Besucher statt der Webseite nur den Hinweis unten. Der Betreiber kommt weiter hinein.')
|
||||
->default(true)
|
||||
->live(),
|
||||
Textarea::make('suspended_message')
|
||||
->label('Hinweis bei gesperrtem Zugang')
|
||||
->placeholder('Diese Webseite ist zurzeit nicht erreichbar. Bitte versuchen Sie es später noch einmal.')
|
||||
->helperText('Leer = der Standardtext. Wird mit Status 503 ausgeliefert, damit Suchmaschinen die Seite nicht aus dem Index werfen.')
|
||||
->rows(2)
|
||||
->columnSpanFull(),
|
||||
Section::make('Einsprungsadressen')
|
||||
->description('Unter welchen Adressen dieser Mandant antwortet. Die Adresse muss zusätzlich beim Hoster einmalig auf dieses Verzeichnis gelegt werden – das passiert nicht hier. Ab dem zweiten Mandanten bekommt jede nicht eingetragene Adresse eine Fehlerseite.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
Repeater::make('websites')
|
||||
->label('Websites')
|
||||
->addActionLabel('Weitere Website')
|
||||
->defaultItems(1)
|
||||
->itemLabel(fn (array $state): ?string => $state['name'] ?? null)
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
TextInput::make('name')
|
||||
->label('Name der Website')
|
||||
->required()
|
||||
->maxLength(120),
|
||||
TagsInput::make('hosts')
|
||||
->label('Adressen')
|
||||
->placeholder('beispiel.de')
|
||||
->helperText('Jede Schreibweise ist eine eigene Adresse: „www.beispiel.de“ und „beispiel.de“ sind zwei. Die erste gilt als Hauptadresse und steht in Links an Gäste.')
|
||||
->nestedRecursiveRules(['string', 'max:190']),
|
||||
]),
|
||||
]),
|
||||
Section::make('Dienste')
|
||||
->description('Was dieser Mandant nutzen darf. Ein gesperrter Dienst verschwindet auch aus seinem Admin – die Rolle eines Benutzers kann das nicht aufwiegen.')
|
||||
->columnSpanFull()
|
||||
->schema([
|
||||
...array_map(fn (TenantServiceKey $service): Toggle => Toggle::make('services.'.$service->value.'.is_enabled')
|
||||
->label($service->label())
|
||||
->helperText($service->description()), TenantServiceKey::wired()),
|
||||
Text::make('Noch nicht gebaut und deshalb nicht schaltbar: '.implode(', ', array_map(
|
||||
fn (TenantServiceKey $service): string => $service->label(),
|
||||
array_values(array_filter(TenantServiceKey::cases(), fn (TenantServiceKey $service): bool => ! $service->isWired())),
|
||||
)).'. Diese Dienste erscheinen hier, sobald die Anwendung sie wirklich abfragt; eigene API-Schlüssel gehören dann in den Admin des Mandanten.'),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kurzname'),
|
||||
TextColumn::make('services_count')
|
||||
->label('Dienste frei')
|
||||
->counts(['services' => fn (Builder $query): Builder => $query->where('is_enabled', true)])
|
||||
->suffix(' von '.count(TenantServiceKey::wired())),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
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,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\Concerns\EditsTenantSetup;
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
use EditsTenantSetup;
|
||||
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
|
||||
class ListTenants extends ListRecords
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()
|
||||
->label('Neuen Mandanten anlegen')
|
||||
->icon(Heroicon::OutlinedPlus),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -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';
|
||||
@@ -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,312 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\TenantServiceKey;
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\Settings;
|
||||
use App\Tenancy\TenantConfig;
|
||||
use App\Tenancy\TenantFeatures;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
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 data of the landlord: operating mode (test mode sends every e-mail to one test recipient only;
|
||||
* live delivers to the real recipients), the addresses of the internal communication, the landlord's own
|
||||
* address and bank details, and the periods. Administrators only.
|
||||
*/
|
||||
class Operations extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
/** Periods and counters the landlord may set (column => label). Empty means the system default. */
|
||||
private const PERIODS = [
|
||||
'deposit_due_days' => 'Anzahlung fällig nach (Tage)',
|
||||
'review_request_after_days' => 'Bewertungsbitte nach Abreise (Tage)',
|
||||
'guest_retention_years' => 'Gästedaten löschen nach (Jahre)',
|
||||
'retention_inquiry_months' => 'Nicht gebuchte Anfragen löschen nach (Monate)',
|
||||
'retention_portal_email_excerpt_days' => 'Portal-Mail-Auszug löschen nach (Tage)',
|
||||
'retention_attribution_months' => 'Herkunftsangaben löschen nach (Monate)',
|
||||
'spam_min_seconds' => 'Bot-Schutz: Mindestzeit im Formular (Sekunden)',
|
||||
'spam_per_ip_per_hour' => 'Bot-Schutz: Anfragen je IP und Stunde',
|
||||
'spam_per_email_per_day' => 'Bot-Schutz: Anfragen je E-Mail und Tag',
|
||||
'spam_open_requests_per_email' => 'Bot-Schutz: gleichzeitig offene Anfragen je E-Mail',
|
||||
'spam_max_links' => 'Bot-Schutz: erlaubte Links im Text',
|
||||
'channel_stale_after_minutes' => 'Portal-Abgleich gilt als veraltet nach (Minuten)',
|
||||
'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)',
|
||||
];
|
||||
|
||||
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, mixed> */
|
||||
public array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$tenant = $this->tenant();
|
||||
|
||||
$this->form->fill([
|
||||
'mode' => $tenant->operating_mode ?: Settings::MODE_TEST,
|
||||
'test_recipient' => $tenant->test_recipient ?: auth()->user()?->email,
|
||||
'notification_recipients' => $tenant->notificationRecipients(),
|
||||
'contact_email' => $tenant->contact_email,
|
||||
'sender_name' => $tenant->sender_name,
|
||||
'sender_email' => $tenant->sender_email,
|
||||
'owner_name' => $tenant->owner_name,
|
||||
'owner_street' => $tenant->owner_street,
|
||||
'owner_city' => $tenant->owner_city,
|
||||
'owner_phone' => $tenant->owner_phone,
|
||||
'bank_account_holder' => $tenant->bank_account_holder,
|
||||
'bank_name' => $tenant->bank_name,
|
||||
'bank_iban' => $tenant->bank_iban,
|
||||
'bank_bic' => $tenant->bank_bic,
|
||||
'tax_note' => $tenant->tax_note,
|
||||
'mailbox_host' => $tenant->mailbox_host,
|
||||
'mailbox_port' => $tenant->mailbox_port,
|
||||
'mailbox_username' => $tenant->mailbox_username,
|
||||
'mailbox_password' => $tenant->mailbox_password,
|
||||
'mailbox_encryption' => $tenant->mailbox_encryption,
|
||||
'mailbox_folder' => $tenant->mailbox_folder,
|
||||
...$this->periodValues($tenant),
|
||||
]);
|
||||
}
|
||||
|
||||
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(),
|
||||
]),
|
||||
Section::make('Vermieterin')
|
||||
->description('Steht in E-Mails, im Angebot, im Mietvertrag und auf der Webseite.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('owner_name')->label('Name')->required()->maxLength(255),
|
||||
TextInput::make('owner_phone')->label('Telefon')->maxLength(50),
|
||||
TextInput::make('owner_street')->label('Straße und Hausnummer')->maxLength(255),
|
||||
TextInput::make('owner_city')->label('PLZ und Ort')->maxLength(255),
|
||||
]),
|
||||
Section::make('Bankverbindung und Steuer')
|
||||
->description('Steht im Mietvertrag und in den Zahlungsaufforderungen. Die Angaben liegen verschlüsselt in der Datenbank.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TextInput::make('bank_account_holder')->label('Kontoinhaber')->maxLength(255),
|
||||
TextInput::make('bank_name')->label('Bank')->maxLength(255),
|
||||
TextInput::make('bank_iban')->label('IBAN')->maxLength(40),
|
||||
TextInput::make('bank_bic')->label('BIC')->maxLength(20),
|
||||
TextInput::make('tax_note')
|
||||
->label('Steuerangabe')
|
||||
->helperText('Zum Beispiel die Steuernummer oder der Hinweis auf die Kleinunternehmerregelung.')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Portal-Postfach')
|
||||
->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.')
|
||||
->columns(2)
|
||||
->collapsed()
|
||||
->visible(fn (): bool => app(TenantFeatures::class)->enabled(TenantServiceKey::PortalMail))
|
||||
->schema([
|
||||
TextInput::make('mailbox_host')->label('IMAP-Server')->maxLength(190),
|
||||
TextInput::make('mailbox_port')->label('Port')->numeric()->integer()->placeholder('993'),
|
||||
TextInput::make('mailbox_username')->label('Benutzer')->maxLength(190),
|
||||
TextInput::make('mailbox_password')->label('Passwort')->password()->revealable()->autocomplete(false)->maxLength(190),
|
||||
Select::make('mailbox_encryption')
|
||||
->label('Verschlüsselung')
|
||||
->options(['ssl' => 'SSL', 'tls' => 'TLS', 'starttls' => 'STARTTLS'])
|
||||
->placeholder('SSL'),
|
||||
TextInput::make('mailbox_folder')->label('Ordner')->placeholder('INBOX')->maxLength(190),
|
||||
]),
|
||||
Section::make('Fristen und Grenzen')
|
||||
->description('Leer bedeutet: die Vorgabe des Systems gilt. Löschfristen und Bot-Schutz lassen sich verschärfen, aber nicht über die Vorgabe hinaus lockern.')
|
||||
->columns(3)
|
||||
->collapsed()
|
||||
->schema($this->periodFields()),
|
||||
]);
|
||||
}
|
||||
|
||||
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();
|
||||
$tenant = $this->tenant();
|
||||
$wasLive = $tenant->isLive();
|
||||
|
||||
$tenant->update([
|
||||
'operating_mode' => $data['mode'],
|
||||
'test_recipient' => $data['test_recipient'] ?? $tenant->test_recipient,
|
||||
'notification_emails' => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
|
||||
'contact_email' => $data['contact_email'],
|
||||
'sender_name' => $data['sender_name'],
|
||||
'sender_email' => $data['sender_email'],
|
||||
'owner_name' => $data['owner_name'],
|
||||
'owner_street' => $data['owner_street'] ?? null,
|
||||
'owner_city' => $data['owner_city'] ?? null,
|
||||
'owner_phone' => $data['owner_phone'] ?? null,
|
||||
'bank_account_holder' => $data['bank_account_holder'] ?? null,
|
||||
'bank_name' => $data['bank_name'] ?? null,
|
||||
'bank_iban' => $data['bank_iban'] ?? null,
|
||||
'bank_bic' => $data['bank_bic'] ?? null,
|
||||
'tax_note' => $data['tax_note'] ?? null,
|
||||
'mailbox_host' => $data['mailbox_host'] ?? null,
|
||||
'mailbox_port' => filled($data['mailbox_port'] ?? null) ? (int) $data['mailbox_port'] : null,
|
||||
'mailbox_username' => $data['mailbox_username'] ?? null,
|
||||
'mailbox_password' => $data['mailbox_password'] ?? null,
|
||||
'mailbox_encryption' => $data['mailbox_encryption'] ?? null,
|
||||
'mailbox_folder' => $data['mailbox_folder'] ?? null,
|
||||
...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)),
|
||||
]);
|
||||
|
||||
app(TenantConfig::class)->refresh();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && ! $wasLive) {
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The landlord this page edits: the one of the request, else the only one there is.
|
||||
*/
|
||||
private function tenant(): Tenant
|
||||
{
|
||||
$tenant = Settings::tenant();
|
||||
|
||||
abort_if($tenant === null, 404);
|
||||
|
||||
return $tenant;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, ?int>
|
||||
*/
|
||||
private function periodValues(Tenant $tenant): array
|
||||
{
|
||||
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): ?int => $tenant->{$column}, array_keys(self::PERIODS)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function periodInput(array $data): array
|
||||
{
|
||||
return array_combine(array_keys(self::PERIODS), array_map(fn (string $column): mixed => $data[$column] ?? null, array_keys(self::PERIODS)));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<TextInput>
|
||||
*/
|
||||
private function periodFields(): array
|
||||
{
|
||||
return array_map(function (string $column) {
|
||||
$field = TextInput::make($column)
|
||||
->label(self::PERIODS[$column])
|
||||
->numeric()
|
||||
->integer()
|
||||
->minValue(0);
|
||||
|
||||
$config = app(TenantConfig::class);
|
||||
|
||||
if (($ceiling = $config->ceilingFor($column)) !== null) {
|
||||
return $field->maxValue($ceiling)->helperText('Vorgabe des Systems: höchstens '.$ceiling);
|
||||
}
|
||||
|
||||
if (($floor = $config->floorFor($column)) !== null) {
|
||||
return $field->minValue($floor)->helperText('Vorgabe des Systems: mindestens '.$floor);
|
||||
}
|
||||
|
||||
return $field;
|
||||
}, array_keys(self::PERIODS));
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class AppearanceResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Appearance::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
|
||||
|
||||
@@ -2,17 +2,23 @@
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Photo;
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SpecialOffer;
|
||||
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;
|
||||
|
||||
@@ -39,19 +45,18 @@ public static function configure(Schema $schema): Schema
|
||||
Toggle::make('is_default')->label('Standard (wenn kein Zeitraum passt)')->inline(false),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
|
||||
]),
|
||||
Section::make('Bild & Angebot')
|
||||
->columns(2)
|
||||
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([
|
||||
Select::make('hero_photo_id')
|
||||
PhotoSelect::make('hero_photo_id')
|
||||
->label('Titelbild')
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->searchable()
|
||||
->placeholder('Bild der Seite verwenden'),
|
||||
Select::make('featured_offer_id')
|
||||
->label('Hervorgehobenes Sonderangebot')
|
||||
->options(fn (): array => SpecialOffer::query()->where('is_active', true)->pluck('name', 'id')->all())
|
||||
->placeholder('keins'),
|
||||
]),
|
||||
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)
|
||||
@@ -69,14 +74,68 @@ public static function configure(Schema $schema): Schema
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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'): array
|
||||
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens', ?string $themeKey = null): array
|
||||
{
|
||||
$theme = Site::find($siteId)?->theme ?? config('themes.base');
|
||||
$theme = $themeKey ?: (Site::find($siteId)?->theme ?? config('themes.base'));
|
||||
|
||||
return collect(app(ThemeRegistry::class)->get($theme)->tokens)
|
||||
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();
|
||||
|
||||
@@ -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,6 +3,7 @@
|
||||
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;
|
||||
@@ -20,6 +21,8 @@
|
||||
|
||||
class BookingResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Booking::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
|
||||
|
||||
@@ -4,19 +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
|
||||
@@ -33,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),
|
||||
])
|
||||
@@ -52,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([
|
||||
@@ -66,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(),
|
||||
])
|
||||
@@ -117,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;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -13,6 +14,8 @@
|
||||
|
||||
class ChannelTaskResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = ChannelTask::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\FloorPlans\Pages\CreateFloorPlan;
|
||||
use App\Filament\Resources\FloorPlans\Pages\EditFloorPlan;
|
||||
use App\Filament\Resources\FloorPlans\Pages\ListFloorPlans;
|
||||
use App\Filament\Resources\FloorPlans\Schemas\FloorPlanForm;
|
||||
use App\Filament\Resources\FloorPlans\Tables\FloorPlansTable;
|
||||
use App\Models\FloorPlan;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Floor plan per apartment: picture from the website photos plus rooms drawn on it (section "Grundriss").
|
||||
*/
|
||||
class FloorPlanResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = FloorPlan::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMap;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
|
||||
protected static ?string $modelLabel = 'Grundriss';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Grundriss';
|
||||
|
||||
protected static ?int $navigationSort = 5;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return FloorPlanForm::configure($schema);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return FloorPlansTable::configure($table);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListFloorPlans::route('/'),
|
||||
'create' => CreateFloorPlan::route('/create'),
|
||||
'edit' => EditFloorPlan::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans\Pages;
|
||||
|
||||
use App\Filament\Resources\FloorPlans\FloorPlanResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateFloorPlan extends CreateRecord
|
||||
{
|
||||
protected static string $resource = FloorPlanResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans\Pages;
|
||||
|
||||
use App\Filament\Resources\FloorPlans\FloorPlanResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditFloorPlan extends EditRecord
|
||||
{
|
||||
protected static string $resource = FloorPlanResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans\Pages;
|
||||
|
||||
use App\Filament\Resources\FloorPlans\FloorPlanResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListFloorPlans extends ListRecords
|
||||
{
|
||||
protected static string $resource = FloorPlanResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Amenity;
|
||||
use App\Models\FloorPlan;
|
||||
use App\Models\Property;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Repeater;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Forms\Components\ViewField;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class FloorPlanForm
|
||||
{
|
||||
public static function configure(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->value('id'))
|
||||
->unique(ignoreRecord: true)
|
||||
->validationMessages(['unique' => 'Für diese Wohnung gibt es schon einen Grundriss.'])
|
||||
->required()
|
||||
->live(),
|
||||
PhotoSelect::make('photo_id')
|
||||
->label('Grundriss-Bild')
|
||||
->helperText('Rendering oder Plan aus Webseite › Fotos. Ein neues Bild im gleichen Ausschnitt behält die Räume.')
|
||||
->required()
|
||||
->live(),
|
||||
Repeater::make('rooms')
|
||||
->label('Räume')
|
||||
->columnSpanFull()
|
||||
->defaultItems(0)
|
||||
->addActionLabel('Raum hinzufügen')
|
||||
->reorderable()
|
||||
->collapsible()
|
||||
->itemLabel(fn (array $state): string => filled($state['name'] ?? null) ? $state['name'] : 'Neuer Raum')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Hidden::make('id')->default(fn (): string => (string) Str::uuid()),
|
||||
TextInput::make('name')->label('Name')->placeholder('z. B. Schlafzimmer')->required()->maxLength(60)->live(onBlur: true),
|
||||
Toggle::make('is_visible')->label('Auf der Website zeigen')->default(true)->inline(false),
|
||||
ViewField::make('points')
|
||||
->label('Fläche auf dem Grundriss')
|
||||
->view('filament.forms.floor-plan-area')
|
||||
->columnSpanFull()
|
||||
->rules([
|
||||
fn (): Closure => function (string $attribute, mixed $value, Closure $fail): void {
|
||||
if (count(FloorPlan::points(is_string($value) ? $value : null)) < 3) {
|
||||
$fail('Bitte mindestens drei Ecken des Raums auf dem Bild anklicken.');
|
||||
}
|
||||
},
|
||||
]),
|
||||
Textarea::make('description')->label('Beschreibung')->rows(3)->maxLength(400)->columnSpanFull(),
|
||||
PhotoSelect::make('photo_ids')->label('Fotos')->multiple()->helperText('Das erste Foto steht oben, die weiteren als kleine Bilder darunter.'),
|
||||
Select::make('amenity_ids')
|
||||
->label('Ausstattung')
|
||||
->multiple()
|
||||
->searchable()
|
||||
->options(fn (Get $get): array => Amenity::query()->where('property_id', $get('../../property_id'))->orderBy('sort_order')->pluck('name', 'id')->all())
|
||||
->helperText('Aus Webseite › Ausstattung – nichts doppelt pflegen.'),
|
||||
TextInput::make('hint')
|
||||
->label('Hinweis zur Barrierefreiheit (optional)')
|
||||
->placeholder('z. B. Flache Dusche mit kleiner Kante')
|
||||
->maxLength(160)
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\FloorPlans\Tables;
|
||||
|
||||
use App\Models\FloorPlan;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class FloorPlansTable
|
||||
{
|
||||
public static function configure(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->paginated(false)
|
||||
->columns([
|
||||
TextColumn::make('property.name')->label('Wohnung'),
|
||||
TextColumn::make('rooms')->label('Räume')
|
||||
->state(fn (FloorPlan $record): string => $record->visibleRooms()->pluck('name')->implode(', ') ?: 'noch keine'),
|
||||
TextColumn::make('updated_at')->label('Geändert')->since(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
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;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class PageResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Page::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentDuplicate;
|
||||
|
||||
@@ -28,7 +28,7 @@ public static function configure(Schema $schema): Schema
|
||||
->schema([
|
||||
Builder::make('sections')
|
||||
->hiddenLabel()
|
||||
->blocks(fn (): array => app(SectionRegistry::class)->blocks())
|
||||
->blocks(fn (callable $get): array => app(SectionRegistry::class)->blocks($get('site_id')))
|
||||
->addActionLabel('Baustein hinzufügen')
|
||||
->collapsible()
|
||||
->collapsed()
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -21,6 +21,7 @@ public static function configure(Schema $schema): Schema
|
||||
SpatieMediaLibraryFileUpload::make('image')
|
||||
->label('Bild')
|
||||
->collection(Photo::COLLECTION)
|
||||
->disk('public')
|
||||
->image()
|
||||
->imageEditor()
|
||||
->maxSize(25 * 1024)
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\PortalEmails;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
|
||||
use App\Filament\Resources\PortalEmails\Tables\PortalEmailsTable;
|
||||
use App\Models\PortalEmail;
|
||||
@@ -14,6 +15,8 @@
|
||||
|
||||
class PortalEmailResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = PortalEmail::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelopeOpen;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Properties;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Properties\Pages\CreateProperty;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\Pages\ListProperties;
|
||||
@@ -22,6 +23,8 @@
|
||||
|
||||
class PropertyResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Property::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHomeModern;
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
@@ -35,6 +36,8 @@
|
||||
|
||||
class SeasonsRelationManager extends RelationManager
|
||||
{
|
||||
public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
|
||||
|
||||
protected static string $relationship = 'seasons';
|
||||
|
||||
protected static ?string $title = 'Saisons & Preise';
|
||||
@@ -111,6 +114,7 @@ public function table(Table $table): Table
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
$this->copyToNextYearAction(),
|
||||
$this->minimumStayRulesAction(),
|
||||
$this->priceCalculatorAction(),
|
||||
])
|
||||
->recordActions([
|
||||
@@ -179,22 +183,52 @@ private function seasonYears(): array
|
||||
return $years->combine($years)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* The relaxations of the seasons' minimum stay, edited where the seasons are maintained.
|
||||
*/
|
||||
private function minimumStayRulesAction(): Action
|
||||
{
|
||||
return Action::make('minimumStayRules')
|
||||
->label('Regeln Mindestaufenthalt')
|
||||
->icon(Heroicon::OutlinedAdjustmentsHorizontal)
|
||||
->color('gray')
|
||||
->modalHeading('Mindestaufenthalt – Ausnahmen')
|
||||
->modalDescription('Jede Saison hat ihre Mindestnächte. Diese Regeln erlauben kürzere Aufenthalte, wenn sie den Kalender nicht zerstückeln. Sonderangebote können den Mindestaufenthalt zusätzlich aufheben.')
|
||||
->fillForm(fn (): array => $this->getOwnerRecord()->only(['changeover_weekday', 'min_stay_fill_gaps', 'min_stay_until_changeover', 'min_stay_absolute']))
|
||||
->schema([
|
||||
Select::make('changeover_weekday')->label('Typischer An- und Abreisetag')->options(self::WEEKDAYS)->placeholder('keiner'),
|
||||
Toggle::make('min_stay_fill_gaps')->label('Kalenderlücken: kürzer erlaubt, wenn die Buchung eine Lücke zwischen zwei Belegungen vollständig füllt'),
|
||||
Toggle::make('min_stay_until_changeover')->label('Kürzer erlaubt, wenn die Buchung am typischen Anreisetag endet (die Woche danach bleibt frei buchbar)'),
|
||||
TextInput::make('min_stay_absolute')->label('Untergrenze für alle Ausnahmen')->integer()->minValue(1)->maxValue(14)->suffix('Nächte')->required(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$this->getOwnerRecord()->update($data);
|
||||
Notification::make()->title('Regeln gespeichert')->success()->send();
|
||||
});
|
||||
}
|
||||
|
||||
private function copyToNextYearAction(): Action
|
||||
{
|
||||
return Action::make('copyToNextYear')
|
||||
->label('In Folgejahr kopieren')
|
||||
->icon(Heroicon::OutlinedDocumentDuplicate)
|
||||
->color('gray')
|
||||
->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit gleichen Kalenderdaten und Preisen ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.')
|
||||
->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit Preisen und Mindestnächten ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.')
|
||||
->schema([
|
||||
Select::make('year')
|
||||
->label('Jahr kopieren')
|
||||
->options(fn (): array => $this->seasonYears())
|
||||
->default((string) now()->year)
|
||||
->required(),
|
||||
Select::make('weekday')
|
||||
->label('Saisonbeginn legen auf')
|
||||
->helperText('Jeder Saisonbeginn wird auf den nächstgelegenen Wochentag verschoben (höchstens 3 Tage); aneinandergrenzende Saisons bleiben lückenlos.')
|
||||
->options(self::WEEKDAYS)
|
||||
->placeholder('gleiche Kalenderdaten wie im Vorjahr')
|
||||
->default(fn (): ?int => $this->getOwnerRecord()->changeover_weekday),
|
||||
])
|
||||
->action(function (array $data, CopySeasonsToNextYear $copySeasons): void {
|
||||
$result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year']);
|
||||
$result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year'], filled($data['weekday'] ?? null) ? (int) $data['weekday'] : null);
|
||||
|
||||
Notification::make()
|
||||
->title("{$result['created']} Saisons nach ".((int) $data['year'] + 1).' kopiert')
|
||||
|
||||
+94
-19
@@ -3,8 +3,8 @@
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Enums\DiscountType;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Models\SpecialOffer;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
@@ -12,12 +12,14 @@
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
@@ -33,10 +35,48 @@ class SpecialOffersRelationManager extends RelationManager
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sonderangebote';
|
||||
|
||||
/**
|
||||
* Starting points for typical offers in the create form.
|
||||
*
|
||||
* @var array<string, array{label: string, values: array<string, mixed>}>
|
||||
*/
|
||||
private const PRESETS = [
|
||||
'last_minute' => ['label' => 'Last Minute (−15 %, bis 14 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Last Minute', 'discount_type' => 'percent', 'discount_value' => 15, 'max_days_before_arrival' => 14]],
|
||||
'early_bird' => ['label' => 'Frühbucher (−5 %, ab 180 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Frühbucher', 'discount_type' => 'percent', 'discount_value' => 5, 'min_days_before_arrival' => 180]],
|
||||
'long_stay' => ['label' => 'Längerer Aufenthalt (ab 3 Nächten −10 %)', 'values' => ['kind' => 'rule', 'name' => 'Ab 3 Nächten', 'discount_type' => 'percent', 'discount_value' => 10, 'min_nights' => 3]],
|
||||
'week' => ['label' => '7 = 6 (eine Nacht gratis ab 7 Nächten)', 'values' => ['kind' => 'rule', 'name' => '7 Nächte bleiben, 6 bezahlen', 'discount_type' => 'free_nights', 'discount_value' => 1, 'min_nights' => 7]],
|
||||
'weekend' => ['label' => 'Special Weekend (Anreise Freitag, 2 Nächte)', 'values' => ['kind' => 'rule', 'name' => 'Special Weekend', 'discount_type' => 'percent', 'discount_value' => 10, 'arrival_weekdays' => [5], 'min_nights' => 2, 'max_nights' => 2]],
|
||||
'gap' => ['label' => 'Lückenfüller (Lücken bis 4 Nächte −20 %)', 'values' => ['kind' => 'gap_filler', 'name' => 'Kurzfristige Lücke', 'discount_type' => 'percent', 'discount_value' => 20, 'max_gap_nights' => 4, 'waives_min_stay' => true]],
|
||||
'fixed_week' => ['label' => 'Fester Termin (eine Woche zum Pauschalpreis)', 'values' => ['kind' => 'fixed_dates', 'name' => 'Ostsee-Woche', 'discount_type' => 'fixed_stay_price']],
|
||||
];
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Art des Angebots')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('preset')
|
||||
->label('Vorlage (optional)')
|
||||
->helperText('Füllt typische Einstellungen vor – alles bleibt änderbar.')
|
||||
->options(collect(self::PRESETS)->map(fn (array $preset): string => $preset['label'])->all())
|
||||
->dehydrated(false)
|
||||
->live()
|
||||
->afterStateUpdated(function (?string $state, Set $set): void {
|
||||
foreach (self::PRESETS[$state]['values'] ?? [] as $field => $value) {
|
||||
$set($field, $value);
|
||||
}
|
||||
})
|
||||
->visibleOn('create'),
|
||||
Radio::make('kind')
|
||||
->label('Art')
|
||||
->options(OfferKind::class)
|
||||
->default(OfferKind::Rule)
|
||||
->live()
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Angebot')
|
||||
->columns(2)
|
||||
->schema([
|
||||
@@ -60,24 +100,54 @@ public function form(Schema $schema): Schema
|
||||
DiscountType::AmountPerStay => 'Rabatt pro Aufenthalt',
|
||||
DiscountType::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
DiscountType::FreeNights => 'Anzahl Gratis-Nächte',
|
||||
DiscountType::FixedStayPrice => 'Pauschalpreis für alle Nächte',
|
||||
})
|
||||
->suffix(fn (Get $get): string => match ($this->discountType($get)) {
|
||||
DiscountType::Percent => '%',
|
||||
DiscountType::FreeNights => 'Nächte',
|
||||
default => '€',
|
||||
})
|
||||
->helperText(fn (Get $get): ?string => $this->discountType($get) === DiscountType::FreeNights ? 'Die günstigsten Nächte des Aufenthalts sind gratis.' : null)
|
||||
->helperText(fn (Get $get): ?string => match ($this->discountType($get)) {
|
||||
DiscountType::FreeNights => 'Die günstigsten Nächte des Aufenthalts sind gratis.',
|
||||
DiscountType::FixedStayPrice => 'Übernachtungen zusammen; Endreinigung und Extras kommen dazu.',
|
||||
default => null,
|
||||
})
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->required()
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $this->isMoney($record?->discount_type) ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->isMoney($this->discountType($get)) ? (int) round((float) $state * 100) : (int) $state),
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $record?->discount_type?->isMoney() ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->discountType($get)->isMoney() ? (int) round((float) $state * 100) : (int) $state),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true),
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_combinable')
|
||||
->label('Mit anderen kombinierbaren Angeboten kombinierbar')
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.')
|
||||
->columnSpanFull(),
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.'),
|
||||
Toggle::make('waives_min_stay')
|
||||
->label('Mindestaufenthalt der Saison aufheben')
|
||||
->helperText('Wenn das Angebot gilt, darf der Aufenthalt kürzer sein als die Mindestnächte der Saison (z. B. Special Weekend mit 2 Nächten, kurze Lücke).'),
|
||||
]),
|
||||
Section::make('Bewerbung auf der Webseite')
|
||||
->description('Welche Angebote gerade erscheinen, ergibt sich automatisch: aktiv, ohne Aktionscode, im Buchungszeitraum, feste Termine nur solange frei, Lückenfüller je gefundener Lücke. Mehrere gleichzeitig werden im Baustein „Sonderangebote“ nebeneinander, als Liste oder rollierend gezeigt.')
|
||||
->columns(3)
|
||||
->schema([
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_featured')->label('Hervorheben')->helperText('Steht vorne, ist farbig markiert und erscheint im Titelbereich.'),
|
||||
TextInput::make('priority')->label('Priorität')->helperText('Höher = weiter vorne')->integer()->default(0),
|
||||
]),
|
||||
Section::make('Termin')
|
||||
->description('Der Gast muss genau diesen Zeitraum buchen. Beworben wird er nur, solange er frei ist.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates)
|
||||
->schema([
|
||||
DatePicker::make('stay_from')->label('Anreise')->required(),
|
||||
DatePicker::make('stay_until')->label('Abreise')->after('stay_from')->required(),
|
||||
]),
|
||||
Section::make('Kalenderlücken')
|
||||
->description('Freie Zeiträume zwischen zwei Buchungen oder Sperrzeiten. Die Webseite zeigt bis zu drei gefundene Lücken mit Termin und Preis.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::GapFiller)
|
||||
->schema([
|
||||
TextInput::make('max_gap_nights')->label('Lücken bis höchstens … Nächte')->integer()->minValue(1)->default(4)->required(),
|
||||
|
||||
]),
|
||||
Section::make('Bedingungen')
|
||||
->description('Leere Felder bedeuten: keine Einschränkung.')
|
||||
@@ -103,15 +173,15 @@ public function form(Schema $schema): Schema
|
||||
->helperText('Frühbucher, z. B. 180')
|
||||
->integer()
|
||||
->minValue(0),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
CheckboxList::make('arrival_weekdays')
|
||||
->label('Anreise nur am')
|
||||
->options([1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'])
|
||||
->columns(7)
|
||||
->columnSpanFull(),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab'),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am'),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DateTimePicker::make('bookable_from')->label('Buchbar ab')->seconds(false),
|
||||
DateTimePicker::make('bookable_until')->label('Buchbar bis')->seconds(false),
|
||||
]),
|
||||
@@ -122,19 +192,22 @@ public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->defaultSort('priority', 'desc')
|
||||
->description('Sonderangebote werden bei jeder Preisberechnung automatisch geprüft und angewendet.')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Angebot')
|
||||
->description(fn (SpecialOffer $record): ?string => $record->public_description),
|
||||
TextColumn::make('kind')->label('Art')->badge(),
|
||||
TextColumn::make('discount')
|
||||
->label('Vorteil')
|
||||
->state(fn (SpecialOffer $record): string => match ($record->discount_type) {
|
||||
DiscountType::Percent => "−{$record->discount_value} %",
|
||||
DiscountType::AmountPerStay => '−'.Money::format($record->discount_value),
|
||||
DiscountType::NightlyRate => Money::format($record->discount_value).' / Nacht',
|
||||
DiscountType::FreeNights => "{$record->discount_value} Nacht/Nächte gratis",
|
||||
}),
|
||||
->state(fn (SpecialOffer $record): string => $record->advantageLabel()),
|
||||
TextColumn::make('conditions')
|
||||
->label('Bedingungen')
|
||||
->state(fn (SpecialOffer $record): string => implode(' · ', $record->conditionSummary()) ?: '–')
|
||||
->wrap(),
|
||||
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean(),
|
||||
TextColumn::make('priority')->label('Priorität')->sortable(),
|
||||
TextColumn::make('code')->label('Code')->placeholder('automatisch')->badge(),
|
||||
TextColumn::make('season_names')->label('Saisons')->badge()->placeholder('alle'),
|
||||
IconColumn::make('is_combinable')->label('Kombinierbar')->boolean(),
|
||||
@@ -157,8 +230,10 @@ private function discountType(Get $get): DiscountType
|
||||
return $type instanceof DiscountType ? $type : (DiscountType::tryFrom((string) $type) ?? DiscountType::Percent);
|
||||
}
|
||||
|
||||
private function isMoney(?DiscountType $type): bool
|
||||
private function kind(Get $get): OfferKind
|
||||
{
|
||||
return in_array($type, [DiscountType::AmountPerStay, DiscountType::NightlyRate], true);
|
||||
$kind = $get('kind');
|
||||
|
||||
return $kind instanceof OfferKind ? $kind : (OfferKind::tryFrom((string) $kind) ?? OfferKind::Rule);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Properties\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\EuroInput;
|
||||
use App\ImageWorlds\ImageWorldRegistry;
|
||||
use App\Models\Site;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -52,6 +53,11 @@ public static function configure(Schema $schema): Schema
|
||||
->label('Website')
|
||||
->options(fn (): array => Site::query()->pluck('name', 'id')->all())
|
||||
->placeholder('keine'),
|
||||
Select::make('image_world')
|
||||
->label('Bildwelt')
|
||||
->options(fn (): array => app(ImageWorldRegistry::class)->options())
|
||||
->placeholder('wie die Website')
|
||||
->helperText('Nur setzen, wenn diese Wohnung anders aussehen soll als die Website – etwa eine Bergwohnung auf einer Küsten-Website.'),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv (auf der Webseite buchbar)')
|
||||
->default(true),
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Reviews;
|
||||
|
||||
use App\Enums\ReviewStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Reviews\Pages\CreateReview;
|
||||
use App\Filament\Resources\Reviews\Pages\EditReview;
|
||||
use App\Filament\Resources\Reviews\Pages\ListReviews;
|
||||
@@ -18,6 +19,8 @@
|
||||
|
||||
class ReviewResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Review::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedStar;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\Sites\Concerns;
|
||||
|
||||
use App\Models\Site;
|
||||
|
||||
/**
|
||||
* Shows the hostnames of a website in the landlord's admin. Read only: addresses are given out by the
|
||||
* operator, because every address also has to be wired to this directory at the hoster, and because a
|
||||
* landlord must not be able to point somebody else's address at their own website.
|
||||
*/
|
||||
trait EditsSiteHosts
|
||||
{
|
||||
/**
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeFill(array $data): array
|
||||
{
|
||||
$site = $this->record;
|
||||
|
||||
if (! $site instanceof Site) {
|
||||
return $data;
|
||||
}
|
||||
|
||||
$data['extra_hosts'] = $site->domains()
|
||||
->where('host', '!=', (string) $site->domain)
|
||||
->pluck('host')
|
||||
->all();
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\Sites\Pages;
|
||||
|
||||
use App\Filament\Resources\Sites\Concerns\EditsSiteHosts;
|
||||
use App\Filament\Resources\Sites\SiteResource;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditSite extends EditRecord
|
||||
{
|
||||
use EditsSiteHosts;
|
||||
|
||||
protected static string $resource = SiteResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
|
||||
@@ -3,14 +3,19 @@
|
||||
namespace App\Filament\Resources\Sites\Schemas;
|
||||
|
||||
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
|
||||
use App\ImageWorlds\ImageWorldRegistry;
|
||||
use App\Models\Site;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\SpatieMediaLibraryFileUpload;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class SiteForm
|
||||
{
|
||||
@@ -24,19 +29,63 @@ public static function configure(Schema $schema): Schema
|
||||
->schema([
|
||||
TextInput::make('name')->label('Name')->required()->maxLength(120),
|
||||
TextInput::make('domain')
|
||||
->label('Domain')
|
||||
->placeholder('www.fewo-stommer.de')
|
||||
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(190),
|
||||
Select::make('theme')->label('Theme')->options(fn (): array => app(ThemeRegistry::class)->options())->default(config('themes.base'))->required()->live(),
|
||||
->label('Hauptadresse')
|
||||
->helperText('Steht in Links an Gäste. Adressen werden vom Betreiber vergeben, weil sie beim Hoster eingerichtet werden müssen.')
|
||||
->disabled()
|
||||
->dehydrated(false),
|
||||
TagsInput::make('extra_hosts')
|
||||
->label('Antwortet außerdem auf')
|
||||
->placeholder('keine weitere Adresse')
|
||||
->disabled()
|
||||
->dehydrated(false)
|
||||
->columnSpanFull(),
|
||||
Select::make('theme')
|
||||
->label('Theme')
|
||||
->options(fn (): array => app(ThemeRegistry::class)->options())
|
||||
->default(config('themes.base'))
|
||||
->required()
|
||||
->live()
|
||||
->helperText(fn (Get $get): ?string => filled($get('theme')) ? app(ThemeRegistry::class)->get($get('theme'))->description : null)
|
||||
->hintAction(
|
||||
Action::make('previewTheme')
|
||||
->label('Vorschau')
|
||||
->icon('heroicon-o-eye')
|
||||
->url(fn (Get $get): string => URL::temporarySignedRoute('home', now()->addDay(), ['theme' => $get('theme') ?: config('themes.base')]), shouldOpenInNewTab: true),
|
||||
),
|
||||
Select::make('image_world')
|
||||
->label('Bildwelt')
|
||||
->options(fn (): array => app(ImageWorldRegistry::class)->options())
|
||||
->placeholder('Vorgabe der Installation')
|
||||
->helperText(fn (Get $get): ?string => app(ImageWorldRegistry::class)->get($get('image_world'))?->description
|
||||
?: 'Bänder, Vignetten und Ornamente dieser Website. Eine Wohnung kann eine andere Bildwelt tragen.'),
|
||||
Toggle::make('is_default')->label('Standard-Website')->inline(false),
|
||||
]),
|
||||
Section::make('Marke')
|
||||
->description('Logo, Favicon und das Logo für E-Mails und den Mietvertrag. Gehört dem Vermieter, nicht dem Theme – jede Website hat ihre eigene.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->schema([
|
||||
SpatieMediaLibraryFileUpload::make('logo')
|
||||
->label('Logo')
|
||||
->collection(Site::BRAND_LOGO)
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/webp'])
|
||||
->helperText('SVG bevorzugt – bleibt in jeder Größe scharf.'),
|
||||
SpatieMediaLibraryFileUpload::make('favicon')
|
||||
->label('Favicon')
|
||||
->collection(Site::BRAND_FAVICON)
|
||||
->acceptedFileTypes(['image/svg+xml', 'image/png', 'image/x-icon'])
|
||||
->helperText('Das kleine Zeichen im Browser-Tab.'),
|
||||
SpatieMediaLibraryFileUpload::make('document_logo')
|
||||
->label('Logo für E-Mail und Vertrag')
|
||||
->collection(Site::BRAND_DOCUMENT_LOGO)
|
||||
->acceptedFileTypes(['image/png', 'image/jpeg'])
|
||||
->helperText('Als PNG oder JPG – E-Mail-Programme und der PDF-Druck zeichnen kein SVG.'),
|
||||
]),
|
||||
Section::make('Farben des Themes')
|
||||
->description('Grundfarben dieser Website; saisonale Erscheinungsbilder können einzelne Farben zusätzlich ändern.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens')),
|
||||
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens', $get('theme'))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Sites;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Sites\Pages\CreateSite;
|
||||
use App\Filament\Resources\Sites\Pages\EditSite;
|
||||
use App\Filament\Resources\Sites\Pages\ListSites;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class SiteResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Site::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedGlobeAlt;
|
||||
|
||||
@@ -15,7 +15,8 @@ public static function configure(Table $table): Table
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Website')->weight('medium'),
|
||||
TextColumn::make('domain')->label('Domain')->placeholder('alle übrigen Adressen'),
|
||||
TextColumn::make('domain')->label('Hauptadresse')->placeholder('alle übrigen Adressen'),
|
||||
TextColumn::make('domains.host')->label('Antwortet auf')->badge()->placeholder('jede Adresse'),
|
||||
TextColumn::make('theme')->label('Theme')->formatStateUsing(fn (string $state): string => app(ThemeRegistry::class)->get($state)->name),
|
||||
TextColumn::make('properties_count')->label('Wohnungen')->counts('properties'),
|
||||
IconColumn::make('is_default')->label('Standard')->boolean(),
|
||||
|
||||
@@ -3,9 +3,40 @@
|
||||
namespace App\Filament\Resources\Users\Pages;
|
||||
|
||||
use App\Filament\Resources\Users\UserResource;
|
||||
use App\Models\User;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class CreateUser extends CreateRecord
|
||||
{
|
||||
protected static string $resource = UserResource::class;
|
||||
|
||||
/**
|
||||
* An address that already belongs to another landlord is attached. The account, its password
|
||||
* and its two-factor setup stay as they are.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
protected function handleRecordCreation(array $data): Model
|
||||
{
|
||||
$email = is_string($data['email'] ?? null) ? $data['email'] : '';
|
||||
$existing = User::query()->where('email', $email)->first();
|
||||
|
||||
if ($existing === null) {
|
||||
return parent::handleRecordCreation($data);
|
||||
}
|
||||
|
||||
$attributes = [
|
||||
'name' => $data['name'] ?? $existing->name,
|
||||
'role' => $data['role'] ?? $existing->role,
|
||||
];
|
||||
|
||||
if (array_key_exists('admin_mode', $data)) {
|
||||
$attributes['admin_mode'] = $data['admin_mode'];
|
||||
}
|
||||
|
||||
$existing->forceFill($attributes)->save();
|
||||
|
||||
return $existing;
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Users\Pages;
|
||||
|
||||
use App\Filament\Resources\Users\UserResource;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
@@ -16,4 +17,22 @@ protected function getHeaderActions(): array
|
||||
DeleteAction::make(),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* A hidden password field must not be writable by a crafted request either.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
protected function mutateFormDataBeforeSave(array $data): array
|
||||
{
|
||||
$actor = auth()->user();
|
||||
$record = $this->getRecord();
|
||||
|
||||
if (! $actor instanceof User || ! $record instanceof User || ! $actor->mayResetCredentials($record)) {
|
||||
unset($data['password']);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,11 @@
|
||||
|
||||
namespace App\Filament\Resources\Users\Schemas;
|
||||
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Schemas\Schema;
|
||||
@@ -20,14 +24,59 @@ public static function configure(Schema $schema): Schema
|
||||
->maxLength(255),
|
||||
TextInput::make('email')
|
||||
->label('E-Mail (Anmeldename)')
|
||||
->helperText('Besteht die E-Mail schon, kommt das Konto zu diesem Mandanten dazu. Passwort und Zwei-Faktor-Anmeldung bleiben.')
|
||||
->email()
|
||||
->required()
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(255),
|
||||
->maxLength(255)
|
||||
->rules([
|
||||
fn (?User $record): Closure => function (string $attribute, mixed $value, Closure $fail) use ($record): void {
|
||||
if (! is_string($value)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$existing = User::query()->where('email', $value)->first();
|
||||
|
||||
if ($existing === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($record !== null) {
|
||||
if ($existing->isNot($record)) {
|
||||
$fail('Diese E-Mail wird schon verwendet.');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId !== null && $existing->tenants()->where('tenants.id', $tenantId)->exists()) {
|
||||
$fail('Diese Person gehört schon zu diesem Mandanten.');
|
||||
}
|
||||
},
|
||||
]),
|
||||
Radio::make('role')
|
||||
->label('Rolle')
|
||||
->helperText('Gilt für diesen Mandanten.')
|
||||
->options(UserRole::class)
|
||||
->required()
|
||||
->afterStateHydrated(function (Radio $component, ?User $record): void {
|
||||
if ($record === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
$role = $tenantId !== null ? ($record->roleOn($tenantId) ?? $record->role) : $record->role;
|
||||
|
||||
if ($role !== null) {
|
||||
$component->state($role->value);
|
||||
}
|
||||
})
|
||||
->columnSpanFull(),
|
||||
Radio::make('admin_mode')
|
||||
->label('Ansicht')
|
||||
->helperText('Bestimmt nur, was im Menü erscheint. Leer = Administratoren Expertenansicht, alle anderen einfache Ansicht. Jederzeit umschaltbar über das Benutzermenü oben rechts.')
|
||||
->options(AdminMode::class)
|
||||
->columnSpanFull(),
|
||||
TextInput::make('password')
|
||||
->label(fn (string $operation): string => $operation === 'create' ? 'Passwort' : 'Neues Passwort (leer lassen = unverändert)')
|
||||
@@ -35,6 +84,15 @@ public static function configure(Schema $schema): Schema
|
||||
->revealable()
|
||||
->minLength(10)
|
||||
->required(fn (string $operation): bool => $operation === 'create')
|
||||
->visible(function (string $operation, ?User $record): bool {
|
||||
if ($operation === 'create') {
|
||||
return true;
|
||||
}
|
||||
|
||||
$actor = auth()->user();
|
||||
|
||||
return $actor instanceof User && $actor->mayResetCredentials($record);
|
||||
})
|
||||
->dehydrated(fn (?string $state): bool => filled($state)),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,15 @@
|
||||
|
||||
namespace App\Filament\Resources\Users\Tables;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
@@ -15,10 +22,58 @@ public static function configure(Table $table): Table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('email')->label('E-Mail')->searchable(),
|
||||
TextColumn::make('role')->label('Rolle')->badge(),
|
||||
TextColumn::make('role')
|
||||
->label('Rolle')
|
||||
->badge()
|
||||
->state(function (User $record): ?UserRole {
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId === null) {
|
||||
return $record->role;
|
||||
}
|
||||
|
||||
return $record->roleOn($tenantId) ?? $record->role;
|
||||
}),
|
||||
TextColumn::make('mode')->label('Ansicht')->state(fn (User $record): string => $record->adminMode()->getLabel()),
|
||||
IconColumn::make('two_factor')->label('2FA')->state(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))->boolean(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('resetTwoFactor')
|
||||
->label('2FA zurücksetzen')
|
||||
->icon(Heroicon::OutlinedKey)
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Zum Beispiel bei verlorenem Handy: Die Person richtet die Zwei-Faktor-Anmeldung bei der nächsten Anmeldung neu ein.')
|
||||
->visible(function (User $record): bool {
|
||||
$actor = auth()->user();
|
||||
|
||||
return filled($record->getAppAuthenticationSecret())
|
||||
&& $actor instanceof User
|
||||
&& $actor->mayResetCredentials($record);
|
||||
})
|
||||
->action(function (User $record): void {
|
||||
$actor = auth()->user();
|
||||
|
||||
if (! $actor instanceof User || ! $actor->mayResetCredentials($record)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$record->saveAppAuthenticationSecret(null);
|
||||
$record->saveAppAuthenticationRecoveryCodes(null);
|
||||
Notification::make()->title('2FA zurückgesetzt')->success()->send();
|
||||
}),
|
||||
Action::make('revokeAccess')
|
||||
->label('Zugang entziehen')
|
||||
->icon(Heroicon::OutlinedNoSymbol)
|
||||
->color('danger')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Das Konto bleibt bestehen und verliert nur den Zugang zu diesem Mandanten. Passwort und Zwei-Faktor-Anmeldung bleiben.')
|
||||
->visible(fn (User $record): bool => $record->tenants()->count() >= 2)
|
||||
->action(function (User $record): void {
|
||||
$record->revokeCurrentTenant();
|
||||
Notification::make()->title('Zugang entzogen')->success()->send();
|
||||
}),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,21 +2,26 @@
|
||||
|
||||
namespace App\Filament\Resources\Users;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Users\Pages\CreateUser;
|
||||
use App\Filament\Resources\Users\Pages\EditUser;
|
||||
use App\Filament\Resources\Users\Pages\ListUsers;
|
||||
use App\Filament\Resources\Users\Schemas\UserForm;
|
||||
use App\Filament\Resources\Users\Tables\UsersTable;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use BackedEnum;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use UnitEnum;
|
||||
|
||||
class UserResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = User::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUserGroup;
|
||||
@@ -27,6 +32,23 @@ class UserResource extends Resource
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Benutzer';
|
||||
|
||||
/**
|
||||
* Accounts are global. This list shows only people who belong to the landlord that is open.
|
||||
*
|
||||
* @return Builder<User>
|
||||
*/
|
||||
public static function getEloquentQuery(): Builder
|
||||
{
|
||||
$query = parent::getEloquentQuery();
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId === null) {
|
||||
return $query;
|
||||
}
|
||||
|
||||
return $query->whereHas('tenants', fn (Builder $membership) => $membership->where('tenants.id', $tenantId));
|
||||
}
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return UserForm::configure($schema);
|
||||
|
||||
Loaded 100 of 444 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user