Compare commits
37
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -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=
|
||||
|
||||
@@ -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.
|
||||
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
|
||||
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`. 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`.
|
||||
- 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.
|
||||
- Booking path 1 (KONZEPT §6a): request (`Reserved`, hold) → `SendOffer` (`OfferSent`, versioned, contract draft, signed link `offers.show`) → guest `AcceptOffer` (acceptance record, then `ConfirmBooking`) or `RejectOffer`; `ExpireReservations` handles both holding statuses (`BookingStatus::holding()`). Manual price changes are `QuoteLineType::Adjustment` lines.
|
||||
- Minimum stay: season `min_nights`, relaxed in `PriceCalculator::minimumStayRelaxed` (offer `waives_min_stay`, gap filled completely, departure on the property's `changeover_weekday`, never below `min_stay_absolute`).
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`. 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`.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- Strato specifics: `public/index.php` strips the internal `/releases/<v>/public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Internal addresses are admin settings too: send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly); contact/reply-to (`fewo.owner.email`) and sender (`mail.from`) are overridden at boot by `Settings::applyAddressOverrides()`. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0.
|
||||
- Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR).
|
||||
- PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there).
|
||||
- Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`.
|
||||
|
||||
@@ -1,58 +1,37 @@
|
||||
<p align="center"><a href="https://laravel.com" target="_blank"><img src="https://raw.githubusercontent.com/laravel/art/master/logo-lockup/5%20SVG/2%20CMYK/1%20Full%20Color/laravel-logolockup-cmyk-red.svg" width="400" alt="Laravel Logo"></a></p>
|
||||
# Ferienwohnung Stommer – Webseite und Vermietungsverwaltung
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/laravel/framework/actions"><img src="https://github.com/laravel/framework/workflows/tests/badge.svg" alt="Build Status"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/dt/laravel/framework" alt="Total Downloads"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/v/laravel/framework" alt="Latest Stable Version"></a>
|
||||
<a href="https://packagist.org/packages/laravel/framework"><img src="https://img.shields.io/packagist/l/laravel/framework" alt="License"></a>
|
||||
</p>
|
||||
Webseite mit Buchungsanfrage und eine Verwaltung (Admin) für die Ferienwohnung Stommer, Strandstraße 15, 18225 Kühlungsborn. Ersetzt die bisherige WordPress-Seite www.fewo-stommer.de. Laravel 13, Filament 5, Livewire 4, Tailwind 4; Hosting bei Strato (Shared Webhosting, Hosting Pro).
|
||||
|
||||
## About Laravel
|
||||
**Testbetrieb:** https://stommer.info · Verwaltung: https://stommer.info/admin (Konto + Zwei-Faktor-Anmeldung, siehe docs/BETRIEB.md §7)
|
||||
|
||||
Laravel is a web application framework with expressive, elegant syntax. We believe development must be an enjoyable and creative experience to be truly fulfilling. Laravel takes the pain out of development by easing common tasks used in many web projects, such as:
|
||||
## Wo steht was?
|
||||
|
||||
- [Simple, fast routing engine](https://laravel.com/docs/routing).
|
||||
- [Powerful dependency injection container](https://laravel.com/docs/container).
|
||||
- Multiple back-ends for [session](https://laravel.com/docs/session) and [cache](https://laravel.com/docs/cache) storage.
|
||||
- Expressive, intuitive [database ORM](https://laravel.com/docs/eloquent).
|
||||
- Database agnostic [schema migrations](https://laravel.com/docs/migrations).
|
||||
- [Robust background job processing](https://laravel.com/docs/queues).
|
||||
- [Real-time event broadcasting](https://laravel.com/docs/broadcasting).
|
||||
| Dokument | Inhalt |
|
||||
|---|---|
|
||||
| [docs/STATUS.md](docs/STATUS.md) | **Aktueller Stand**: was fertig ist, was offen ist, nächste Schritte – hier anfangen |
|
||||
| [docs/ZUSAMMENARBEIT.md](docs/ZUSAMMENARBEIT.md) | Regeln für parallele Arbeit (z. B. Theme-Entwicklung auf einem anderen Rechner) – Branches, Dateibereiche, Ausliefern |
|
||||
| [docs/KONZEPT.md](docs/KONZEPT.md) | Fachliches Konzept und alle Entscheidungen (Buchungswege §6a, Festlegungen §6b) |
|
||||
| [docs/BETRIEB.md](docs/BETRIEB.md) | Server, Zugänge, Konfiguration, Konten/2FA, Backups, Löschfristen, bekannte Eigenheiten |
|
||||
| [docs/DEPLOYMENT.md](docs/DEPLOYMENT.md) | Auslieferung auf Strato (Skript, Versionen, Gitea Actions) |
|
||||
| [docs/THEMES.md](docs/THEMES.md) | Theme-System: Architektur, Bausteine und ihre Daten (Vorlagen-Vertrag) |
|
||||
| [docs/THEME-ERSTELLUNG.md](docs/THEME-ERSTELLUNG.md) | **Verbindliche Anleitung für ein neues Theme** (Design-Sitzung) |
|
||||
| [docs/PORTALE.md](docs/PORTALE.md) | Buchungsportale, Kalenderabgleich, Portal-E-Mails |
|
||||
| [styles/README.md](styles/README.md) | Markenelemente (Logo, Favicon, Symbole, Wellenband) |
|
||||
| docs/DATENSCHUTZ-*, GAP-DELTA, GO-LIVE-CHECKLISTE, LOESCHKONZEPT, BUCHUNGSPROZESS, DATENMODELL-KONZEPT | Analyse eines Datenschutz-Agenten (Annahmen markiert; maßgeblich ist KONZEPT.md) |
|
||||
| [CLAUDE.md](CLAUDE.md) / [AGENTS.md](AGENTS.md) | Technische Leitplanken für KI-Assistenten (identisch) |
|
||||
|
||||
Laravel is accessible, powerful, and provides tools required for large, robust applications.
|
||||
|
||||
## Learning Laravel
|
||||
|
||||
Laravel has the most extensive and thorough [documentation](https://laravel.com/docs) and video tutorial library of all modern web application frameworks, making it a breeze to get started with the framework.
|
||||
|
||||
In addition, [Laracasts](https://laracasts.com) contains thousands of video tutorials on a range of topics including Laravel, modern PHP, unit testing, and JavaScript. Boost your skills by digging into our comprehensive video library.
|
||||
|
||||
You can also watch bite-sized lessons with real-world projects on [Laravel Learn](https://laravel.com/learn), where you will be guided through building a Laravel application from scratch while learning PHP fundamentals.
|
||||
|
||||
## Agentic Development
|
||||
|
||||
Laravel's predictable structure and conventions make it ideal for AI coding agents like Claude Code, Cursor, and GitHub Copilot. Install [Laravel Boost](https://laravel.com/docs/ai) to supercharge your AI workflow:
|
||||
## Lokal starten
|
||||
|
||||
```bash
|
||||
composer require laravel/boost --dev
|
||||
|
||||
php artisan boost:install
|
||||
composer install && npm ci
|
||||
cp .env.example .env && php artisan key:generate
|
||||
touch database/database.sqlite # PowerShell: New-Item database/database.sqlite
|
||||
php artisan migrate:fresh --seed # Testdaten: Wohnung, Preise 2026, Seiten, Erscheinungsbilder
|
||||
npm run build # oder npm run dev
|
||||
php artisan serve # http://localhost:8000 · /admin: admin@example.com / password (2FA beim ersten Login)
|
||||
php artisan test --compact # alle Tests müssen grün sein
|
||||
```
|
||||
|
||||
Boost provides your agent 15+ tools and skills that help agents build Laravel applications while following best practices.
|
||||
## Ausliefern
|
||||
|
||||
## Contributing
|
||||
|
||||
Thank you for considering contributing to the Laravel framework! The contribution guide can be found in the [Laravel documentation](https://laravel.com/docs/contributions).
|
||||
|
||||
## Code of Conduct
|
||||
|
||||
In order to ensure that the Laravel community is welcoming to all, please review and abide by the [Code of Conduct](https://laravel.com/docs/contributions#code-of-conduct).
|
||||
|
||||
## Security Vulnerabilities
|
||||
|
||||
If you discover a security vulnerability within Laravel, please send an e-mail to Taylor Otwell via [taylor@laravel.com](mailto:taylor@laravel.com). All security vulnerabilities will be promptly addressed.
|
||||
|
||||
## License
|
||||
|
||||
The Laravel framework is open-sourced software licensed under the [MIT license](https://opensource.org/licenses/MIT).
|
||||
`bash scripts/deploy.sh staging deploy` – baut den **letzten Commit** und spielt ihn auf stommer.info (Details und Regeln: docs/DEPLOYMENT.md, docs/ZUSAMMENARBEIT.md).
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
use App\Support\Content;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* The guest accepts the offer on the signed offer page: the booking is concluded. A record of what was
|
||||
* accepted is kept (offer version, time, fingerprints of price and terms – no IP address), then the booking
|
||||
* is confirmed as usual (contract + confirmation mail as electronic acknowledgement).
|
||||
*/
|
||||
class AcceptOffer
|
||||
{
|
||||
public function __construct(private ConfirmBooking $confirm) {}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function handle(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
$this->ensureAcceptable($booking, $offerVersion);
|
||||
|
||||
$booking->update([
|
||||
'accepted_at' => now(),
|
||||
'acceptance' => [
|
||||
'offer_version' => $booking->offer_version,
|
||||
'accepted_at' => now()->toIso8601String(),
|
||||
'total' => $booking->total,
|
||||
'quote_sha256' => hash('sha256', json_encode($booking->quote)),
|
||||
'terms_sha256' => hash('sha256', (string) Content::get('contract.terms').'|'.Content::get('stay.cancellation')),
|
||||
'via' => 'offer_link',
|
||||
],
|
||||
]);
|
||||
|
||||
$this->confirm->handle($booking);
|
||||
|
||||
try {
|
||||
Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: true));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @throws ReservationException
|
||||
*/
|
||||
public function ensureAcceptable(Booking $booking, int $offerVersion): void
|
||||
{
|
||||
if ($offerVersion !== $booking->offer_version) {
|
||||
throw ReservationException::offerOutdated();
|
||||
}
|
||||
|
||||
if ($booking->status !== BookingStatus::OfferSent) {
|
||||
throw ReservationException::invalidTransition($booking->status->getLabel(), 'angenommen');
|
||||
}
|
||||
|
||||
if (! $booking->hold_expires_at?->isFuture()) {
|
||||
throw ReservationException::offerExpired();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,15 @@
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Guest;
|
||||
use App\Models\PortalEmail;
|
||||
|
||||
/**
|
||||
* Anonymises guests whose last stay ended longer ago than the retention period (GDPR storage limitation).
|
||||
* GDPR storage limitation: anonymises guests whose last stay ended longer ago than the retention period, and
|
||||
* guests who only ever sent requests/offers that never became binding (shorter period), and removes
|
||||
* operational extras that are no longer needed (portal e-mail excerpts, marketing attribution).
|
||||
* Booking records (dates, prices, payments) stay as accounting documents.
|
||||
*/
|
||||
class AnonymizeGuests
|
||||
{
|
||||
@@ -19,8 +24,32 @@ public function handle(): int
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereDate('departure', '>=', $cutoff))
|
||||
->get();
|
||||
|
||||
$guests->each->anonymize();
|
||||
$inquiryCutoff = now()->subMonths(config('fewo.retention.inquiry_months'));
|
||||
$inquiriesOnly = Guest::query()
|
||||
->whereNull('anonymized_at')
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->whereNotNull('confirmed_at'))
|
||||
->whereDoesntHave('bookings', fn ($query) => $query->where('updated_at', '>=', $inquiryCutoff))
|
||||
->where('updated_at', '<', $inquiryCutoff)
|
||||
->get();
|
||||
|
||||
return $guests->count();
|
||||
$all = $guests->merge($inquiriesOnly)->unique('id');
|
||||
$all->each->anonymize();
|
||||
|
||||
$this->purgeOperationalData();
|
||||
|
||||
return $all->count();
|
||||
}
|
||||
|
||||
private function purgeOperationalData(): void
|
||||
{
|
||||
PortalEmail::query()
|
||||
->whereNotNull('excerpt')
|
||||
->where('received_at', '<', now()->subDays(config('fewo.retention.portal_email_excerpt_days')))
|
||||
->update(['excerpt' => null]);
|
||||
|
||||
Booking::query()
|
||||
->where('created_at', '<', now()->subMonths(config('fewo.retention.attribution_months')))
|
||||
->where(fn ($query) => $query->whereNotNull('referral_source')->orWhereNotNull('utm_source')->orWhereNotNull('utm_medium')->orWhereNotNull('utm_campaign'))
|
||||
->update(['referral_source' => null, 'utm_source' => null, 'utm_medium' => null, 'utm_campaign' => null]);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
@@ -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::LAST_ERROR_KEY)));
|
||||
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
|
||||
|
||||
return 1;
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Channel;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
@@ -68,11 +69,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,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));
|
||||
}
|
||||
}
|
||||
@@ -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,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;
|
||||
}
|
||||
}
|
||||
@@ -7,28 +7,31 @@
|
||||
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]);
|
||||
Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', ['booking' => $booking, 'draft' => $draft])->setPaper('a4')->output());
|
||||
$booking->update([$draft ? 'offer_path' : 'contract_path' => $path]);
|
||||
|
||||
return $path;
|
||||
}
|
||||
|
||||
public function absolutePath(Booking $booking): ?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;
|
||||
}
|
||||
}
|
||||
@@ -2,10 +2,12 @@
|
||||
|
||||
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;
|
||||
@@ -26,9 +28,11 @@ enum AdminMode: string implements HasDescription, HasLabel
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
BookingResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
|
||||
public function getLabel(): string
|
||||
@@ -42,7 +46,7 @@ public function getLabel(): string
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Nur das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Gäste, Portal-Aufgaben, Bewertungen',
|
||||
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',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,8 +7,13 @@
|
||||
|
||||
enum BookingStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** Guest request; the dates are held until hold_expires_at. */
|
||||
/** Non-binding guest request; the dates are held until hold_expires_at. */
|
||||
case Reserved = 'reserved';
|
||||
|
||||
/** The landlord sent an offer; the dates are held until hold_expires_at (= end of the offer's validity). */
|
||||
case OfferSent = 'offer_sent';
|
||||
|
||||
/** Binding booking: the guest accepted the offer (or the landlord confirmed directly). */
|
||||
case Confirmed = 'confirmed';
|
||||
case DepositPaid = 'deposit_paid';
|
||||
case Paid = 'paid';
|
||||
@@ -20,7 +25,8 @@ enum BookingStatus: string implements HasColor, HasLabel
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'Vorreserviert',
|
||||
self::Reserved => 'Anfrage (vorgemerkt)',
|
||||
self::OfferSent => 'Angebot gesendet',
|
||||
self::Confirmed => 'Bestätigt',
|
||||
self::DepositPaid => 'Anzahlung erhalten',
|
||||
self::Paid => 'Bezahlt',
|
||||
@@ -35,12 +41,23 @@ public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'warning',
|
||||
self::OfferSent => 'primary',
|
||||
self::Confirmed, self::DepositPaid => 'info',
|
||||
self::Paid, self::Completed => 'success',
|
||||
self::Declined, self::Expired, self::Cancelled => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar while their hold time (hold_expires_at) runs.
|
||||
*
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function holding(): array
|
||||
{
|
||||
return [self::Reserved, self::OfferSent];
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar regardless of any hold time.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
+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,91 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator;
|
||||
|
||||
use App\Filament\Operator\Tenants\Pages\CreateTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\EditTenant;
|
||||
use App\Filament\Operator\Tenants\Pages\ListTenants;
|
||||
use App\Models\Tenant;
|
||||
use App\Models\TenantAccessLog;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Columns\ToggleColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
class TenantResource extends Resource
|
||||
{
|
||||
protected static ?string $model = Tenant::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedBuildingOffice;
|
||||
|
||||
protected static ?string $modelLabel = 'Mandant';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Mandanten';
|
||||
|
||||
protected static ?string $navigationLabel = 'Mandanten';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
TextInput::make('name')
|
||||
->label('Name')
|
||||
->required()
|
||||
->maxLength(255),
|
||||
TextInput::make('slug')
|
||||
->label('Kurzname')
|
||||
->required()
|
||||
->alphaDash()
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(255),
|
||||
Toggle::make('is_active')
|
||||
->label('Aktiv')
|
||||
->helperText('Ein gesperrter Mandant ist von außen nicht mehr erreichbar. Der Betreiber kommt weiter hinein.')
|
||||
->default(true),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->columns([
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('slug')->label('Kurzname'),
|
||||
ToggleColumn::make('is_active')->label('Aktiv'),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('openAdmin')
|
||||
->label('Im Admin öffnen')
|
||||
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
|
||||
->action(function (Tenant $record) {
|
||||
TenantAccessLog::query()->create([
|
||||
'tenant_id' => $record->id,
|
||||
'user_id' => auth()->id(),
|
||||
]);
|
||||
|
||||
$domain = $record->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
|
||||
|
||||
return redirect(is_string($domain) && $domain !== '' ? 'https://'.$domain.'/admin' : url('/admin'));
|
||||
}),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ListTenants::route('/'),
|
||||
'create' => CreateTenant::route('/create'),
|
||||
'edit' => EditTenant::route('/{record}/edit'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\CreateRecord;
|
||||
|
||||
class CreateTenant extends CreateRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Resources\Pages\EditRecord;
|
||||
|
||||
class EditTenant extends EditRecord
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Operator\Tenants\Pages;
|
||||
|
||||
use App\Filament\Operator\TenantResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ListRecords;
|
||||
|
||||
class ListTenants extends ListRecords
|
||||
{
|
||||
protected static string $resource = TenantResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Support\Settings;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\TagsInput;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Actions;
|
||||
use Filament\Schemas\Components\EmbeddedSchema;
|
||||
use Filament\Schemas\Components\Form;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* Operating mode (test mode sends every e-mail to one test recipient only; live delivers to the real recipients)
|
||||
* and the addresses of the internal communication (notifications, contact/reply-to, sender). Administrators only.
|
||||
*/
|
||||
class Operations extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'System';
|
||||
|
||||
protected static ?string $navigationLabel = 'Betrieb';
|
||||
|
||||
protected static ?string $title = 'Betrieb';
|
||||
|
||||
protected static ?string $slug = 'betrieb';
|
||||
|
||||
protected static ?int $navigationSort = 1;
|
||||
|
||||
/** @var array<string, ?string> */
|
||||
public array $data = [];
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->form->fill([
|
||||
'mode' => Settings::get(Settings::MODE, Settings::MODE_TEST),
|
||||
'test_recipient' => Settings::get(Settings::TEST_RECIPIENT) ?? auth()->user()?->email,
|
||||
'notification_recipients' => Settings::notificationRecipients(),
|
||||
'contact_email' => config('fewo.owner.email'),
|
||||
'sender_name' => config('mail.from.name'),
|
||||
'sender_email' => config('mail.from.address'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->statePath('data')
|
||||
->components([
|
||||
Section::make('E-Mail-Versand')
|
||||
->description('Im Testbetrieb gehen alle E-Mails – Eingangsbestätigungen, Angebote, Bestätigungen, Erinnerungen, Benachrichtigungen – ausschließlich an die Testadresse, egal welche Adresse auf der Webseite eingetragen wurde.')
|
||||
->schema([
|
||||
Radio::make('mode')
|
||||
->label('Betriebsart')
|
||||
->options([
|
||||
Settings::MODE_TEST => 'Testbetrieb – alle E-Mails an die Testadresse',
|
||||
Settings::MODE_LIVE => 'Scharf geschaltet – E-Mails an Gäste und Vermieterin',
|
||||
])
|
||||
->required()
|
||||
->live(),
|
||||
TextInput::make('test_recipient')
|
||||
->label('Testadresse')
|
||||
->email()
|
||||
->required(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST)
|
||||
->visible(fn (Get $get): bool => $get('mode') === Settings::MODE_TEST),
|
||||
Text::make(fn (): string => filled(config('fewo.mail_redirect_to'))
|
||||
? 'Hinweis: Auf diesem Server ist zusätzlich FEWO_MAIL_REDIRECT_TO='.config('fewo.mail_redirect_to').' gesetzt – diese Umleitung gilt immer, auch wenn hier scharf geschaltet ist.'
|
||||
: ''),
|
||||
]),
|
||||
Section::make('Adressen der internen Kommunikation')
|
||||
->description('Gelten sofort für alle E-Mails, die Webseite und den Mietvertrag. Im Testbetrieb gehen trotzdem alle E-Mails nur an die Testadresse.')
|
||||
->columns(2)
|
||||
->schema([
|
||||
TagsInput::make('notification_recipients')
|
||||
->label('Benachrichtigungen an')
|
||||
->helperText('Neue Anfragen, angenommene/abgelehnte Angebote, abgelaufene Fristen, Bewertungen, Portal-Mails und -Aufgaben, Kopie der Zahlungserinnerungen. Mehrere Adressen möglich (Enter nach jeder Adresse).')
|
||||
->placeholder('adresse@beispiel.de')
|
||||
->nestedRecursiveRules(['email'])
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
TextInput::make('contact_email')
|
||||
->label('Kontakt- und Antwortadresse')
|
||||
->helperText('Steht auf der Webseite und im Mietvertrag; Antworten der Gäste auf unsere E-Mails gehen hierhin.')
|
||||
->email()
|
||||
->required(),
|
||||
TextInput::make('sender_name')
|
||||
->label('Absendername')
|
||||
->required()
|
||||
->maxLength(100),
|
||||
TextInput::make('sender_email')
|
||||
->label('Absenderadresse')
|
||||
->helperText(fn (): string => 'Muss das Postfach sein, mit dem der Server versendet (SMTP-Anmeldung: '.(config('mail.mailers.smtp.username') ?: 'nicht gesetzt').') – sonst lehnt Strato den Versand ab.')
|
||||
->email()
|
||||
->required(),
|
||||
Text::make(fn (Get $get): string => filled(config('mail.mailers.smtp.username')) && filled($get('sender_email')) && strcasecmp((string) $get('sender_email'), (string) config('mail.mailers.smtp.username')) !== 0
|
||||
? '⚠ Die Absenderadresse weicht vom SMTP-Postfach ('.config('mail.mailers.smtp.username').') ab. Strato stellt solche E-Mails in der Regel nicht zu.'
|
||||
: '')
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
return $schema->components([
|
||||
Form::make([EmbeddedSchema::make('form')])
|
||||
->id('form')
|
||||
->livewireSubmitHandler('save')
|
||||
->footer([Actions::make([Action::make('save')->label('Speichern')->submit('save')])]),
|
||||
]);
|
||||
}
|
||||
|
||||
public function save(): void
|
||||
{
|
||||
$data = $this->form->getState();
|
||||
|
||||
if ($data['mode'] === Settings::MODE_LIVE && Settings::get(Settings::MODE) !== Settings::MODE_LIVE) {
|
||||
Notification::make()->title('Scharf geschaltet')->body('Ab jetzt erhalten Gäste und Vermieterin die E-Mails direkt.')->warning()->send();
|
||||
} else {
|
||||
Notification::make()->title('Gespeichert')->success()->send();
|
||||
}
|
||||
|
||||
Settings::save([
|
||||
Settings::MODE => $data['mode'],
|
||||
Settings::TEST_RECIPIENT => $data['test_recipient'] ?? Settings::get(Settings::TEST_RECIPIENT),
|
||||
Settings::NOTIFICATION_RECIPIENTS => implode(', ', Settings::addressList(implode(',', $data['notification_recipients'] ?? []))),
|
||||
Settings::CONTACT_EMAIL => $data['contact_email'],
|
||||
Settings::SENDER_NAME => $data['sender_name'],
|
||||
Settings::SENDER_EMAIL => $data['sender_email'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
|
||||
use App\Models\Property;
|
||||
use BackedEnum;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Livewire;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Livewire\Attributes\Url;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* The yearly price work in one place, without the other apartment settings: seasons & prices,
|
||||
* special offers & promo codes, extras. Reuses the relation managers of the apartment.
|
||||
*/
|
||||
class PricesAndOffers extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCurrencyEuro;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $title = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $slug = 'preise-und-angebote';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
#[Url(as: 'wohnung')]
|
||||
public ?int $propertyId = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id');
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
$property = Property::find($this->propertyId);
|
||||
if ($property === null) {
|
||||
return $schema->components([Text::make('Es ist noch keine Wohnung angelegt (Expertenansicht › Wohnungen).')]);
|
||||
}
|
||||
|
||||
$context = ['ownerRecord' => $property, 'pageClass' => EditProperty::class];
|
||||
|
||||
return $schema->components([
|
||||
Select::make('propertyId')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->live()
|
||||
->afterStateUpdated(fn () => $this->redirect(static::getUrl(['wohnung' => $this->propertyId])))
|
||||
->visible(fn (): bool => Property::query()->count() > 1),
|
||||
Tabs::make('prices')
|
||||
->persistTabInQueryString()
|
||||
->tabs([
|
||||
Tab::make('Saisons & Preise')->icon(Heroicon::OutlinedCalendar)->schema([
|
||||
Livewire::make(SeasonsRelationManager::class, $context)->key("seasons-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Sonderangebote & Rabattcodes')->icon(Heroicon::OutlinedSparkles)->schema([
|
||||
Livewire::make(SpecialOffersRelationManager::class, $context)->key("offers-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Extras')->icon(Heroicon::OutlinedGift)->schema([
|
||||
Livewire::make(ExtrasRelationManager::class, $context)->key("extras-{$property->id}"),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -121,6 +121,9 @@ public function form(Schema $schema): Schema
|
||||
Toggle::make('is_combinable')
|
||||
->label('Mit anderen kombinierbaren Angeboten kombinierbar')
|
||||
->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.')
|
||||
@@ -144,10 +147,7 @@ public function form(Schema $schema): Schema
|
||||
->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(),
|
||||
Toggle::make('waives_min_stay')
|
||||
->label('Mindestaufenthalt der Saison aufheben')
|
||||
->helperText('Damit auch kurze Lücken (z. B. 2 Nächte bei 5 Nächten Mindestaufenthalt) buchbar werden.')
|
||||
->default(true),
|
||||
|
||||
]),
|
||||
Section::make('Bedingungen')
|
||||
->description('Leere Felder bedeuten: keine Einschränkung.')
|
||||
|
||||
@@ -28,7 +28,7 @@ public static function configure(Schema $schema): Schema
|
||||
TextInput::make('domain')
|
||||
->label('Domain')
|
||||
->placeholder('www.fewo-stommer.de')
|
||||
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
|
||||
->helperText('Leer = Standard-Website, solange es nur diesen Mandanten gibt. Ab dem zweiten Mandanten antwortet nur eine eingetragene Domain.')
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(190),
|
||||
Select::make('theme')
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
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;
|
||||
@@ -21,15 +24,54 @@ 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('Bestimmt, was die Person darf.')
|
||||
->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')
|
||||
@@ -42,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,7 +2,9 @@
|
||||
|
||||
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;
|
||||
@@ -20,7 +22,18 @@ 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(),
|
||||
])
|
||||
@@ -32,12 +45,35 @@ public static function configure(Table $table): Table
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Zum Beispiel bei verlorenem Handy: Die Person richtet die Zwei-Faktor-Anmeldung bei der nächsten Anmeldung neu ein.')
|
||||
->visible(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))
|
||||
->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(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -9,11 +9,13 @@
|
||||
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
|
||||
@@ -30,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);
|
||||
|
||||
@@ -36,8 +36,7 @@ public function feed(string $token, ICalFeed $feed): Response
|
||||
|
||||
public function health(Request $request): JsonResponse
|
||||
{
|
||||
$token = config('fewo.channels.health_token');
|
||||
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404);
|
||||
abort_unless($this->hasValidToken($request, config('fewo.channels.health_token')), 404);
|
||||
|
||||
$channels = Channel::query()->active()->get()->map(fn (Channel $channel): array => [
|
||||
'name' => $channel->name,
|
||||
@@ -69,8 +68,7 @@ public function health(Request $request): JsonResponse
|
||||
*/
|
||||
public function scheduler(Request $request): JsonResponse
|
||||
{
|
||||
$token = config('fewo.scheduler_token');
|
||||
abort_if(blank($token) || ! hash_equals($token, (string) $request->query('token')), 404);
|
||||
abort_unless($this->hasValidToken($request, config('fewo.scheduler_token')), 404);
|
||||
|
||||
Artisan::call('schedule:run');
|
||||
|
||||
@@ -129,4 +127,15 @@ private function verifySignature(Request $request): void
|
||||
|
||||
abort_if(blank($secret) || ! hash_equals(hash_hmac('sha256', $request->getContent(), $secret), $signature), 403);
|
||||
}
|
||||
|
||||
/**
|
||||
* The token is sent as header "Authorization: Bearer <token>" (preferred – does not end up in web server logs)
|
||||
* or, for older automations, as ?token=<token>.
|
||||
*/
|
||||
private function hasValidToken(Request $request, ?string $expected): bool
|
||||
{
|
||||
$given = (string) ($request->bearerToken() ?? $request->header('X-Fewo-Token') ?? $request->query('token', ''));
|
||||
|
||||
return filled($expected) && hash_equals((string) $expected, $given);
|
||||
}
|
||||
}
|
||||
@@ -20,7 +20,8 @@ public function confirm(Guest $guest): View
|
||||
return view('marketing-consent', [
|
||||
'title' => 'Anmeldung bestätigt',
|
||||
'message' => 'Vielen Dank! Wir informieren Sie künftig über freie Termine und Angebote. Sie können sich jederzeit wieder abmelden.',
|
||||
'unsubscribeUrl' => URL::signedRoute('marketing.unsubscribe', $guest),
|
||||
'unsubscribeUrl' => $guest->website()?->signedRoute('marketing.unsubscribe', $guest)
|
||||
?? URL::signedRoute('marketing.unsubscribe', $guest),
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Controllers;
|
||||
|
||||
use App\Actions\AcceptOffer;
|
||||
use App\Actions\RejectOffer;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
/**
|
||||
* The guest's offer page (no account): reached by the signed link in the offer e-mail. Shows the complete
|
||||
* offer and lets the guest accept or decline it; the form actions are signed the same way.
|
||||
*/
|
||||
class OfferController extends Controller
|
||||
{
|
||||
public function show(Request $request, Booking $booking, AcceptOffer $accept): View
|
||||
{
|
||||
$booking->loadMissing(['guest', 'property']);
|
||||
$version = (int) $request->query('v');
|
||||
|
||||
$problem = null;
|
||||
if ($booking->status === BookingStatus::OfferSent) {
|
||||
try {
|
||||
$accept->ensureAcceptable($booking, $version);
|
||||
} catch (ReservationException $exception) {
|
||||
$problem = $exception->getMessage();
|
||||
}
|
||||
}
|
||||
|
||||
$expires = $booking->hold_expires_at?->isFuture() ? $booking->hold_expires_at : now()->addHour();
|
||||
|
||||
return view('offer', [
|
||||
'booking' => $booking,
|
||||
'problem' => $problem,
|
||||
'canAnswer' => $booking->status === BookingStatus::OfferSent && $problem === null,
|
||||
'acceptUrl' => $this->signed($booking, 'offers.accept', $expires, $version),
|
||||
'rejectUrl' => $this->signed($booking, 'offers.reject', $expires, $version),
|
||||
'title' => 'Ihr Angebot',
|
||||
]);
|
||||
}
|
||||
|
||||
public function accept(Request $request, Booking $booking, AcceptOffer $accept): RedirectResponse
|
||||
{
|
||||
$request->validate(['terms' => ['accepted']], ['terms.accepted' => 'Bitte bestätigen Sie, dass Sie die Bedingungen gelesen haben.']);
|
||||
|
||||
return $this->answer($request, $booking, fn (int $version) => $accept->handle($booking, $version), 'Vielen Dank! Ihre Buchung ist verbindlich. Die Bestätigung mit dem Mietvertrag haben wir Ihnen per E-Mail gesendet.');
|
||||
}
|
||||
|
||||
public function reject(Request $request, Booking $booking, RejectOffer $reject): RedirectResponse
|
||||
{
|
||||
return $this->answer($request, $booking, fn (int $version) => $reject->handle($booking, $version), 'Schade – wir haben Ihre Absage erhalten und den Zeitraum wieder freigegeben. Vielleicht ein anderes Mal!');
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs the answer and returns to a freshly signed offer page with the result.
|
||||
*/
|
||||
private function answer(Request $request, Booking $booking, callable $action, string $success): RedirectResponse
|
||||
{
|
||||
$version = (int) $request->query('v');
|
||||
$back = $this->signed($booking, 'offers.show', now()->addDays(30), $version);
|
||||
|
||||
try {
|
||||
$action($version);
|
||||
} catch (ReservationException $exception) {
|
||||
return redirect()->to($back)->with('offer.error', $exception->getMessage());
|
||||
}
|
||||
|
||||
return redirect()->to($back)->with('offer.success', $success);
|
||||
}
|
||||
|
||||
private function signed(Booking $booking, string $name, DateTimeInterface $expiration, int $version): string
|
||||
{
|
||||
$parameters = ['booking' => $booking, 'v' => $version];
|
||||
|
||||
return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters)
|
||||
?? URL::temporarySignedRoute($name, $expiration, $parameters);
|
||||
}
|
||||
}
|
||||
@@ -66,6 +66,7 @@ public function robots(): Response
|
||||
'Disallow: /automation',
|
||||
'Disallow: /bewertung',
|
||||
'Disallow: /angebote',
|
||||
'Disallow: /angebot/',
|
||||
'Sitemap: '.route('sitemap'),
|
||||
'',
|
||||
]), 200, ['Content-Type' => 'text/plain; charset=UTF-8']);
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\User;
|
||||
use Closure;
|
||||
use Filament\Auth\MultiFactor\Http\Middleware\EnsureMultiFactorAuthenticationIsEnabled;
|
||||
use Filament\Facades\Filament;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
/**
|
||||
* Filament evaluates "two-factor required" once per panel; this narrows it to administrators.
|
||||
* Other roles may set it up voluntarily in their profile.
|
||||
*/
|
||||
class RequireTwoFactorForAdmins extends EnsureMultiFactorAuthenticationIsEnabled
|
||||
{
|
||||
public function handle(Request $request, Closure $next): mixed
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
if (! $user instanceof User || ! $user->hasRole(UserRole::Admin)) {
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
return parent::handle($request, $next);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use App\Models\Tenant;
|
||||
use App\Models\User;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Themes\Theme;
|
||||
use App\Themes\ThemeFactory;
|
||||
use Closure;
|
||||
@@ -17,8 +20,42 @@ public function __construct(private ThemeFactory $factory) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
app()->instance(Theme::class, $this->factory->forRequest($request)->activate());
|
||||
$context = app(TenantContext::class);
|
||||
$context->forget();
|
||||
|
||||
$theme = $this->factory->forRequest($request)->activate();
|
||||
app()->instance(Theme::class, $theme);
|
||||
|
||||
$tenant = null;
|
||||
|
||||
if ($theme->site->exists && $theme->site->tenant_id !== null) {
|
||||
$tenant = $theme->site->tenant;
|
||||
} elseif (Tenant::query()->count() === 1) {
|
||||
$tenant = Tenant::query()->first();
|
||||
}
|
||||
|
||||
if ($tenant !== null) {
|
||||
if (! $tenant->is_active && ! $this->operatorMayPass($request)) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$context->set($tenant);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* A suspended landlord stays reachable for the operator, and the operator panel itself stays open.
|
||||
*/
|
||||
private function operatorMayPass(Request $request): bool
|
||||
{
|
||||
if ($request->is('betreiber', 'betreiber/*')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$user = $request->user();
|
||||
|
||||
return $user instanceof User && $user->is_operator;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Middleware;
|
||||
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Security headers for every response. A Content-Security-Policy is not set yet: Livewire/Filament rely on
|
||||
* inline scripts and styles, a policy needs nonces and a careful test first.
|
||||
*/
|
||||
class SecurityHeaders
|
||||
{
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$response = $next($request);
|
||||
|
||||
$response->headers->set('X-Content-Type-Options', 'nosniff');
|
||||
$response->headers->set('X-Frame-Options', 'SAMEORIGIN');
|
||||
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
|
||||
$response->headers->set('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), payment=(), usb=()');
|
||||
|
||||
if ($request->isSecure() && ! app()->environment('local', 'testing')) {
|
||||
$response->headers->set('Strict-Transport-Security', 'max-age=31536000');
|
||||
}
|
||||
|
||||
return $response;
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
use App\Actions\CreateReservation;
|
||||
use App\Actions\RequestMarketingConsent;
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ReferralSource;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Models\Booking;
|
||||
@@ -14,6 +15,7 @@
|
||||
use App\Pricing\PriceQuote;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Database\Eloquent\Collection;
|
||||
@@ -77,12 +79,17 @@ class BookingRequest extends Component
|
||||
/** Honeypot, must stay empty. */
|
||||
public string $website = '';
|
||||
|
||||
/** When the form was opened (time trap against bots); cannot be changed by the browser. */
|
||||
#[Locked]
|
||||
public int $openedAt = 0;
|
||||
|
||||
#[Locked]
|
||||
public ?int $bookingId = null;
|
||||
|
||||
public function mount(?Property $property = null): void
|
||||
{
|
||||
$this->propertyId = ($property ?? Property::query()->where('is_active', true)->firstOrFail())->id;
|
||||
$this->openedAt = now()->getTimestamp();
|
||||
$this->month = CarbonImmutable::today()->format('Y-m');
|
||||
$this->prefillFromSearch();
|
||||
$this->utm = collect(request()->only(['utm_source', 'utm_medium', 'utm_campaign']))
|
||||
@@ -215,17 +222,22 @@ public function submit(CreateReservation $createReservation): void
|
||||
{
|
||||
$this->validate();
|
||||
|
||||
if ($this->website !== '') {
|
||||
// Bots: honeypot filled or submitted faster than a human can fill the form – silently ignored.
|
||||
if ($this->website !== '' || now()->getTimestamp() - $this->openedAt < config('fewo.spam.min_seconds')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$rateLimitKey = 'booking-request:'.request()->ip();
|
||||
if (RateLimiter::tooManyAttempts($rateLimitKey, 5)) {
|
||||
if ($this->tooManyRequests()) {
|
||||
$this->addError('email', 'Zu viele Anfragen. Bitte versuchen Sie es später erneut oder rufen Sie uns an.');
|
||||
|
||||
return;
|
||||
}
|
||||
RateLimiter::hit($rateLimitKey, 3600);
|
||||
|
||||
if ($this->openRequestsOfEmail() >= config('fewo.spam.open_requests_per_email')) {
|
||||
$this->addError('email', 'Zu dieser E-Mail-Adresse liegen bereits offene Anfragen vor. Wir melden uns in Kürze – bei Fragen rufen Sie uns gern an.');
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$booking = $createReservation->handle(
|
||||
@@ -260,6 +272,40 @@ public function submit(CreateReservation $createReservation): void
|
||||
/**
|
||||
* @return array<string, list<string>>
|
||||
*/
|
||||
/**
|
||||
* Rate limits per IP address, per e-mail address and for all requests together (counted when they pass).
|
||||
*/
|
||||
private function tooManyRequests(): bool
|
||||
{
|
||||
$tenantKey = (string) (app(TenantContext::class)->id() ?? 'global');
|
||||
$limits = [
|
||||
'booking-request:'.$tenantKey.':'.request()->ip() => [config('fewo.spam.per_ip_per_hour'), 3600],
|
||||
'booking-request-email:'.$tenantKey.':'.sha1(mb_strtolower($this->email)) => [config('fewo.spam.per_email_per_day'), 86400],
|
||||
'booking-request-all' => [config('fewo.spam.total_per_hour'), 3600],
|
||||
];
|
||||
|
||||
foreach ($limits as $key => [$max]) {
|
||||
if (RateLimiter::tooManyAttempts($key, $max)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($limits as $key => [, $decay]) {
|
||||
RateLimiter::hit($key, $decay);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function openRequestsOfEmail(): int
|
||||
{
|
||||
return Booking::query()
|
||||
->whereIn('status', BookingStatus::holding())
|
||||
->where('hold_expires_at', '>', now())
|
||||
->whereHas('guest', fn ($query) => $query->where('email', mb_strtolower($this->email)))
|
||||
->count();
|
||||
}
|
||||
|
||||
protected function rules(): array
|
||||
{
|
||||
return [
|
||||
@@ -268,14 +314,18 @@ protected function rules(): array
|
||||
'guests' => ['required', 'integer', 'min:1', 'max:'.$this->property->max_guests],
|
||||
'extras.*' => ['nullable', 'integer', 'min:0', 'max:10'],
|
||||
'promoCode' => ['nullable', 'string', 'max:50'],
|
||||
'firstName' => ['required', 'string', 'max:255'],
|
||||
'lastName' => ['required', 'string', 'max:255'],
|
||||
'firstName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'],
|
||||
'lastName' => ['required', 'string', 'max:255', 'not_regex:/https?:|www\.|<|>/i'],
|
||||
'email' => ['required', 'email', 'max:255'],
|
||||
'phone' => ['nullable', 'string', 'max:50'],
|
||||
'street' => ['nullable', 'string', 'max:255'],
|
||||
'postalCode' => ['nullable', 'string', 'max:20'],
|
||||
'city' => ['nullable', 'string', 'max:255'],
|
||||
'message' => ['nullable', 'string', 'max:5000'],
|
||||
'message' => ['nullable', 'string', 'max:5000', function (string $attribute, mixed $value, \Closure $fail): void {
|
||||
if (preg_match_all('~https?://|www\.~i', (string) $value) > config('fewo.spam.max_links')) {
|
||||
$fail('Bitte schreiben Sie Ihre Nachricht ohne Links.');
|
||||
}
|
||||
}],
|
||||
'referralSource' => ['nullable', Rule::enum(ReferralSource::class)],
|
||||
'privacyAccepted' => ['accepted'],
|
||||
];
|
||||
|
||||
@@ -31,7 +31,8 @@ public function envelope(): Envelope
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
with: ['url' => URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
|
||||
with: ['url' => $this->guest->website()?->temporarySignedRoute('marketing.confirm', now()->addDays(14), ['guest' => $this->guest])
|
||||
?? URL::temporarySignedRoute('marketing.confirm', now()->addDays(14), $this->guest)],
|
||||
markdown: 'mail.marketing-consent-request',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* Tells the landlord that the guest accepted or declined an offer.
|
||||
*/
|
||||
class OfferAnswered extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Booking $booking, public bool $accepted) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: ($this->accepted ? 'Angebot angenommen: ' : 'Angebot abgelehnt: ').$this->booking->reference,
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(markdown: 'mail.offer-answered');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Documents\RentalContract;
|
||||
use App\Models\Booking;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
use Illuminate\Mail\Mailables\Attachment;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* The offer to the guest: price, validity, contract draft as PDF and the link to accept or decline.
|
||||
*/
|
||||
class OfferMade extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
public function __construct(public Booking $booking, public string $offerUrl) {}
|
||||
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Ihr Angebot '.$this->booking->reference.' – Ferienwohnung Stommer',
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
);
|
||||
}
|
||||
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(markdown: 'mail.offer-made');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<Attachment>
|
||||
*/
|
||||
public function attachments(): array
|
||||
{
|
||||
$path = app(RentalContract::class)->absolutePath($this->booking, draft: true);
|
||||
|
||||
return $path ? [Attachment::fromPath($path)->as("Angebot-{$this->booking->reference}.pdf")->withMime('application/pdf')] : [];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Support\Settings;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Address;
|
||||
@@ -33,7 +34,7 @@ public function envelope(): Envelope
|
||||
default => "Zahlungserinnerung zu Ihrer Buchung {$this->booking->reference}",
|
||||
},
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
bcc: $this->kind === self::BALANCE_REQUEST ? [] : [new Address(config('fewo.notification_email'))],
|
||||
bcc: $this->kind === self::BALANCE_REQUEST ? [] : array_map(fn (string $address): Address => new Address($address), Settings::notificationRecipients()),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,7 +22,7 @@ public function __construct(public Booking $booking) {}
|
||||
public function envelope(): Envelope
|
||||
{
|
||||
return new Envelope(
|
||||
subject: 'Ihre Anfrage '.$this->booking->reference.' – Termin vorgemerkt',
|
||||
subject: 'Ihre Anfrage '.$this->booking->reference.' – Termin vorgemerkt, Angebot folgt',
|
||||
replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -31,7 +31,8 @@ public function envelope(): Envelope
|
||||
public function content(): Content
|
||||
{
|
||||
return new Content(
|
||||
with: ['url' => URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
|
||||
with: ['url' => $this->booking->website()?->temporarySignedRoute('reviews.create', now()->addDays(90), ['booking' => $this->booking])
|
||||
?? URL::temporarySignedRoute('reviews.create', now()->addDays(90), $this->booking)],
|
||||
markdown: 'mail.review-request',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\AmenityArea;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\AmenityFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -16,7 +17,7 @@
|
||||
class Amenity extends Model
|
||||
{
|
||||
/** @use HasFactory<AmenityFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\AppearanceFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -19,7 +20,7 @@
|
||||
class Appearance extends Model
|
||||
{
|
||||
/** @use HasFactory<AppearanceFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Texts an appearance can replace, with their admin labels. Sections read them through Theme::text().
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Observers\BlockedPeriodObserver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BlockedPeriodFactory;
|
||||
@@ -22,7 +23,7 @@
|
||||
class BlockedPeriod extends Model
|
||||
{
|
||||
/** @use HasFactory<BlockedPeriodFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
+53
-5
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\ReferralSource;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Observers\BookingObserver;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\BookingFactory;
|
||||
@@ -36,6 +37,8 @@
|
||||
'guests',
|
||||
'extras',
|
||||
'promo_code',
|
||||
'price_adjustment',
|
||||
'price_adjustment_label',
|
||||
'quote',
|
||||
'total',
|
||||
'deposit',
|
||||
@@ -43,9 +46,16 @@
|
||||
'balance_due_on',
|
||||
'contract_path',
|
||||
'hold_expires_at',
|
||||
'offer_version',
|
||||
'offer_sent_at',
|
||||
'offer_message',
|
||||
'offer_path',
|
||||
'message',
|
||||
'internal_notes',
|
||||
'confirmed_at',
|
||||
'accepted_at',
|
||||
'acceptance',
|
||||
'declined_by',
|
||||
'cancelled_at',
|
||||
'review_requested_at',
|
||||
'deposit_reminded_at',
|
||||
@@ -56,15 +66,41 @@
|
||||
class Booking extends Model
|
||||
{
|
||||
/** @use HasFactory<BookingFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::created(function (Booking $booking): void {
|
||||
$booking->forceFill(['reference' => $booking->created_at->format('Y').'-'.str_pad((string) $booking->id, 4, '0', STR_PAD_LEFT)])->saveQuietly();
|
||||
$booking->forceFill(['reference' => $booking->nextReference()])->saveQuietly();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Next booking number of this landlord in the year of creation, continuing after the highest
|
||||
* number already issued. Existing numbers are never rewritten.
|
||||
*/
|
||||
public function nextReference(): string
|
||||
{
|
||||
$year = $this->created_at->format('Y');
|
||||
|
||||
$references = static::withoutGlobalScope('tenant')
|
||||
->where('tenant_id', $this->tenant_id)
|
||||
->where('reference', 'like', $year.'-%')
|
||||
->whereKeyNot($this->id)
|
||||
->lockForUpdate()
|
||||
->pluck('reference');
|
||||
|
||||
$number = 1;
|
||||
|
||||
foreach ($references as $reference) {
|
||||
if (is_string($reference) && preg_match('/-(\d+)$/', $reference, $match) === 1) {
|
||||
$number = max($number, ((int) $match[1]) + 1);
|
||||
}
|
||||
}
|
||||
|
||||
return $year.'-'.str_pad((string) $number, 4, '0', STR_PAD_LEFT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
@@ -83,6 +119,9 @@ protected function casts(): array
|
||||
'balance_due_on' => 'immutable_date',
|
||||
'hold_expires_at' => 'immutable_datetime',
|
||||
'confirmed_at' => 'immutable_datetime',
|
||||
'offer_sent_at' => 'immutable_datetime',
|
||||
'accepted_at' => 'immutable_datetime',
|
||||
'acceptance' => 'array',
|
||||
'cancelled_at' => 'immutable_datetime',
|
||||
'review_requested_at' => 'immutable_datetime',
|
||||
'deposit_reminded_at' => 'immutable_datetime',
|
||||
@@ -109,7 +148,7 @@ public function guest(): BelongsTo
|
||||
}
|
||||
|
||||
/**
|
||||
* Bookings that currently occupy their dates: confirmed ones and reservations whose hold has not expired.
|
||||
* Bookings that currently occupy their dates: confirmed ones and requests/offers whose hold has not expired.
|
||||
*
|
||||
* @param Builder<Booking> $query
|
||||
* @return Builder<Booking>
|
||||
@@ -120,7 +159,7 @@ protected function occupying(Builder $query): Builder
|
||||
return $query->where(fn (Builder $query) => $query
|
||||
->whereIn('status', BookingStatus::occupying())
|
||||
->orWhere(fn (Builder $query) => $query
|
||||
->where('status', BookingStatus::Reserved)
|
||||
->whereIn('status', BookingStatus::holding())
|
||||
->where('hold_expires_at', '>', now())));
|
||||
}
|
||||
|
||||
@@ -185,6 +224,15 @@ public function nights(): int
|
||||
|
||||
public function isHoldActive(): bool
|
||||
{
|
||||
return $this->status === BookingStatus::Reserved && $this->hold_expires_at?->isFuture();
|
||||
return in_array($this->status, BookingStatus::holding(), true) && $this->hold_expires_at?->isFuture();
|
||||
}
|
||||
|
||||
/**
|
||||
* The website this stay belongs to, regardless of which landlord is current.
|
||||
*/
|
||||
public function website(): ?Site
|
||||
{
|
||||
return $this->property()->withoutGlobalScope('tenant')->first()
|
||||
?->site()->withoutGlobalScope('tenant')->first();
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Channels\ChannelRegistry;
|
||||
use App\Channels\Contracts\ChannelConnector;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\ChannelFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
@@ -24,7 +25,7 @@
|
||||
class Channel extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
@@ -9,6 +10,8 @@
|
||||
#[Fillable(['channel_id', 'successful', 'events', 'added', 'changed', 'removed', 'conflicts', 'message', 'duration_ms'])]
|
||||
class ChannelSyncLog extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
public const UPDATED_AT = null;
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\ChannelTaskAction;
|
||||
use App\Enums\ChannelTaskStatus;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\ChannelTaskFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -20,7 +21,7 @@
|
||||
class ChannelTask extends Model
|
||||
{
|
||||
/** @use HasFactory<ChannelTaskFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Concerns;
|
||||
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\Guest;
|
||||
use App\Models\Property;
|
||||
use App\Models\Site;
|
||||
use App\Models\Tenant;
|
||||
use App\Tenancy\TenantContext;
|
||||
use App\Tenancy\TenantContextMissing;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* Every row belongs to exactly one landlord. When a landlord is current, queries only see that
|
||||
* landlord. Inserts copy the landlord from the parent row, then from the current context.
|
||||
*
|
||||
* @mixin Model
|
||||
*/
|
||||
trait BelongsToTenant
|
||||
{
|
||||
public function initializeBelongsToTenant(): void
|
||||
{
|
||||
$this->mergeFillable(['tenant_id']);
|
||||
}
|
||||
|
||||
public static function bootBelongsToTenant(): void
|
||||
{
|
||||
static::addGlobalScope('tenant', function (Builder $builder): void {
|
||||
$context = app(TenantContext::class);
|
||||
|
||||
if ($context->id() !== null) {
|
||||
$builder->where($builder->getModel()->qualifyColumn('tenant_id'), $context->id());
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($context->isRequired()) {
|
||||
throw new TenantContextMissing($builder->getModel()::class);
|
||||
}
|
||||
});
|
||||
|
||||
static::creating(function (Model $model): void {
|
||||
$inherited = self::tenantIdFromParent($model);
|
||||
|
||||
if ($inherited !== null) {
|
||||
$model->setAttribute('tenant_id', $inherited);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (filled($model->getAttribute('tenant_id'))) {
|
||||
return;
|
||||
}
|
||||
|
||||
$current = app(TenantContext::class)->id();
|
||||
|
||||
if ($current !== null) {
|
||||
$model->setAttribute('tenant_id', $current);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if (app()->runningUnitTests() && ! app(TenantContext::class)->isRequired()) {
|
||||
$model->setAttribute('tenant_id', Tenant::query()->create([
|
||||
'name' => 'Testmandant',
|
||||
'slug' => 'test-'.Str::lower(Str::random(10)),
|
||||
])->id);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
throw new TenantContextMissing($model::class);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* The parent row wins, so a booking cannot land on a different landlord than its apartment.
|
||||
*/
|
||||
private static function tenantIdFromParent(Model $model): ?int
|
||||
{
|
||||
$parents = [
|
||||
'property_id' => Property::class,
|
||||
'booking_id' => Booking::class,
|
||||
'channel_id' => Channel::class,
|
||||
'site_id' => Site::class,
|
||||
'guest_id' => Guest::class,
|
||||
];
|
||||
|
||||
foreach ($parents as $column => $class) {
|
||||
$id = $model->getAttribute($column);
|
||||
|
||||
if (! $id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$tenantId = $class::withoutGlobalScope('tenant')->whereKey($id)->value('tenant_id');
|
||||
|
||||
if ($tenantId !== null) {
|
||||
return (int) $tenantId;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
@@ -9,4 +10,7 @@
|
||||
* Value of an editable website text; the available keys are defined in config/content.php.
|
||||
*/
|
||||
#[Fillable(['key', 'value'])]
|
||||
class ContentBlock extends Model {}
|
||||
class ContentBlock extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\ExtraPricing;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\ExtraFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -18,7 +19,7 @@
|
||||
class Extra extends Model
|
||||
{
|
||||
/** @use HasFactory<ExtraFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\FaqFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -13,7 +14,7 @@
|
||||
class Faq extends Model
|
||||
{
|
||||
/** @use HasFactory<FaqFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\FloorPlanFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Floor plan of an apartment: a picture (rendering or scan) from the website photos and the rooms drawn
|
||||
* on it. Room corners are stored in percent of the picture, so the areas fit every picture size.
|
||||
*
|
||||
* @property list<array{id?: string, name?: string, description?: string, hint?: string, points?: string, photo_ids?: list<int|string>, amenity_ids?: list<int|string>, is_visible?: bool}>|null $rooms
|
||||
*/
|
||||
#[Fillable(['property_id', 'photo_id', 'rooms'])]
|
||||
class FloorPlan extends Model
|
||||
{
|
||||
/** @use HasFactory<FloorPlanFactory> */
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'rooms' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Property, $this>
|
||||
*/
|
||||
public function property(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Property::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Photo, $this>
|
||||
*/
|
||||
public function photo(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Photo::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rooms shown on the website: visible and with an area of at least three corners.
|
||||
*
|
||||
* @return Collection<int, array<string, mixed>>
|
||||
*/
|
||||
public function visibleRooms(): Collection
|
||||
{
|
||||
return collect($this->rooms ?? [])
|
||||
->filter(fn (array $room): bool => ($room['is_visible'] ?? true) && filled($room['name'] ?? null) && count(self::points($room['points'] ?? null)) >= 3)
|
||||
->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses "x,y x,y …" (percent) into points, ignoring anything outside 0–100.
|
||||
*
|
||||
* @return list<array{float, float}>
|
||||
*/
|
||||
public static function points(?string $points): array
|
||||
{
|
||||
$parsed = [];
|
||||
foreach (preg_split('/\s+/', trim((string) $points)) ?: [] as $pair) {
|
||||
if (preg_match('/^(\d{1,3}(?:\.\d+)?),(\d{1,3}(?:\.\d+)?)$/', $pair, $match) && (float) $match[1] <= 100 && (float) $match[2] <= 100) {
|
||||
$parsed[] = [(float) $match[1], (float) $match[2]];
|
||||
}
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
}
|
||||
+23
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\GuestFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -17,7 +18,7 @@
|
||||
class Guest extends Model
|
||||
{
|
||||
/** @use HasFactory<GuestFactory> */
|
||||
use HasFactory, Notifiable;
|
||||
use BelongsToTenant, HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
@@ -67,7 +68,19 @@ protected function withMarketingConsent(Builder $query): Builder
|
||||
public function anonymize(): void
|
||||
{
|
||||
DB::transaction(function (): void {
|
||||
$this->bookings()->update(['message' => null]);
|
||||
$this->bookings()->update([
|
||||
'message' => null,
|
||||
'internal_notes' => null,
|
||||
'offer_message' => null,
|
||||
'referral_source' => null,
|
||||
'utm_source' => null,
|
||||
'utm_medium' => null,
|
||||
'utm_campaign' => null,
|
||||
]);
|
||||
Review::query()->whereIn('booking_id', $this->bookings()->select('id'))->update([
|
||||
'display_name' => 'Gast',
|
||||
'private_feedback' => null,
|
||||
]);
|
||||
|
||||
$this->forceFill([
|
||||
'first_name' => 'Anonymisiert',
|
||||
@@ -84,4 +97,12 @@ public function anonymize(): void
|
||||
])->save();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The website of this guest's landlord, regardless of which landlord is current.
|
||||
*/
|
||||
public function website(): ?Site
|
||||
{
|
||||
return $this->tenant?->sites()->withoutGlobalScope('tenant')->orderByDesc('is_default')->orderBy('id')->first();
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\NoticeTone;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\NoticeFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -17,7 +18,7 @@
|
||||
class Notice extends Model
|
||||
{
|
||||
/** @use HasFactory<NoticeFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\PageFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -18,7 +19,7 @@
|
||||
class Page extends Model
|
||||
{
|
||||
/** @use HasFactory<PageFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
public const HOME = 'start';
|
||||
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\PaymentMethod;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\PaymentFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
@@ -16,7 +17,7 @@
|
||||
class Payment extends Model
|
||||
{
|
||||
/** @use HasFactory<PaymentFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\PhotoCategory;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\PhotoFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -22,7 +23,7 @@
|
||||
class Photo extends Model implements HasMedia
|
||||
{
|
||||
/** @use HasFactory<PhotoFactory> */
|
||||
use HasFactory, InteractsWithMedia;
|
||||
use BelongsToTenant, HasFactory, InteractsWithMedia;
|
||||
|
||||
public const COLLECTION = 'image';
|
||||
|
||||
@@ -44,7 +45,9 @@ protected function casts(): array
|
||||
|
||||
public function registerMediaCollections(): void
|
||||
{
|
||||
// Website photos are public files; the app's default disk (FILESYSTEM_DISK=local) is private.
|
||||
$this->addMediaCollection(self::COLLECTION)
|
||||
->useDisk('public')
|
||||
->singleFile()
|
||||
->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\PortalEmailType;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
@@ -15,6 +16,8 @@
|
||||
#[Fillable(['channel_id', 'message_id', 'from', 'subject', 'received_at', 'type', 'status', 'starts_on', 'ends_on', 'reference', 'blocked_period_id', 'excerpt', 'note'])]
|
||||
class PortalEmail extends Model
|
||||
{
|
||||
use BelongsToTenant;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
|
||||
+39
-1
@@ -2,12 +2,15 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Factories\PropertyFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||
|
||||
/**
|
||||
* A rentable holiday apartment. All money amounts are stored in euro cents.
|
||||
@@ -27,28 +30,55 @@
|
||||
'hold_hours',
|
||||
'check_in_time',
|
||||
'check_out_time',
|
||||
'changeover_weekday',
|
||||
'min_stay_fill_gaps',
|
||||
'min_stay_until_changeover',
|
||||
'min_stay_absolute',
|
||||
'is_active',
|
||||
])]
|
||||
class Property extends Model
|
||||
{
|
||||
/** @use HasFactory<PropertyFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
* @return array<string, string>
|
||||
*/
|
||||
/**
|
||||
* Defaults of the minimum stay rules (as in the migration), also before the model is reloaded.
|
||||
*
|
||||
* @var array<string, mixed>
|
||||
*/
|
||||
protected $attributes = [
|
||||
'min_stay_fill_gaps' => true,
|
||||
'min_stay_until_changeover' => false,
|
||||
'min_stay_absolute' => 2,
|
||||
];
|
||||
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
'min_stay_fill_gaps' => 'boolean',
|
||||
'min_stay_until_changeover' => 'boolean',
|
||||
'changeover_weekday' => 'integer',
|
||||
'min_stay_absolute' => 'integer',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Season, $this>
|
||||
*/
|
||||
/**
|
||||
* @return BelongsTo<Site, $this>
|
||||
*/
|
||||
public function site(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Site::class);
|
||||
}
|
||||
|
||||
public function seasons(): HasMany
|
||||
{
|
||||
return $this->hasMany(Season::class)->orderBy('starts_on');
|
||||
@@ -86,6 +116,14 @@ public function amenities(): HasMany
|
||||
return $this->hasMany(Amenity::class)->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasOne<FloorPlan, $this>
|
||||
*/
|
||||
public function floorPlan(): HasOne
|
||||
{
|
||||
return $this->hasOne(FloorPlan::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<SpecialOffer, $this>
|
||||
*/
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\ReviewStatus;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Database\Factories\ReviewFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Scope;
|
||||
@@ -38,7 +39,7 @@
|
||||
class Review extends Model
|
||||
{
|
||||
/** @use HasFactory<ReviewFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/** Rating categories besides the overall rating, with their German labels. */
|
||||
public const CATEGORIES = [
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\SeasonFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -19,7 +20,7 @@
|
||||
class Season extends Model
|
||||
{
|
||||
/** @use HasFactory<SeasonFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
/**
|
||||
* One operational setting (key → value), read through App\Support\Settings.
|
||||
*/
|
||||
#[Fillable(['key', 'value'])]
|
||||
class Setting extends Model {}
|
||||
+99
-1
@@ -2,12 +2,16 @@
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use Carbon\CarbonInterface;
|
||||
use Database\Factories\SiteFactory;
|
||||
use DateInterval;
|
||||
use DateTimeInterface;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
/**
|
||||
* A website: domain, theme with its settings, pages and appearances, and the properties it shows.
|
||||
@@ -17,7 +21,14 @@
|
||||
class Site extends Model
|
||||
{
|
||||
/** @use HasFactory<SiteFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saved(function (Site $site): void {
|
||||
$site->syncDomainHost();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
@@ -32,6 +43,93 @@ protected function casts(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<SiteDomain, $this>
|
||||
*/
|
||||
public function domains(): HasMany
|
||||
{
|
||||
return $this->hasMany(SiteDomain::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scheme and host for guest links. Empty while the website has no hostname yet.
|
||||
*/
|
||||
public function origin(): ?string
|
||||
{
|
||||
$host = $this->domains()->value('host') ?: $this->domain;
|
||||
|
||||
if (! is_string($host) || $host === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
$scheme = in_array($host, ['localhost', '127.0.0.1'], true) ? 'http' : 'https';
|
||||
|
||||
return $scheme.'://'.$host;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $parameters
|
||||
*/
|
||||
public function temporarySignedRoute(string $name, DateTimeInterface|DateInterval|int $expiration, array $parameters = []): string
|
||||
{
|
||||
return $this->withOrigin(fn (): string => URL::temporarySignedRoute($name, $expiration, $parameters));
|
||||
}
|
||||
|
||||
public function signedRoute(string $name, mixed $parameters = []): string
|
||||
{
|
||||
return $this->withOrigin(fn (): string => URL::signedRoute($name, $parameters));
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep the single domain field and the host table on the same hostname.
|
||||
*/
|
||||
public function syncDomainHost(): void
|
||||
{
|
||||
if (! $this->wasRecentlyCreated && ! $this->wasChanged('domain')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$previous = $this->getOriginal('domain');
|
||||
|
||||
if (is_string($previous) && $previous !== '' && $previous !== $this->domain) {
|
||||
$this->domains()->where('host', mb_strtolower($previous))->delete();
|
||||
}
|
||||
|
||||
if (! is_string($this->domain) || $this->domain === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
SiteDomain::query()->updateOrCreate(
|
||||
['host' => mb_strtolower($this->domain)],
|
||||
['site_id' => $this->id],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param callable(): string $callback
|
||||
*/
|
||||
private function withOrigin(callable $callback): string
|
||||
{
|
||||
$origin = $this->origin();
|
||||
|
||||
if ($origin === null) {
|
||||
return $callback();
|
||||
}
|
||||
|
||||
$generator = app('url');
|
||||
$previousRoot = (fn () => $this->forcedRoot)->call($generator);
|
||||
$previousScheme = (fn () => $this->forceScheme)->call($generator);
|
||||
URL::forceRootUrl($origin);
|
||||
URL::forceScheme(parse_url($origin, PHP_URL_SCHEME) ?: 'https');
|
||||
|
||||
try {
|
||||
return $callback();
|
||||
} finally {
|
||||
URL::forceRootUrl($previousRoot);
|
||||
URL::forceScheme(is_string($previousScheme) ? strstr($previousScheme, ':', true) : null);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Page, $this>
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* One hostname of a website. A host belongs to exactly one website.
|
||||
*/
|
||||
#[Fillable(['site_id', 'host'])]
|
||||
class SiteDomain extends Model
|
||||
{
|
||||
/**
|
||||
* @return BelongsTo<Site, $this>
|
||||
*/
|
||||
public function site(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Site::class);
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
use App\Enums\DiscountType;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Models\Concerns\BelongsToTenant;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
@@ -48,7 +49,7 @@
|
||||
class SpecialOffer extends Model
|
||||
{
|
||||
/** @use HasFactory<SpecialOfferFactory> */
|
||||
use HasFactory;
|
||||
use BelongsToTenant, HasFactory;
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Database\Factories\TenantFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
/**
|
||||
* A landlord. Owns websites, apartments, guests, bookings and settings. One account can belong
|
||||
* to several landlords; the operator is not a landlord.
|
||||
*/
|
||||
#[Fillable(['name', 'slug', 'is_active'])]
|
||||
class Tenant extends Model
|
||||
{
|
||||
/** @use HasFactory<TenantFactory> */
|
||||
use HasFactory;
|
||||
|
||||
/**
|
||||
* The landlord the existing single-website data belongs to.
|
||||
*/
|
||||
public static function stommer(): self
|
||||
{
|
||||
return static::query()->firstOrCreate(
|
||||
['slug' => 'stommer'],
|
||||
['name' => 'Stommer'],
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'is_active' => 'boolean',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Site, $this>
|
||||
*/
|
||||
public function sites(): HasMany
|
||||
{
|
||||
return $this->hasMany(Site::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<Property, $this>
|
||||
*/
|
||||
public function properties(): HasMany
|
||||
{
|
||||
return $this->hasMany(Property::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<User, $this>
|
||||
*/
|
||||
public function users(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(User::class)->withPivot('role')->withTimestamps();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models;
|
||||
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Written when an operator opens a landlord's admin. Support access stays visible.
|
||||
*/
|
||||
#[Fillable(['tenant_id', 'user_id', 'created_at'])]
|
||||
class TenantAccessLog extends Model
|
||||
{
|
||||
public $timestamps = false;
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function casts(): array
|
||||
{
|
||||
return [
|
||||
'created_at' => 'datetime',
|
||||
];
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::creating(function (TenantAccessLog $log): void {
|
||||
$log->created_at ??= now();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<Tenant, $this>
|
||||
*/
|
||||
public function tenant(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Tenant::class);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class);
|
||||
}
|
||||
}
|
||||
+169
-3
@@ -5,6 +5,7 @@
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\UserRole;
|
||||
use App\Tenancy\TenantContext;
|
||||
use Database\Factories\UserFactory;
|
||||
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
|
||||
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthenticationRecovery;
|
||||
@@ -15,6 +16,7 @@
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
@@ -25,12 +27,24 @@ class User extends Authenticatable implements FilamentUser, HasAppAuthentication
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasFactory, InteractsWithAppAuthentication, InteractsWithAppAuthenticationRecovery, Notifiable;
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saved(function (User $user): void {
|
||||
$user->attachCurrentRole();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Accounts are created by administrators only; an account without a role has no access.
|
||||
* The operator panel is only for operators. The landlord admin needs a role there, or the operator flag.
|
||||
* Password and two-factor belong to the account and are not a per-landlord setting.
|
||||
*/
|
||||
public function canAccessPanel(Panel $panel): bool
|
||||
{
|
||||
return $this->role !== null;
|
||||
if ($panel->getId() === 'operator') {
|
||||
return (bool) $this->is_operator;
|
||||
}
|
||||
|
||||
return $this->currentRole() !== null || (bool) $this->is_operator;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,7 +57,158 @@ public function adminMode(): AdminMode
|
||||
|
||||
public function hasRole(UserRole ...$roles): bool
|
||||
{
|
||||
return in_array($this->role, $roles, true);
|
||||
return in_array($this->currentRole(), $roles, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Role inside the landlord that is current. The operator acts as administrator of whichever landlord is open.
|
||||
* With exactly one landlord, the old account role still applies until a membership exists.
|
||||
*/
|
||||
public function currentRole(): ?UserRole
|
||||
{
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId !== null) {
|
||||
if ($this->is_operator) {
|
||||
return UserRole::Admin;
|
||||
}
|
||||
|
||||
$role = $this->roleOn($tenantId);
|
||||
|
||||
if ($role !== null) {
|
||||
return $role;
|
||||
}
|
||||
|
||||
if ($this->role !== null && Tenant::query()->count() === 1) {
|
||||
return $this->role;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($this->role !== null) {
|
||||
return $this->role;
|
||||
}
|
||||
|
||||
if ($this->is_operator) {
|
||||
return UserRole::Admin;
|
||||
}
|
||||
|
||||
$memberships = $this->tenants()->get();
|
||||
|
||||
if ($memberships->count() === 1) {
|
||||
return $this->roleFromPivot($memberships->first()?->pivot?->role);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function roleOn(int $tenantId): ?UserRole
|
||||
{
|
||||
$membership = $this->tenants()->where('tenants.id', $tenantId)->first();
|
||||
|
||||
return $this->roleFromPivot($membership?->pivot?->role);
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy the account role onto the current landlord. Does nothing without a role or a landlord.
|
||||
*/
|
||||
public function attachCurrentRole(?Tenant $tenant = null): void
|
||||
{
|
||||
if ($this->role === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$tenant ??= app(TenantContext::class)->get();
|
||||
|
||||
if ($tenant === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$alreadyMember = $this->tenants()->where('tenants.id', $tenant->id)->exists();
|
||||
|
||||
if ($alreadyMember) {
|
||||
if ($this->wasChanged('role')) {
|
||||
$this->tenants()->updateExistingPivot($tenant->id, ['role' => $this->role->value]);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->tenants()->attach($tenant->id, ['role' => $this->role->value]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Password and two-factor stay on the account. A landlord admin may reset them only when the
|
||||
* account belongs to no other landlord. Otherwise only the operator may.
|
||||
*/
|
||||
public function mayResetCredentials(?User $other): bool
|
||||
{
|
||||
if ($this->is_operator) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (! $this->hasRole(UserRole::Admin)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($other === null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $other->tenants()->count() < 2;
|
||||
}
|
||||
|
||||
/**
|
||||
* Another landlord this account belongs to, when that landlord has its own domain.
|
||||
*/
|
||||
public function otherTenantAdminUrl(): ?string
|
||||
{
|
||||
$current = app(TenantContext::class)->id();
|
||||
$other = $this->tenants()->where('tenants.id', '!=', $current)->first();
|
||||
|
||||
if ($other === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$domain = $other->sites()->withoutGlobalScope('tenant')->whereNotNull('domain')->value('domain');
|
||||
|
||||
if (! is_string($domain) || $domain === '') {
|
||||
return null;
|
||||
}
|
||||
|
||||
return 'https://'.$domain.'/admin';
|
||||
}
|
||||
|
||||
public function showsTenantSwitch(): bool
|
||||
{
|
||||
return $this->otherTenantAdminUrl() !== null;
|
||||
}
|
||||
|
||||
public function revokeCurrentTenant(): void
|
||||
{
|
||||
$tenantId = app(TenantContext::class)->id();
|
||||
|
||||
if ($tenantId !== null) {
|
||||
$this->tenants()->detach($tenantId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Tenant, $this>
|
||||
*/
|
||||
public function tenants(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(Tenant::class)->withPivot('role')->withTimestamps();
|
||||
}
|
||||
|
||||
private function roleFromPivot(mixed $role): ?UserRole
|
||||
{
|
||||
if ($role instanceof UserRole) {
|
||||
return $role;
|
||||
}
|
||||
|
||||
return is_string($role) ? UserRole::tryFrom($role) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -58,6 +223,7 @@ protected function casts(): array
|
||||
'password' => 'hashed',
|
||||
'role' => UserRole::class,
|
||||
'admin_mode' => AdminMode::class,
|
||||
'is_operator' => 'boolean',
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ private function occupies(BookingStatus|string|null $status): bool
|
||||
|
||||
private function tasks(Booking $booking, ChannelTaskAction $action): void
|
||||
{
|
||||
$this->createChannelTasks->handle($booking->property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
|
||||
$property = $booking->property()->withoutGlobalScope('tenant')->first();
|
||||
|
||||
if ($property === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->createChannelTasks->handle($property, $booking->arrival, $booking->departure, $action, "Buchung {$booking->reference}");
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Enums\Permission;
|
||||
|
||||
class AmenityPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return [UserRole::Content];
|
||||
return Permission::Content;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Enums\Permission;
|
||||
|
||||
class AppearancePolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return [UserRole::Content];
|
||||
return Permission::Content;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Enums\Permission;
|
||||
|
||||
class BlockedPeriodPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return [UserRole::Rentals];
|
||||
return Permission::Bookings;
|
||||
}
|
||||
}
|
||||
@@ -2,12 +2,12 @@
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Enums\Permission;
|
||||
|
||||
class BookingPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
protected function permission(): Permission
|
||||
{
|
||||
return [UserRole::Rentals];
|
||||
return Permission::Bookings;
|
||||
}
|
||||
}
|
||||
Loaded 100 of 290 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user