Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
70a8c5072b | ||
|
|
20235b9139 | ||
|
|
565eee4325 | ||
|
|
fd744edf8c | ||
|
|
7a6ee316cd | ||
|
|
6690beafe6 | ||
|
|
4f69b426a4 | ||
|
|
82698f8eda | ||
|
|
7d0bc93abc |
No files matched your search
@@ -43,6 +43,8 @@ MAIL_FROM_NAME="${APP_NAME}"
|
||||
FEWO_OWNER_NAME="Brigitte Stommer"
|
||||
FEWO_OWNER_EMAIL=fewo@stommer.de
|
||||
FEWO_NOTIFICATION_EMAIL=fewo@stommer.de
|
||||
# Nur Testbetrieb: alle E-Mails ausschließlich an diese Adresse (leer = normaler Versand)
|
||||
FEWO_MAIL_REDIRECT_TO=
|
||||
FEWO_BANK_ACCOUNT_HOLDER=
|
||||
FEWO_BANK_IBAN=
|
||||
FEWO_BANK_BIC=
|
||||
|
||||
@@ -10,10 +10,10 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- 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).
|
||||
|
||||
@@ -10,10 +10,10 @@ # Ferienwohnung Stommer
|
||||
- Portals must be integrated through a pluggable channel-connector system (see concept §7), never hard-coded.
|
||||
- Bookings/blocks use nights: `arrival <= night < departure`; same-day changeover is allowed. Reservations with an elapsed hold never occupy the calendar (scope `Booking::occupying()`), cron only updates status.
|
||||
- Business operations live in `app/Actions` (CreateReservation, ConfirmBooking, …); Filament pages and Livewire components call them instead of changing bookings directly.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts.
|
||||
- Special offers are evaluated automatically by `PriceCalculator`; discounts are `QuoteLineType::Discount` lines with negative amounts. Kinds (`OfferKind`): rule, fixed dates, gap filler (`App\Availability\GapFinder`). Which offers the website advertises is decided by `App\Pricing\OfferShowcase` (not by appearances); it prices fixed dates/gaps with `PriceCalculator`.
|
||||
- Portal sync lives in `app/Channels` (connector interface + registry in `config/channels.php`, iCal connector/parser/feed). Our system leads; `SyncChannel` imports portal occupations as `BlockedPeriod` rows with `channel_id`; each channel's export feed excludes its own blocks. Observers on Booking/BlockedPeriod create `ChannelTask`s for portals with `requires_manual_blocking`. Portal booking e-mails are a fast path (`app/Channels/Mail`, `ProcessPortalMail`): they create blocks with source `email`, which `SyncChannel` later confirms/replaces and never removes as stale. Portal analysis: `docs/PORTALE.md`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`.
|
||||
- Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/<key>` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make <key>`, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request.
|
||||
- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`.
|
||||
- Deployment: `scripts/deploy.sh <env> setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy/<env>/<timestamp>`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`.
|
||||
- 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).
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
<?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 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(config('fewo.notification_email'))->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);
|
||||
}
|
||||
}
|
||||
@@ -47,8 +47,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 +65,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 +76,42 @@ 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]), []];
|
||||
}
|
||||
|
||||
$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.
|
||||
*/
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,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();
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Mail\OfferAnswered;
|
||||
use App\Models\Booking;
|
||||
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(config('fewo.notification_email'))->send(new OfferAnswered($booking, accepted: false));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?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
|
||||
{
|
||||
return URL::temporarySignedRoute('offers.show', $booking->hold_expires_at, ['booking' => $booking, 'v' => $booking->offer_version]);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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));
|
||||
}
|
||||
}
|
||||
@@ -64,7 +64,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',
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
namespace App\Availability;
|
||||
|
||||
use App\Models\Property;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* Free gaps in the calendar: runs of free nights with an occupied night (booking or block) directly
|
||||
* before and after. Open-ended free periods (nothing booked behind them yet) are not gaps.
|
||||
*/
|
||||
class GapFinder
|
||||
{
|
||||
/** How far around a stay we look for the neighbouring occupations. */
|
||||
private const LOOKAROUND_NIGHTS = 60;
|
||||
|
||||
public function __construct(private AvailabilityChecker $availability = new AvailabilityChecker) {}
|
||||
|
||||
/**
|
||||
* Length in nights of the gap that contains the whole stay, or null if the stay is not inside a gap
|
||||
* (because a night is occupied or the free period is not closed on both sides).
|
||||
*/
|
||||
public function gapContaining(Property $property, CarbonImmutable $arrival, CarbonImmutable $departure): ?int
|
||||
{
|
||||
$from = $arrival->subDays(self::LOOKAROUND_NIGHTS);
|
||||
$until = $departure->addDays(self::LOOKAROUND_NIGHTS);
|
||||
$occupied = $this->availability->occupiedNights($property, $from, $until);
|
||||
|
||||
for ($night = $arrival; $night->lessThan($departure); $night = $night->addDay()) {
|
||||
if (isset($occupied[$night->toDateString()])) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$start = $arrival;
|
||||
while (! isset($occupied[$start->subDay()->toDateString()])) {
|
||||
$start = $start->subDay();
|
||||
if ($start->lessThanOrEqualTo($from)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
$end = $departure;
|
||||
while (! isset($occupied[$end->toDateString()])) {
|
||||
$end = $end->addDay();
|
||||
if ($end->greaterThanOrEqualTo($until)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return (int) $start->diffInDays($end);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gaps of 1 … $maxNights nights starting within [$from, $until), as [arrival, departure] pairs.
|
||||
*
|
||||
* @return list<array{0: CarbonImmutable, 1: CarbonImmutable}>
|
||||
*/
|
||||
public function gaps(Property $property, CarbonImmutable $from, CarbonImmutable $until, int $maxNights): array
|
||||
{
|
||||
$occupied = $this->availability->occupiedNights($property, $from->subDay(), $until->addDays($maxNights + 1));
|
||||
|
||||
$gaps = [];
|
||||
$night = $from;
|
||||
while ($night->lessThan($until)) {
|
||||
$isGapStart = ! isset($occupied[$night->toDateString()]) && isset($occupied[$night->subDay()->toDateString()]);
|
||||
if (! $isGapStart) {
|
||||
$night = $night->addDay();
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$end = $night;
|
||||
while (! isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$end = $end->addDay();
|
||||
}
|
||||
|
||||
if (isset($occupied[$end->toDateString()]) && $night->diffInDays($end) <= $maxNights) {
|
||||
$gaps[] = [$night, $end];
|
||||
}
|
||||
|
||||
$night = $end->addDay();
|
||||
}
|
||||
|
||||
return $gaps;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
use Throwable;
|
||||
|
||||
#[Signature('backup:database {--keep= : Anzahl aufbewahrter Sicherungen}')]
|
||||
#[Description('Write a compressed SQL dump of the database to storage/app/private/backups and keep the newest ones')]
|
||||
class BackupDatabase extends Command
|
||||
{
|
||||
public const DIRECTORY = 'backups';
|
||||
|
||||
/** Tables without lasting value; their content is not dumped (structure only). */
|
||||
private const SKIP_DATA = ['sessions', 'cache', 'cache_locks', 'jobs', 'job_batches', 'failed_jobs'];
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(): int
|
||||
{
|
||||
$keep = (int) ($this->option('keep') ?? config('fewo.backup.keep', 14));
|
||||
$file = self::DIRECTORY.'/fewo-'.now()->format('Ymd-His').'.sql.gz';
|
||||
$temp = tempnam(sys_get_temp_dir(), 'fewo-backup');
|
||||
$out = gzopen($temp, 'wb6');
|
||||
|
||||
try {
|
||||
gzwrite($out, '-- FeWo Stommer database backup '.now()->toIso8601String().' ('.DB::getDriverName().")\n");
|
||||
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=0;\nSET NAMES utf8mb4;\n" : "PRAGMA foreign_keys=OFF;\n");
|
||||
|
||||
foreach ($this->tables() as $table) {
|
||||
gzwrite($out, "\nDROP TABLE IF EXISTS ".$this->quoteName($table).";\n".$this->createStatement($table).";\n");
|
||||
if (! in_array($table, self::SKIP_DATA, true)) {
|
||||
$this->dumpRows($out, $table);
|
||||
}
|
||||
}
|
||||
|
||||
gzwrite($out, $this->isMysql() ? "SET FOREIGN_KEY_CHECKS=1;\n" : "PRAGMA foreign_keys=ON;\n");
|
||||
gzclose($out);
|
||||
|
||||
Storage::disk('local')->put($file, (string) file_get_contents($temp));
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
$this->error('Sicherung fehlgeschlagen: '.$exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
} finally {
|
||||
@unlink($temp);
|
||||
}
|
||||
|
||||
$this->prune($keep);
|
||||
$this->info("Sicherung erstellt: storage/app/private/{$file} (".round(Storage::disk('local')->size($file) / 1024).' KB)');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
private function isMysql(): bool
|
||||
{
|
||||
return in_array(DB::getDriverName(), ['mysql', 'mariadb'], true);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<string>
|
||||
*/
|
||||
private function tables(): array
|
||||
{
|
||||
return $this->isMysql()
|
||||
? array_map(fn (object $row): string => (string) array_values((array) $row)[0], DB::select('SHOW TABLES'))
|
||||
: array_map(fn (object $row): string => $row->name, DB::select("SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%' ORDER BY name"));
|
||||
}
|
||||
|
||||
private function createStatement(string $table): string
|
||||
{
|
||||
if ($this->isMysql()) {
|
||||
return (string) array_values((array) DB::selectOne('SHOW CREATE TABLE '.$this->quoteName($table)))[1];
|
||||
}
|
||||
|
||||
return (string) DB::selectOne("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", [$table])->sql;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param resource $out
|
||||
*/
|
||||
private function dumpRows($out, string $table): void
|
||||
{
|
||||
$pdo = DB::connection()->getPdo();
|
||||
$offset = 0;
|
||||
|
||||
do {
|
||||
$rows = DB::table($table)->offset($offset)->limit(500)->get();
|
||||
foreach ($rows as $row) {
|
||||
$values = array_map(fn ($value): string => $value === null ? 'NULL' : (is_int($value) || is_float($value) ? (string) $value : $pdo->quote((string) $value)), (array) $row);
|
||||
gzwrite($out, 'INSERT INTO '.$this->quoteName($table).' ('.implode(', ', array_map($this->quoteName(...), array_keys((array) $row))).') VALUES ('.implode(', ', $values).");\n");
|
||||
}
|
||||
$offset += 500;
|
||||
} while ($rows->count() === 500);
|
||||
}
|
||||
|
||||
private function quoteName(string $name): string
|
||||
{
|
||||
return $this->isMysql() ? '`'.str_replace('`', '``', $name).'`' : '"'.str_replace('"', '""', $name).'"';
|
||||
}
|
||||
|
||||
private function prune(int $keep): void
|
||||
{
|
||||
collect(Storage::disk('local')->files(self::DIRECTORY))
|
||||
->filter(fn (string $path): bool => str_ends_with($path, '.sql.gz'))
|
||||
->sort()
|
||||
->reverse()
|
||||
->slice(max(1, $keep))
|
||||
->each(fn (string $path) => Storage::disk('local')->delete($path));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeChecker;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('themes:check {theme? : Key des Themes (leer = alle)}')]
|
||||
#[Description('Check themes against the theme contract (docs/THEME-ERSTELLUNG.md): manifest, build, required markup, colours, contrast')]
|
||||
class CheckTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeChecker $checker): int
|
||||
{
|
||||
$key = $this->argument('theme');
|
||||
if ($key !== null && ! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$themes = $key !== null ? [$registry->all()[$key]] : array_values($registry->all());
|
||||
$failed = false;
|
||||
|
||||
foreach ($themes as $theme) {
|
||||
['errors' => $errors, 'warnings' => $warnings] = $checker->check($theme);
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$theme->name}</> ({$theme->key} {$theme->version}".($theme->parent ? ", Eltern-Theme {$theme->parent}" : '').')');
|
||||
|
||||
foreach ($errors as $error) {
|
||||
$this->line(" <fg=red>✗</> {$error}");
|
||||
}
|
||||
foreach ($warnings as $warning) {
|
||||
$this->line(" <fg=yellow>!</> {$warning}");
|
||||
}
|
||||
if ($errors === [] && $warnings === []) {
|
||||
$this->line(' <fg=green>✓</> Alles in Ordnung.');
|
||||
}
|
||||
|
||||
$failed = $failed || $errors !== [];
|
||||
}
|
||||
|
||||
$this->line('');
|
||||
|
||||
return $failed ? self::FAILURE : self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -55,9 +55,7 @@ public function handle(): int
|
||||
|
||||
$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;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Themes\ThemeManifest;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\File;
|
||||
|
||||
#[Signature('themes:make {key : Ordner/Key, z. B. ostsee-nacht} {--name= : Anzeigename} {--parent= : Eltern-Theme (Standard: Basis-Theme)} {--description= : Beschreibung für die Theme-Auswahl}')]
|
||||
#[Description('Create a new theme next to the existing ones (never overwrites) – inherits everything until views are added')]
|
||||
class MakeTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry): int
|
||||
{
|
||||
$key = (string) $this->argument('key');
|
||||
$parent = (string) ($this->option('parent') ?: config('themes.base'));
|
||||
$themesPath = rtrim((string) (config('themes.paths')[0] ?? resource_path('themes')), '/\\');
|
||||
$path = "{$themesPath}/{$key}";
|
||||
$folder = str_replace('\\', '/', ltrim(substr($path, strlen(base_path())), '/\\'));
|
||||
|
||||
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $key)) {
|
||||
$this->error('Key: nur Kleinbuchstaben, Ziffern und Bindestriche, z. B. ostsee-nacht.');
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (File::exists($path) || isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ gibt es schon – es wird nichts überschrieben.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
if (! isset($registry->all()[$parent])) {
|
||||
$this->error("Eltern-Theme „{$parent}“ ist nicht installiert.");
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$name = (string) ($this->option('name') ?: str($key)->replace('-', ' ')->title());
|
||||
$manifest = [
|
||||
'key' => $key,
|
||||
'name' => $name,
|
||||
'version' => '0.1.0',
|
||||
'parent' => $parent,
|
||||
'description' => (string) ($this->option('description') ?: "Neues Theme auf Basis von „{$registry->get($parent)->name}“."),
|
||||
'assets' => ['css' => "{$folder}/theme.css", 'js' => "{$folder}/theme.js"],
|
||||
'tokens' => $registry->tokens($parent),
|
||||
];
|
||||
|
||||
File::ensureDirectoryExists("{$path}/views/sections");
|
||||
File::ensureDirectoryExists("{$path}/views/partials");
|
||||
File::put("{$path}/views/sections/.gitkeep", '');
|
||||
File::put("{$path}/views/partials/.gitkeep", '');
|
||||
File::put("{$path}/theme.json", json_encode($manifest, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)."\n");
|
||||
File::put("{$path}/theme.css", $this->css($name, $parent, $path, $registry));
|
||||
File::put("{$path}/theme.js", $this->js($name, ThemeManifest::relativePath($path, $registry->get($parent)->path).'/theme.js'));
|
||||
File::put("{$path}/README.md", $this->readme($name, $key, $parent));
|
||||
|
||||
$this->info("Theme „{$name}“ angelegt: {$folder}");
|
||||
$this->line('Es erbt zunächst alles von „'.$parent.'“. Vorlagen nach views/ kopieren und umgestalten – Anleitung: docs/THEME-ERSTELLUNG.md');
|
||||
$this->line("Prüfen: php artisan themes:check {$key} · Bauen: npm run build · Auswählen: Admin › System › Websites › Theme (dort „Vorschau“).");
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Child theme CSS: Tailwind, the reusable styles of the nearest ancestor that has a theme-base.css,
|
||||
* and the template sources of all ancestors, the booking forms and the theme itself.
|
||||
*/
|
||||
private function css(string $name, string $parent, string $path, ThemeRegistry $registry): string
|
||||
{
|
||||
$ancestors = $registry->chain($parent);
|
||||
$base = collect($ancestors)->first(fn (ThemeManifest $theme): bool => is_file($theme->path.'/theme-base.css')) ?? $ancestors[0];
|
||||
$import = ThemeManifest::relativePath($path, $base->path).'/theme-base.css';
|
||||
$sources = collect($ancestors)
|
||||
->map(fn (ThemeManifest $theme): string => "@source '".ThemeManifest::relativePath($path, $theme->viewsPath())."';")
|
||||
->push("@source '".ThemeManifest::relativePath($path, resource_path('views/livewire'))."';")
|
||||
->push("@source './views';")
|
||||
->implode("\n");
|
||||
|
||||
return <<<CSS
|
||||
/*
|
||||
* Theme „{$name}“ – Child von „{$parent}“ (Anleitung: docs/THEME-ERSTELLUNG.md).
|
||||
* theme-base.css des Eltern-Themes bringt Schriften, Token-Mapping und Basis-Klassen (.eyebrow,
|
||||
* .heading-display, .btn-primary, .btn-accent, .prose-theme, .reveal). Hier nur Abweichungen ergänzen.
|
||||
*/
|
||||
@import 'tailwindcss';
|
||||
@import '{$import}';
|
||||
|
||||
/* Eigene Schriften selbst hosten: npm install @fontsource/<schrift> und hier importieren, z. B.
|
||||
@import '@fontsource/fraunces/400.css';
|
||||
*/
|
||||
|
||||
/* Vorlagen, deren Klassen gebaut werden: geerbte, Buchungsformulare, eigene. */
|
||||
{$sources}
|
||||
|
||||
@theme inline {
|
||||
/* --font-display: 'Fraunces', Georgia, serif; */
|
||||
/* --font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif; */
|
||||
}
|
||||
|
||||
@layer components {
|
||||
}
|
||||
|
||||
CSS;
|
||||
}
|
||||
|
||||
private function js(string $name, string $import): string
|
||||
{
|
||||
return <<<JS
|
||||
/**
|
||||
* Theme „{$name}“: übernimmt Lightbox, Verfügbarkeitssuche und rollierende Angebote vom Eltern-Theme.
|
||||
* Eigene Verbesserungen darunter – alles muss auch ohne JavaScript funktionieren.
|
||||
*/
|
||||
import '{$import}';
|
||||
|
||||
JS;
|
||||
}
|
||||
|
||||
private function readme(string $name, string $key, string $parent): string
|
||||
{
|
||||
return <<<MD
|
||||
# Theme „{$name}“ (`{$key}`)
|
||||
|
||||
Child-Theme von `{$parent}`. Vorlagen, die hier fehlen, kommen vom Eltern-Theme.
|
||||
|
||||
- Anleitung und Vorlagen-Vertrag: `docs/THEME-ERSTELLUNG.md`, `docs/THEMES.md` §5
|
||||
- Prüfen: `php artisan themes:check {$key}`
|
||||
- Ansehen ohne Umschalten: Admin › System › Websites › Theme „{$name}“ wählen › „Vorschau“ (erst danach speichern)
|
||||
|
||||
## Eigene Vorlagen
|
||||
|
||||
| Datei | Zweck |
|
||||
|---|---|
|
||||
| | |
|
||||
|
||||
MD;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use App\Models\Page;
|
||||
use App\Themes\ThemeFactory;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
#[Signature('themes:preview {theme : Key des Themes} {--hours=24 : Gültigkeit der Links}')]
|
||||
#[Description('Print signed preview links: every page of the site with the theme, in every appearance – without switching the site')]
|
||||
class PreviewTheme extends Command
|
||||
{
|
||||
/**
|
||||
* Execute the console command.
|
||||
*/
|
||||
public function handle(ThemeRegistry $registry, ThemeFactory $factory): int
|
||||
{
|
||||
$key = (string) $this->argument('theme');
|
||||
if (! isset($registry->all()[$key])) {
|
||||
$this->error("Theme „{$key}“ nicht gefunden. Installiert: ".implode(', ', array_keys($registry->all())));
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$site = $factory->site();
|
||||
$expires = now()->addHours((int) $this->option('hours'));
|
||||
$pages = $site->exists ? $site->pages()->where('is_published', true)->orderBy('sort_order')->get() : collect();
|
||||
$appearances = $site->exists ? $site->appearances()->orderByDesc('is_default')->orderBy('starts_md')->get() : collect();
|
||||
|
||||
$this->info("Vorschau „{$registry->get($key)->name}“ für {$site->name} (gültig bis {$expires->format('d.m.Y H:i')}):");
|
||||
foreach ($pages as $page) {
|
||||
$this->line('');
|
||||
$this->line("<options=bold>{$page->title}</>");
|
||||
$this->line(' heute: '.$this->url($page, ['theme' => $key], $expires));
|
||||
foreach ($appearances as $appearance) {
|
||||
$this->line(str_pad(" {$appearance->name}:", 16).$this->url($page, ['theme' => $key, 'vorschau' => $appearance->id], $expires));
|
||||
}
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, mixed> $parameters
|
||||
*/
|
||||
private function url(Page $page, array $parameters, \DateTimeInterface $expires): string
|
||||
{
|
||||
return $page->isHome()
|
||||
? URL::temporarySignedRoute('home', $expires, $parameters)
|
||||
: URL::temporarySignedRoute('page', $expires, ['slug' => $page->slug, ...$parameters]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use App\Filament\Pages\PricesAndOffers;
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Filament\Resources\Guests\GuestResource;
|
||||
use App\Filament\Resources\Photos\PhotoResource;
|
||||
use App\Filament\Resources\Reviews\ReviewResource;
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How much of the admin a user sees. It only shapes the menu – what a user may do is decided by the role.
|
||||
*/
|
||||
enum AdminMode: string implements HasDescription, HasLabel
|
||||
{
|
||||
case Simple = 'simple';
|
||||
case Expert = 'expert';
|
||||
|
||||
/**
|
||||
* Menu entries of the simple mode: day-to-day work with requests, bookings, contracts and the calendar.
|
||||
*
|
||||
* @var list<class-string>
|
||||
*/
|
||||
public const SIMPLE_NAVIGATION = [
|
||||
BookingResource::class,
|
||||
BlockedPeriodResource::class,
|
||||
PricesAndOffers::class,
|
||||
GuestResource::class,
|
||||
ChannelTaskResource::class,
|
||||
ReviewResource::class,
|
||||
PhotoResource::class,
|
||||
];
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Einfache Ansicht',
|
||||
self::Expert => 'Expertenansicht',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Portal-Aufgaben, Bewertungen, Fotos',
|
||||
self::Expert => 'Alle Einstellungen: Preise, Angebote, Portale, Webseite, System',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a resource or page appears in the menu in this mode.
|
||||
*
|
||||
* @param class-string $class
|
||||
*/
|
||||
public function shows(string $class): bool
|
||||
{
|
||||
return $this === self::Expert || in_array($class, self::SIMPLE_NAVIGATION, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Label of the user menu entry that switches to this mode.
|
||||
*/
|
||||
public function switchLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Simple => 'Zur einfachen Ansicht wechseln',
|
||||
self::Expert => 'Zur Expertenansicht wechseln',
|
||||
};
|
||||
}
|
||||
|
||||
public function other(): self
|
||||
{
|
||||
return $this === self::Simple ? self::Expert : self::Simple;
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,13 @@
|
||||
|
||||
enum BookingStatus: string implements HasColor, HasLabel
|
||||
{
|
||||
/** Guest request; the dates are held until hold_expires_at. */
|
||||
/** Non-binding guest request; the dates are held until hold_expires_at. */
|
||||
case Reserved = 'reserved';
|
||||
|
||||
/** The landlord sent an offer; the dates are held until hold_expires_at (= end of the offer's validity). */
|
||||
case OfferSent = 'offer_sent';
|
||||
|
||||
/** Binding booking: the guest accepted the offer (or the landlord confirmed directly). */
|
||||
case Confirmed = 'confirmed';
|
||||
case DepositPaid = 'deposit_paid';
|
||||
case Paid = 'paid';
|
||||
@@ -20,7 +25,8 @@ enum BookingStatus: string implements HasColor, HasLabel
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'Vorreserviert',
|
||||
self::Reserved => 'Anfrage (vorgemerkt)',
|
||||
self::OfferSent => 'Angebot gesendet',
|
||||
self::Confirmed => 'Bestätigt',
|
||||
self::DepositPaid => 'Anzahlung erhalten',
|
||||
self::Paid => 'Bezahlt',
|
||||
@@ -35,12 +41,23 @@ public function getColor(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Reserved => 'warning',
|
||||
self::OfferSent => 'primary',
|
||||
self::Confirmed, self::DepositPaid => 'info',
|
||||
self::Paid, self::Completed => 'success',
|
||||
self::Declined, self::Expired, self::Cancelled => 'gray',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar while their hold time (hold_expires_at) runs.
|
||||
*
|
||||
* @return list<self>
|
||||
*/
|
||||
public static function holding(): array
|
||||
{
|
||||
return [self::Reserved, self::OfferSent];
|
||||
}
|
||||
|
||||
/**
|
||||
* Statuses that occupy the calendar regardless of any hold time.
|
||||
*
|
||||
|
||||
@@ -18,6 +18,9 @@ enum DiscountType: string implements HasLabel
|
||||
/** discount_value = number of cheapest nights that are free */
|
||||
case FreeNights = 'free_nights';
|
||||
|
||||
/** discount_value = package price in euro cents for all nights of the stay */
|
||||
case FixedStayPrice = 'fixed_stay_price';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
@@ -25,6 +28,12 @@ public function getLabel(): string
|
||||
self::AmountPerStay => 'Rabatt in € pro Aufenthalt',
|
||||
self::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
self::FreeNights => 'Gratis-Nächte',
|
||||
self::FixedStayPrice => 'Pauschalpreis für den Aufenthalt',
|
||||
};
|
||||
}
|
||||
|
||||
public function isMoney(): bool
|
||||
{
|
||||
return in_array($this, [self::AmountPerStay, self::NightlyRate, self::FixedStayPrice], true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* How an offer finds its stays. All kinds are priced by PriceCalculator and advertised by OfferShowcase.
|
||||
*/
|
||||
enum OfferKind: string implements HasDescription, HasLabel
|
||||
{
|
||||
/** Conditions only (last minute, early bird, from N nights, weekend …). */
|
||||
case Rule = 'rule';
|
||||
|
||||
/** One fixed arrival and departure (stay_from / stay_until), e.g. a week as a package. */
|
||||
case FixedDates = 'fixed_dates';
|
||||
|
||||
/** Free gaps of at most max_gap_nights between two occupations, found automatically. */
|
||||
case GapFiller = 'gap_filler';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Rabattaktion (nach Bedingungen)',
|
||||
self::FixedDates => 'Fester Termin',
|
||||
self::GapFiller => 'Lückenfüller (Kalenderlücken)',
|
||||
};
|
||||
}
|
||||
|
||||
public function getDescription(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Rule => 'Gilt für jeden Aufenthalt, der die Bedingungen erfüllt, z. B. Last Minute oder „ab 3 Nächten −10 %“.',
|
||||
self::FixedDates => 'Ein bestimmter Zeitraum, z. B. „7 Nächte vom 07. bis 14.11.“ – wird nur beworben, solange er frei ist.',
|
||||
self::GapFiller => 'Findet freie Lücken zwischen zwei Buchungen automatisch und bewirbt sie mit konkreten Terminen.',
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -14,6 +14,16 @@ public static function notAvailable(): self
|
||||
return new self('Der gewünschte Zeitraum ist leider nicht mehr frei.');
|
||||
}
|
||||
|
||||
public static function offerExpired(): self
|
||||
{
|
||||
return new self('Dieses Angebot ist nicht mehr gültig. Bitte melden Sie sich bei uns – gern erstellen wir Ihnen ein neues Angebot.');
|
||||
}
|
||||
|
||||
public static function offerOutdated(): self
|
||||
{
|
||||
return new self('Zu dieser Anfrage gibt es inzwischen ein aktualisiertes Angebot. Bitte verwenden Sie den Link aus unserer neuesten E-Mail.');
|
||||
}
|
||||
|
||||
public static function invalidTransition(string $statusLabel, string $action): self
|
||||
{
|
||||
return new self("Eine Buchung im Status „{$statusLabel}“ kann nicht {$action} werden.");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Concerns;
|
||||
|
||||
use App\Enums\AdminMode;
|
||||
use App\Models\User;
|
||||
use Filament\Facades\Filament;
|
||||
|
||||
/**
|
||||
* Hides the menu entry in the simple admin mode unless it is part of AdminMode::SIMPLE_NAVIGATION.
|
||||
* The page stays reachable by URL; access is governed by the policies.
|
||||
*/
|
||||
trait FollowsAdminMode
|
||||
{
|
||||
public static function shouldRegisterNavigation(): bool
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
$mode = $user instanceof User ? $user->adminMode() : AdminMode::Expert;
|
||||
|
||||
return parent::shouldRegisterNavigation() && $mode->shows(static::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Forms\Components;
|
||||
|
||||
use App\Models\Photo;
|
||||
use Filament\Forms\Components\Select;
|
||||
|
||||
/**
|
||||
* Chooses website photos with a thumbnail next to each description, grouped by category,
|
||||
* so editors see what they insert.
|
||||
*/
|
||||
class PhotoSelect extends Select
|
||||
{
|
||||
protected function setUp(): void
|
||||
{
|
||||
parent::setUp();
|
||||
|
||||
$this
|
||||
->options(fn (): array => self::photoOptions())
|
||||
->allowHtml()
|
||||
->searchable()
|
||||
->native(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, string>>
|
||||
*/
|
||||
public static function photoOptions(): array
|
||||
{
|
||||
return Photo::query()->with('media')->orderBy('category')->orderBy('sort_order')->get()
|
||||
->groupBy(fn (Photo $photo): string => $photo->category->getLabel())
|
||||
->map(fn ($photos): array => $photos->mapWithKeys(fn (Photo $photo): array => [$photo->id => self::optionLabel($photo)])->all())
|
||||
->all();
|
||||
}
|
||||
|
||||
public static function optionLabel(Photo $photo): string
|
||||
{
|
||||
$thumbnail = $photo->url('sm');
|
||||
$image = $thumbnail !== ''
|
||||
? '<img src="'.e($thumbnail).'" alt="" loading="lazy" style="width:4.5rem;height:3rem;object-fit:cover;border-radius:.25rem;flex-shrink:0">'
|
||||
: '<span style="width:4.5rem;height:3rem;border-radius:.25rem;background:#e5e7eb;flex-shrink:0"></span>';
|
||||
$hidden = $photo->is_published ? '' : ' <em style="opacity:.6">(ausgeblendet)</em>';
|
||||
|
||||
return '<span style="display:flex;align-items:center;gap:.75rem">'.$image.'<span>'.e($photo->alt_text).$hidden.'</span></span>';
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,8 @@
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Models\Photo;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Support\Content;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\Action;
|
||||
@@ -29,6 +30,8 @@
|
||||
*/
|
||||
class EditContent extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPencilSquare;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Webseite';
|
||||
@@ -120,10 +123,8 @@ private function field(string $key, array $field): TextInput|Textarea|RichEditor
|
||||
'richtext' => RichEditor::make($name)
|
||||
->label($field['label'])
|
||||
->toolbarButtons([['bold', 'italic', 'link'], ['h2', 'h3'], ['bulletList', 'orderedList'], ['undo', 'redo']]),
|
||||
'photo' => Select::make($name)
|
||||
'photo' => PhotoSelect::make($name)
|
||||
->label($field['label'])
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->searchable()
|
||||
->placeholder('Kein Bild gewählt')
|
||||
->helperText('Bilder verwalten Sie unter „Webseite › Bilder“.'),
|
||||
default => TextInput::make($name)->label($field['label'])->maxLength(255),
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Pages;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\RelationManagers\ExtrasRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SeasonsRelationManager;
|
||||
use App\Filament\Resources\Properties\RelationManagers\SpecialOffersRelationManager;
|
||||
use App\Models\Property;
|
||||
use BackedEnum;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Pages\Page;
|
||||
use Filament\Schemas\Components\Livewire;
|
||||
use Filament\Schemas\Components\Tabs;
|
||||
use Filament\Schemas\Components\Tabs\Tab;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Livewire\Attributes\Url;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* The yearly price work in one place, without the other apartment settings: seasons & prices,
|
||||
* special offers & promo codes, extras. Reuses the relation managers of the apartment.
|
||||
*/
|
||||
class PricesAndOffers extends Page
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCurrencyEuro;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $navigationLabel = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $title = 'Preise & Angebote';
|
||||
|
||||
protected static ?string $slug = 'preise-und-angebote';
|
||||
|
||||
protected static ?int $navigationSort = 3;
|
||||
|
||||
#[Url(as: 'wohnung')]
|
||||
public ?int $propertyId = null;
|
||||
|
||||
public static function canAccess(): bool
|
||||
{
|
||||
return (bool) auth()->user()?->hasRole(UserRole::Admin, UserRole::Rentals);
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id');
|
||||
}
|
||||
|
||||
public function content(Schema $schema): Schema
|
||||
{
|
||||
$property = Property::find($this->propertyId);
|
||||
if ($property === null) {
|
||||
return $schema->components([Text::make('Es ist noch keine Wohnung angelegt (Expertenansicht › Wohnungen).')]);
|
||||
}
|
||||
|
||||
$context = ['ownerRecord' => $property, 'pageClass' => EditProperty::class];
|
||||
|
||||
return $schema->components([
|
||||
Select::make('propertyId')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->live()
|
||||
->afterStateUpdated(fn () => $this->redirect(static::getUrl(['wohnung' => $this->propertyId])))
|
||||
->visible(fn (): bool => Property::query()->count() > 1),
|
||||
Tabs::make('prices')
|
||||
->persistTabInQueryString()
|
||||
->tabs([
|
||||
Tab::make('Saisons & Preise')->icon(Heroicon::OutlinedCalendar)->schema([
|
||||
Livewire::make(SeasonsRelationManager::class, $context)->key("seasons-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Sonderangebote & Rabattcodes')->icon(Heroicon::OutlinedSparkles)->schema([
|
||||
Livewire::make(SpecialOffersRelationManager::class, $context)->key("offers-{$property->id}"),
|
||||
]),
|
||||
Tab::make('Extras')->icon(Heroicon::OutlinedGift)->schema([
|
||||
Livewire::make(ExtrasRelationManager::class, $context)->key("extras-{$property->id}"),
|
||||
]),
|
||||
]),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Amenities;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Amenities\Pages\CreateAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\EditAmenity;
|
||||
use App\Filament\Resources\Amenities\Pages\ListAmenities;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class AmenityResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Amenity::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedListBullet;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Appearances;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Appearances\Pages\CreateAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\EditAppearance;
|
||||
use App\Filament\Resources\Appearances\Pages\ListAppearances;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class AppearanceResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Appearance::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedSwatch;
|
||||
|
||||
@@ -2,17 +2,23 @@
|
||||
|
||||
namespace App\Filament\Resources\Appearances\Schemas;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Appearance;
|
||||
use App\Models\Photo;
|
||||
use App\Models\Page;
|
||||
use App\Models\Site;
|
||||
use App\Models\SpecialOffer;
|
||||
use App\Themes\SectionRegistry;
|
||||
use App\Themes\Sections\Section as SectionBlock;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Closure;
|
||||
use Filament\Forms\Components\ColorPicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Component;
|
||||
use Filament\Schemas\Components\Fieldset;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
|
||||
@@ -39,19 +45,18 @@ public static function configure(Schema $schema): Schema
|
||||
Toggle::make('is_default')->label('Standard (wenn kein Zeitraum passt)')->inline(false),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true)->inline(false),
|
||||
]),
|
||||
Section::make('Bild & Angebot')
|
||||
->columns(2)
|
||||
Section::make('Titelbild')
|
||||
->description('Gilt für alle Titelbereiche und als Vorschaubild beim Teilen in sozialen Medien – einzelne Bausteine können unten ein eigenes Bild bekommen. Sonderangebote werden unabhängig vom Erscheinungsbild beworben (Wohnung › Sonderangebote).')
|
||||
->schema([
|
||||
Select::make('hero_photo_id')
|
||||
PhotoSelect::make('hero_photo_id')
|
||||
->label('Titelbild')
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->searchable()
|
||||
->placeholder('Bild der Seite verwenden'),
|
||||
Select::make('featured_offer_id')
|
||||
->label('Hervorgehobenes Sonderangebot')
|
||||
->options(fn (): array => SpecialOffer::query()->where('is_active', true)->pluck('name', 'id')->all())
|
||||
->placeholder('keins'),
|
||||
]),
|
||||
Section::make('Bilder je Baustein')
|
||||
->description('Für jeden Baustein mit Bildern ein eigenes Saisonbild wählen. Leer = Bild aus der Seite. Neue Bilder laden Sie unter Webseite › Fotos hoch.')
|
||||
->collapsible()
|
||||
->columnSpanFull()
|
||||
->schema(fn (Get $get): array => self::sectionPhotoFields($get('site_id'))),
|
||||
Section::make('Texte')
|
||||
->description('Leer lassen = Text der Seite bzw. kein Banner.')
|
||||
->columns(2)
|
||||
@@ -69,14 +74,68 @@ public static function configure(Schema $schema): Schema
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* One group per page and one field set per placed section that has photo slots
|
||||
* (see Section::photoSlots); stored in section_photos[<section id>][<slot>].
|
||||
*
|
||||
* @return list<Component>
|
||||
*/
|
||||
public static function sectionPhotoFields(int|string|null $siteId): array
|
||||
{
|
||||
$registry = app(SectionRegistry::class);
|
||||
$pages = Page::query()->where('site_id', $siteId)->orderBy('sort_order')->get();
|
||||
|
||||
$groups = [];
|
||||
foreach ($pages as $page) {
|
||||
$fieldsets = [];
|
||||
foreach ($page->sections ?? [] as $stored) {
|
||||
$class = $registry->all()[$stored['type'] ?? ''] ?? null;
|
||||
$sectionId = $stored['data']['id'] ?? null;
|
||||
if ($class === null || blank($sectionId) || $class::photoSlots() === []) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$fields = [];
|
||||
foreach ($class::photoSlots() as $slot => $definition) {
|
||||
$field = PhotoSelect::make("section_photos.{$sectionId}.{$slot}")
|
||||
->label($definition['label'])
|
||||
->placeholder('Standard (Bild aus der Seite)')
|
||||
->multiple($definition['type'] !== SectionBlock::SLOT_SINGLE);
|
||||
if (isset($definition['max'])) {
|
||||
$field->maxItems($definition['max']);
|
||||
}
|
||||
$fields[] = $field;
|
||||
|
||||
if ($definition['type'] === SectionBlock::SLOT_COLLECTION) {
|
||||
$fields[] = Radio::make("section_photos.{$sectionId}.mode")
|
||||
->label('Saisonbilder')
|
||||
->options(['replace' => 'ersetzen die Bilder des Bausteins', 'prepend' => 'kommen zuerst, danach die übrigen'])
|
||||
->default('replace')
|
||||
->inline();
|
||||
}
|
||||
}
|
||||
|
||||
$fieldsets[] = Fieldset::make(collect([$class::label(), $class::summary($stored['data'] ?? [])])->filter()->implode(' · '))
|
||||
->columns(1)
|
||||
->schema($fields);
|
||||
}
|
||||
|
||||
if ($fieldsets !== []) {
|
||||
$groups[] = Section::make($page->title)->compact()->collapsible()->schema($fieldsets);
|
||||
}
|
||||
}
|
||||
|
||||
return $groups ?: [Text::make('Auf den Seiten gibt es noch keine Bausteine mit Bildern.')];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<ColorPicker>
|
||||
*/
|
||||
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens'): array
|
||||
public static function tokenFields(int|string|null $siteId, string $statePath = 'tokens', ?string $themeKey = null): array
|
||||
{
|
||||
$theme = Site::find($siteId)?->theme ?? config('themes.base');
|
||||
$theme = $themeKey ?: (Site::find($siteId)?->theme ?? config('themes.base'));
|
||||
|
||||
return collect(app(ThemeRegistry::class)->get($theme)->tokens)
|
||||
return collect(app(ThemeRegistry::class)->tokens($theme))
|
||||
->map(fn (array $token, string $key): ColorPicker => ColorPicker::make("{$statePath}.{$key}")->label($token['label'])->placeholder($token['default']))
|
||||
->values()
|
||||
->all();
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Property;
|
||||
use BackedEnum;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Resources\Resource;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Filters\Filter;
|
||||
use Filament\Tables\Table;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use UnitEnum;
|
||||
|
||||
/**
|
||||
* All blocked periods of all apartments in one place (own use, renovation, portal occupations).
|
||||
* Portal and e-mail blocks are maintained by the sync and can only be viewed here.
|
||||
*/
|
||||
class BlockedPeriodResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = BlockedPeriod::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedNoSymbol;
|
||||
|
||||
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
|
||||
|
||||
protected static ?string $modelLabel = 'Sperrzeit';
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sperrzeiten';
|
||||
|
||||
protected static ?int $navigationSort = 2;
|
||||
|
||||
public static function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->columns(2)
|
||||
->components([
|
||||
Select::make('property_id')
|
||||
->label('Wohnung')
|
||||
->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all())
|
||||
->default(fn (): ?int => Property::query()->where('is_active', true)->value('id'))
|
||||
->required()
|
||||
->columnSpanFull()
|
||||
->hidden(fn (): bool => Property::query()->count() <= 1)
|
||||
->dehydratedWhenHidden(),
|
||||
DatePicker::make('starts_on')->label('Von (erste gesperrte Nacht)')->required(),
|
||||
DatePicker::make('ends_on')->label('Bis (erster freier Tag)')->after('starts_on')->required(),
|
||||
TextInput::make('reason')
|
||||
->label('Grund')
|
||||
->placeholder('z. B. Eigennutzung, Renovierung')
|
||||
->maxLength(255)
|
||||
->columnSpanFull(),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->description('Zeiträume, in denen die Wohnung nicht vermietet wird. Belegungen aus Portalen erscheinen hier automatisch.')
|
||||
->defaultSort('starts_on')
|
||||
->columns([
|
||||
TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y')->sortable(),
|
||||
TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'),
|
||||
TextColumn::make('reason')->label('Grund')->placeholder('–'),
|
||||
TextColumn::make('property.name')->label('Wohnung')->visible(fn (): bool => Property::query()->count() > 1),
|
||||
TextColumn::make('source')
|
||||
->label('Quelle')
|
||||
->formatStateUsing(fn (string $state): string => match ($state) {
|
||||
'manual' => 'von Hand',
|
||||
'channel' => 'Portal-Kalender',
|
||||
'email' => 'Portal-E-Mail',
|
||||
default => $state,
|
||||
})
|
||||
->badge(),
|
||||
])
|
||||
->filters([
|
||||
Filter::make('upcoming')
|
||||
->label('Nur kommende')
|
||||
->default()
|
||||
->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'),
|
||||
]);
|
||||
}
|
||||
|
||||
public static function getPages(): array
|
||||
{
|
||||
return [
|
||||
'index' => ManageBlockedPeriods::route('/'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Filament\Resources\BlockedPeriods\Pages;
|
||||
|
||||
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Resources\Pages\ManageRecords;
|
||||
|
||||
class ManageBlockedPeriods extends ManageRecords
|
||||
{
|
||||
protected static string $resource = BlockedPeriodResource::class;
|
||||
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
CreateAction::make()->label('Zeitraum sperren')->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Bookings;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Bookings\Pages\CreateBooking;
|
||||
use App\Filament\Resources\Bookings\Pages\ListBookings;
|
||||
use App\Filament\Resources\Bookings\Pages\ViewBooking;
|
||||
@@ -20,6 +21,8 @@
|
||||
|
||||
class BookingResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Booking::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
|
||||
|
||||
@@ -4,19 +4,31 @@
|
||||
|
||||
use App\Actions\ConfirmBooking;
|
||||
use App\Actions\DeclineBooking;
|
||||
use App\Actions\SendOffer;
|
||||
use App\Documents\RentalContract;
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Exceptions\ReservationException;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Models\Booking;
|
||||
use App\Pricing\PriceCalculator;
|
||||
use App\Pricing\QuoteException;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\ActionGroup;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\Pages\ViewRecord;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Text;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* @property Booking $record
|
||||
@@ -33,14 +45,92 @@ public function getTitle(): string
|
||||
protected function getHeaderActions(): array
|
||||
{
|
||||
return [
|
||||
Action::make('confirm')
|
||||
->label('Bestätigen')
|
||||
->icon(Heroicon::OutlinedCheckCircle)
|
||||
Action::make('sendOffer')
|
||||
->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden')
|
||||
->icon(Heroicon::OutlinedPaperAirplane)
|
||||
->color('success')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->modalHeading('Angebot an den Gast senden')
|
||||
->modalDescription('Der Gast erhält das Angebot mit Vertragsentwurf per E-Mail und kann es über einen Link annehmen oder ablehnen. Erst mit seiner Annahme ist die Buchung verbindlich.')
|
||||
->modalSubmitActionLabel('Angebot senden')
|
||||
->modalWidth('3xl')
|
||||
->fillForm(fn (): array => [
|
||||
'arrival' => $this->record->arrival->toDateString(),
|
||||
'departure' => $this->record->departure->toDateString(),
|
||||
'guests' => $this->record->guests,
|
||||
'promo_code' => $this->record->promo_code,
|
||||
'price_adjustment' => $this->record->price_adjustment !== null ? number_format($this->record->price_adjustment / 100, 2, '.', '') : null,
|
||||
'price_adjustment_label' => $this->record->price_adjustment_label,
|
||||
'valid_until' => now()->addHours($this->record->property->hold_hours)->format('Y-m-d H:i'),
|
||||
'offer_message' => $this->record->offer_message,
|
||||
'guest' => $this->record->guest->only(['first_name', 'last_name', 'street', 'postal_code', 'city', 'phone']),
|
||||
])
|
||||
->schema([
|
||||
Section::make('Termin')->columns(3)->schema([
|
||||
DatePicker::make('arrival')->label('Anreise')->required()->live(onBlur: true),
|
||||
DatePicker::make('departure')->label('Abreise')->after('arrival')->required()->live(onBlur: true),
|
||||
TextInput::make('guests')->label('Personen')->integer()->minValue(1)->maxValue(fn (): int => $this->record->property->max_guests)->required()->live(onBlur: true),
|
||||
]),
|
||||
Section::make('Preis')->columns(3)->schema([
|
||||
TextInput::make('promo_code')->label('Rabattcode')->helperText('Sonderkondition aus den Angeboten')->maxLength(50)->live(onBlur: true),
|
||||
TextInput::make('price_adjustment')
|
||||
->label('Preisanpassung')
|
||||
->helperText('Minus = Nachlass, z. B. -50')
|
||||
->numeric()
|
||||
->step(0.01)
|
||||
->suffix('€')
|
||||
->live(onBlur: true),
|
||||
TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80),
|
||||
Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Gültigkeit & Nachricht')->columns(2)->schema([
|
||||
DateTimePicker::make('valid_until')
|
||||
->label('Angebot gültig bis')
|
||||
->helperText(fn (): string => 'Standard: '.$this->record->property->hold_hours.' Stunden (Einstellung der Wohnung). Bis dahin bleibt der Zeitraum reserviert.')
|
||||
->seconds(false)
|
||||
->after('now')
|
||||
->required(),
|
||||
Textarea::make('offer_message')->label('Persönliche Nachricht an den Gast (optional)')->rows(3),
|
||||
]),
|
||||
Section::make('Gast – so erscheint er im Mietvertrag')->columns(2)->collapsed()->schema([
|
||||
TextInput::make('guest.first_name')->label('Vorname')->required()->maxLength(100),
|
||||
TextInput::make('guest.last_name')->label('Nachname')->required()->maxLength(100),
|
||||
TextInput::make('guest.street')->label('Straße und Hausnummer')->maxLength(150),
|
||||
TextInput::make('guest.postal_code')->label('PLZ')->maxLength(20),
|
||||
TextInput::make('guest.city')->label('Ort')->maxLength(100),
|
||||
TextInput::make('guest.phone')->label('Telefon')->maxLength(50),
|
||||
]),
|
||||
])
|
||||
->action(fn (array $data, SendOffer $send) => $this->runWorkflow(
|
||||
fn () => $send->handle($this->record, $this->offerChanges($data)),
|
||||
'Angebot gesendet',
|
||||
)),
|
||||
Action::make('offerLink')
|
||||
->label('Angebotslink')
|
||||
->icon(Heroicon::OutlinedLink)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->hold_expires_at?->isFuture())
|
||||
->modalHeading('Link zum Angebot')
|
||||
->modalDescription('Derselbe Link wie in der Angebots-E-Mail – z. B. zum Weitergeben per Messenger. Gültig bis zum Ende der Angebotsfrist.')
|
||||
->schema([
|
||||
TextInput::make('url')->label('Link')->default(fn (SendOffer $send): string => $send->offerUrl($this->record))->readOnly()->copyable(),
|
||||
])
|
||||
->modalSubmitAction(false)
|
||||
->modalCancelActionLabel('Schließen'),
|
||||
Action::make('offerPdf')
|
||||
->label('Angebot (PDF)')
|
||||
->icon(Heroicon::OutlinedDocumentText)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::OfferSent && $this->record->offer_path !== null)
|
||||
->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record, draft: true) ?? abort(404), "Angebot-{$this->record->reference}.pdf")),
|
||||
Action::make('confirm')
|
||||
->label('Direkt bestätigen')
|
||||
->icon(Heroicon::OutlinedCheckCircle)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Buchung bestätigen')
|
||||
->modalDescription('Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
|
||||
->modalHeading('Buchung direkt bestätigen')
|
||||
->modalDescription('Ohne Angebot und Annahme durch den Gast – nur wenn die Buchung bereits anders verbindlich vereinbart wurde (z. B. telefonisch). Die Buchung wird verbindlich und der Zeitraum dauerhaft belegt.')
|
||||
->schema([
|
||||
Toggle::make('notify')->label('Buchungsbestätigung an den Gast senden')->default(true),
|
||||
])
|
||||
@@ -52,7 +142,7 @@ protected function getHeaderActions(): array
|
||||
->label('Ablehnen')
|
||||
->icon(Heroicon::OutlinedXCircle)
|
||||
->color('danger')
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::Expired], true))
|
||||
->visible(fn (): bool => in_array($this->record->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true))
|
||||
->requiresConfirmation()
|
||||
->modalHeading('Anfrage ablehnen')
|
||||
->schema([
|
||||
@@ -66,7 +156,7 @@ protected function getHeaderActions(): array
|
||||
->label('Vormerkung verlängern')
|
||||
->icon(Heroicon::OutlinedClock)
|
||||
->color('gray')
|
||||
->visible(fn (): bool => $this->record->status === BookingStatus::Reserved)
|
||||
->visible(fn (): bool => in_array($this->record->status, BookingStatus::holding(), true))
|
||||
->schema([
|
||||
TextInput::make('hours')->label('Um')->integer()->minValue(1)->default(24)->suffix('Stunden')->required(),
|
||||
])
|
||||
@@ -117,11 +207,45 @@ protected function getHeaderActions(): array
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Form data of the offer modal as SendOffer changes (euro input → cents).
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return array<string, mixed>
|
||||
*/
|
||||
private function offerChanges(array $data): array
|
||||
{
|
||||
return [
|
||||
...$data,
|
||||
'price_adjustment' => filled($data['price_adjustment'] ?? null) ? (int) round((float) $data['price_adjustment'] * 100) : null,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Live price shown in the offer modal, calculated exactly like the offer itself.
|
||||
*/
|
||||
private function offerPricePreview(Get $get): string
|
||||
{
|
||||
try {
|
||||
$stay = new StayRequest(CarbonImmutable::parse($get('arrival')), CarbonImmutable::parse($get('departure')), (int) $get('guests'), $this->record->extras ?? [], filled($get('promo_code')) ? (string) $get('promo_code') : null);
|
||||
$quote = app(PriceCalculator::class)->calculate($this->record->property, $stay);
|
||||
} catch (QuoteException $exception) {
|
||||
return 'Preis: '.$exception->getMessage();
|
||||
} catch (Throwable) {
|
||||
return 'Preis: bitte Termin und Personen angeben.';
|
||||
}
|
||||
|
||||
$adjustment = filled($get('price_adjustment')) ? max((int) round((float) $get('price_adjustment') * 100), -$quote->rent()) : 0;
|
||||
$promo = filled($get('promo_code')) ? ($quote->promoCodeApplied ? ' · Rabattcode angewendet' : ' · Rabattcode gilt hier nicht') : '';
|
||||
|
||||
return 'Gesamtpreis im Angebot: '.Money::format($quote->total() + $adjustment).' (bisher '.Money::format($this->record->total).')'.$promo;
|
||||
}
|
||||
|
||||
private function runWorkflow(callable $workflow, string $successTitle): void
|
||||
{
|
||||
try {
|
||||
$workflow();
|
||||
} catch (ReservationException $exception) {
|
||||
} catch (ReservationException|QuoteException $exception) {
|
||||
Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send();
|
||||
|
||||
return;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\ChannelTasks;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks;
|
||||
use App\Filament\Resources\ChannelTasks\Tables\ChannelTasksTable;
|
||||
use App\Models\ChannelTask;
|
||||
@@ -13,6 +14,8 @@
|
||||
|
||||
class ChannelTaskResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = ChannelTask::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedClipboardDocumentCheck;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Faqs;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Faqs\Pages\CreateFaq;
|
||||
use App\Filament\Resources\Faqs\Pages\EditFaq;
|
||||
use App\Filament\Resources\Faqs\Pages\ListFaqs;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class FaqResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Faq::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedQuestionMarkCircle;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Guests;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Guests\Pages\CreateGuest;
|
||||
use App\Filament\Resources\Guests\Pages\EditGuest;
|
||||
use App\Filament\Resources\Guests\Pages\ListGuests;
|
||||
@@ -18,6 +19,8 @@
|
||||
|
||||
class GuestResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Guest::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUsers;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Notices;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Notices\Pages\CreateNotice;
|
||||
use App\Filament\Resources\Notices\Pages\EditNotice;
|
||||
use App\Filament\Resources\Notices\Pages\ListNotices;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class NoticeResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Notice::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedMegaphone;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Pages;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Pages\Pages\CreatePage;
|
||||
use App\Filament\Resources\Pages\Pages\EditPage;
|
||||
use App\Filament\Resources\Pages\Pages\ListPages;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class PageResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Page::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedDocumentDuplicate;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Photos;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Photos\Pages\CreatePhoto;
|
||||
use App\Filament\Resources\Photos\Pages\EditPhoto;
|
||||
use App\Filament\Resources\Photos\Pages\ListPhotos;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class PhotoResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Photo::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPhoto;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\PortalEmails;
|
||||
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\PortalEmails\Pages\ListPortalEmails;
|
||||
use App\Filament\Resources\PortalEmails\Tables\PortalEmailsTable;
|
||||
use App\Models\PortalEmail;
|
||||
@@ -14,6 +15,8 @@
|
||||
|
||||
class PortalEmailResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = PortalEmail::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedEnvelopeOpen;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Properties;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Properties\Pages\CreateProperty;
|
||||
use App\Filament\Resources\Properties\Pages\EditProperty;
|
||||
use App\Filament\Resources\Properties\Pages\ListProperties;
|
||||
@@ -22,6 +23,8 @@
|
||||
|
||||
class PropertyResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Property::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedHomeModern;
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
@@ -35,6 +36,8 @@
|
||||
|
||||
class SeasonsRelationManager extends RelationManager
|
||||
{
|
||||
public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag'];
|
||||
|
||||
protected static string $relationship = 'seasons';
|
||||
|
||||
protected static ?string $title = 'Saisons & Preise';
|
||||
@@ -111,6 +114,7 @@ public function table(Table $table): Table
|
||||
->headerActions([
|
||||
CreateAction::make(),
|
||||
$this->copyToNextYearAction(),
|
||||
$this->minimumStayRulesAction(),
|
||||
$this->priceCalculatorAction(),
|
||||
])
|
||||
->recordActions([
|
||||
@@ -179,22 +183,52 @@ private function seasonYears(): array
|
||||
return $years->combine($years)->all();
|
||||
}
|
||||
|
||||
/**
|
||||
* The relaxations of the seasons' minimum stay, edited where the seasons are maintained.
|
||||
*/
|
||||
private function minimumStayRulesAction(): Action
|
||||
{
|
||||
return Action::make('minimumStayRules')
|
||||
->label('Regeln Mindestaufenthalt')
|
||||
->icon(Heroicon::OutlinedAdjustmentsHorizontal)
|
||||
->color('gray')
|
||||
->modalHeading('Mindestaufenthalt – Ausnahmen')
|
||||
->modalDescription('Jede Saison hat ihre Mindestnächte. Diese Regeln erlauben kürzere Aufenthalte, wenn sie den Kalender nicht zerstückeln. Sonderangebote können den Mindestaufenthalt zusätzlich aufheben.')
|
||||
->fillForm(fn (): array => $this->getOwnerRecord()->only(['changeover_weekday', 'min_stay_fill_gaps', 'min_stay_until_changeover', 'min_stay_absolute']))
|
||||
->schema([
|
||||
Select::make('changeover_weekday')->label('Typischer An- und Abreisetag')->options(self::WEEKDAYS)->placeholder('keiner'),
|
||||
Toggle::make('min_stay_fill_gaps')->label('Kalenderlücken: kürzer erlaubt, wenn die Buchung eine Lücke zwischen zwei Belegungen vollständig füllt'),
|
||||
Toggle::make('min_stay_until_changeover')->label('Kürzer erlaubt, wenn die Buchung am typischen Anreisetag endet (die Woche danach bleibt frei buchbar)'),
|
||||
TextInput::make('min_stay_absolute')->label('Untergrenze für alle Ausnahmen')->integer()->minValue(1)->maxValue(14)->suffix('Nächte')->required(),
|
||||
])
|
||||
->action(function (array $data): void {
|
||||
$this->getOwnerRecord()->update($data);
|
||||
Notification::make()->title('Regeln gespeichert')->success()->send();
|
||||
});
|
||||
}
|
||||
|
||||
private function copyToNextYearAction(): Action
|
||||
{
|
||||
return Action::make('copyToNextYear')
|
||||
->label('In Folgejahr kopieren')
|
||||
->icon(Heroicon::OutlinedDocumentDuplicate)
|
||||
->color('gray')
|
||||
->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit gleichen Kalenderdaten und Preisen ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.')
|
||||
->modalDescription('Alle Saisons, die im gewählten Jahr beginnen, werden mit Preisen und Mindestnächten ins Folgejahr übernommen. Bereits belegte Zeiträume werden übersprungen.')
|
||||
->schema([
|
||||
Select::make('year')
|
||||
->label('Jahr kopieren')
|
||||
->options(fn (): array => $this->seasonYears())
|
||||
->default((string) now()->year)
|
||||
->required(),
|
||||
Select::make('weekday')
|
||||
->label('Saisonbeginn legen auf')
|
||||
->helperText('Jeder Saisonbeginn wird auf den nächstgelegenen Wochentag verschoben (höchstens 3 Tage); aneinandergrenzende Saisons bleiben lückenlos.')
|
||||
->options(self::WEEKDAYS)
|
||||
->placeholder('gleiche Kalenderdaten wie im Vorjahr')
|
||||
->default(fn (): ?int => $this->getOwnerRecord()->changeover_weekday),
|
||||
])
|
||||
->action(function (array $data, CopySeasonsToNextYear $copySeasons): void {
|
||||
$result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year']);
|
||||
$result = $copySeasons->handle($this->getOwnerRecord(), (int) $data['year'], filled($data['weekday'] ?? null) ? (int) $data['weekday'] : null);
|
||||
|
||||
Notification::make()
|
||||
->title("{$result['created']} Saisons nach ".((int) $data['year'] + 1).' kopiert')
|
||||
|
||||
+94
-19
@@ -3,8 +3,8 @@
|
||||
namespace App\Filament\Resources\Properties\RelationManagers;
|
||||
|
||||
use App\Enums\DiscountType;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Models\SpecialOffer;
|
||||
use App\Support\Money;
|
||||
use Filament\Actions\CreateAction;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
@@ -12,12 +12,14 @@
|
||||
use Filament\Forms\Components\CheckboxList;
|
||||
use Filament\Forms\Components\DatePicker;
|
||||
use Filament\Forms\Components\DateTimePicker;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Resources\RelationManagers\RelationManager;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Components\Utilities\Set;
|
||||
use Filament\Schemas\Schema;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
@@ -33,10 +35,48 @@ class SpecialOffersRelationManager extends RelationManager
|
||||
|
||||
protected static ?string $pluralModelLabel = 'Sonderangebote';
|
||||
|
||||
/**
|
||||
* Starting points for typical offers in the create form.
|
||||
*
|
||||
* @var array<string, array{label: string, values: array<string, mixed>}>
|
||||
*/
|
||||
private const PRESETS = [
|
||||
'last_minute' => ['label' => 'Last Minute (−15 %, bis 14 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Last Minute', 'discount_type' => 'percent', 'discount_value' => 15, 'max_days_before_arrival' => 14]],
|
||||
'early_bird' => ['label' => 'Frühbucher (−5 %, ab 180 Tage vor Anreise)', 'values' => ['kind' => 'rule', 'name' => 'Frühbucher', 'discount_type' => 'percent', 'discount_value' => 5, 'min_days_before_arrival' => 180]],
|
||||
'long_stay' => ['label' => 'Längerer Aufenthalt (ab 3 Nächten −10 %)', 'values' => ['kind' => 'rule', 'name' => 'Ab 3 Nächten', 'discount_type' => 'percent', 'discount_value' => 10, 'min_nights' => 3]],
|
||||
'week' => ['label' => '7 = 6 (eine Nacht gratis ab 7 Nächten)', 'values' => ['kind' => 'rule', 'name' => '7 Nächte bleiben, 6 bezahlen', 'discount_type' => 'free_nights', 'discount_value' => 1, 'min_nights' => 7]],
|
||||
'weekend' => ['label' => 'Special Weekend (Anreise Freitag, 2 Nächte)', 'values' => ['kind' => 'rule', 'name' => 'Special Weekend', 'discount_type' => 'percent', 'discount_value' => 10, 'arrival_weekdays' => [5], 'min_nights' => 2, 'max_nights' => 2]],
|
||||
'gap' => ['label' => 'Lückenfüller (Lücken bis 4 Nächte −20 %)', 'values' => ['kind' => 'gap_filler', 'name' => 'Kurzfristige Lücke', 'discount_type' => 'percent', 'discount_value' => 20, 'max_gap_nights' => 4, 'waives_min_stay' => true]],
|
||||
'fixed_week' => ['label' => 'Fester Termin (eine Woche zum Pauschalpreis)', 'values' => ['kind' => 'fixed_dates', 'name' => 'Ostsee-Woche', 'discount_type' => 'fixed_stay_price']],
|
||||
];
|
||||
|
||||
public function form(Schema $schema): Schema
|
||||
{
|
||||
return $schema
|
||||
->components([
|
||||
Section::make('Art des Angebots')
|
||||
->columns(2)
|
||||
->schema([
|
||||
Select::make('preset')
|
||||
->label('Vorlage (optional)')
|
||||
->helperText('Füllt typische Einstellungen vor – alles bleibt änderbar.')
|
||||
->options(collect(self::PRESETS)->map(fn (array $preset): string => $preset['label'])->all())
|
||||
->dehydrated(false)
|
||||
->live()
|
||||
->afterStateUpdated(function (?string $state, Set $set): void {
|
||||
foreach (self::PRESETS[$state]['values'] ?? [] as $field => $value) {
|
||||
$set($field, $value);
|
||||
}
|
||||
})
|
||||
->visibleOn('create'),
|
||||
Radio::make('kind')
|
||||
->label('Art')
|
||||
->options(OfferKind::class)
|
||||
->default(OfferKind::Rule)
|
||||
->live()
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
]),
|
||||
Section::make('Angebot')
|
||||
->columns(2)
|
||||
->schema([
|
||||
@@ -60,24 +100,54 @@ public function form(Schema $schema): Schema
|
||||
DiscountType::AmountPerStay => 'Rabatt pro Aufenthalt',
|
||||
DiscountType::NightlyRate => 'Sonderpreis pro Nacht',
|
||||
DiscountType::FreeNights => 'Anzahl Gratis-Nächte',
|
||||
DiscountType::FixedStayPrice => 'Pauschalpreis für alle Nächte',
|
||||
})
|
||||
->suffix(fn (Get $get): string => match ($this->discountType($get)) {
|
||||
DiscountType::Percent => '%',
|
||||
DiscountType::FreeNights => 'Nächte',
|
||||
default => '€',
|
||||
})
|
||||
->helperText(fn (Get $get): ?string => $this->discountType($get) === DiscountType::FreeNights ? 'Die günstigsten Nächte des Aufenthalts sind gratis.' : null)
|
||||
->helperText(fn (Get $get): ?string => match ($this->discountType($get)) {
|
||||
DiscountType::FreeNights => 'Die günstigsten Nächte des Aufenthalts sind gratis.',
|
||||
DiscountType::FixedStayPrice => 'Übernachtungen zusammen; Endreinigung und Extras kommen dazu.',
|
||||
default => null,
|
||||
})
|
||||
->numeric()
|
||||
->minValue(0)
|
||||
->required()
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $this->isMoney($record?->discount_type) ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->isMoney($this->discountType($get)) ? (int) round((float) $state * 100) : (int) $state),
|
||||
->formatStateUsing(fn (?int $state, ?SpecialOffer $record): int|string|null => $state !== null && $record?->discount_type?->isMoney() ? number_format($state / 100, 2, '.', '') : $state)
|
||||
->dehydrateStateUsing(fn (string|int|float|null $state, Get $get): int => $this->discountType($get)->isMoney() ? (int) round((float) $state * 100) : (int) $state),
|
||||
Toggle::make('is_active')->label('Aktiv')->default(true),
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_combinable')
|
||||
->label('Mit anderen kombinierbaren Angeboten kombinierbar')
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.')
|
||||
->columnSpanFull(),
|
||||
->helperText('Sonst erhält der Gast automatisch das für ihn beste Einzelangebot.'),
|
||||
Toggle::make('waives_min_stay')
|
||||
->label('Mindestaufenthalt der Saison aufheben')
|
||||
->helperText('Wenn das Angebot gilt, darf der Aufenthalt kürzer sein als die Mindestnächte der Saison (z. B. Special Weekend mit 2 Nächten, kurze Lücke).'),
|
||||
]),
|
||||
Section::make('Bewerbung auf der Webseite')
|
||||
->description('Welche Angebote gerade erscheinen, ergibt sich automatisch: aktiv, ohne Aktionscode, im Buchungszeitraum, feste Termine nur solange frei, Lückenfüller je gefundener Lücke. Mehrere gleichzeitig werden im Baustein „Sonderangebote“ nebeneinander, als Liste oder rollierend gezeigt.')
|
||||
->columns(3)
|
||||
->schema([
|
||||
Toggle::make('is_public')->label('Auf der Webseite bewerben')->default(true),
|
||||
Toggle::make('is_featured')->label('Hervorheben')->helperText('Steht vorne, ist farbig markiert und erscheint im Titelbereich.'),
|
||||
TextInput::make('priority')->label('Priorität')->helperText('Höher = weiter vorne')->integer()->default(0),
|
||||
]),
|
||||
Section::make('Termin')
|
||||
->description('Der Gast muss genau diesen Zeitraum buchen. Beworben wird er nur, solange er frei ist.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates)
|
||||
->schema([
|
||||
DatePicker::make('stay_from')->label('Anreise')->required(),
|
||||
DatePicker::make('stay_until')->label('Abreise')->after('stay_from')->required(),
|
||||
]),
|
||||
Section::make('Kalenderlücken')
|
||||
->description('Freie Zeiträume zwischen zwei Buchungen oder Sperrzeiten. Die Webseite zeigt bis zu drei gefundene Lücken mit Termin und Preis.')
|
||||
->columns(2)
|
||||
->visible(fn (Get $get): bool => $this->kind($get) === OfferKind::GapFiller)
|
||||
->schema([
|
||||
TextInput::make('max_gap_nights')->label('Lücken bis höchstens … Nächte')->integer()->minValue(1)->default(4)->required(),
|
||||
|
||||
]),
|
||||
Section::make('Bedingungen')
|
||||
->description('Leere Felder bedeuten: keine Einschränkung.')
|
||||
@@ -103,15 +173,15 @@ public function form(Schema $schema): Schema
|
||||
->helperText('Frühbucher, z. B. 180')
|
||||
->integer()
|
||||
->minValue(0),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1),
|
||||
TextInput::make('min_nights')->label('Mindestens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
TextInput::make('max_nights')->label('Höchstens Nächte')->integer()->minValue(1)->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
CheckboxList::make('arrival_weekdays')
|
||||
->label('Anreise nur am')
|
||||
->options([1 => 'Mo', 2 => 'Di', 3 => 'Mi', 4 => 'Do', 5 => 'Fr', 6 => 'Sa', 7 => 'So'])
|
||||
->columns(7)
|
||||
->columnSpanFull(),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab'),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am'),
|
||||
DatePicker::make('stay_from')->label('Aufenthalt frühestens ab')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DatePicker::make('stay_until')->label('Abreise spätestens am')->hidden(fn (Get $get): bool => $this->kind($get) === OfferKind::FixedDates),
|
||||
DateTimePicker::make('bookable_from')->label('Buchbar ab')->seconds(false),
|
||||
DateTimePicker::make('bookable_until')->label('Buchbar bis')->seconds(false),
|
||||
]),
|
||||
@@ -122,19 +192,22 @@ public function table(Table $table): Table
|
||||
{
|
||||
return $table
|
||||
->recordTitleAttribute('name')
|
||||
->defaultSort('priority', 'desc')
|
||||
->description('Sonderangebote werden bei jeder Preisberechnung automatisch geprüft und angewendet.')
|
||||
->columns([
|
||||
TextColumn::make('name')
|
||||
->label('Angebot')
|
||||
->description(fn (SpecialOffer $record): ?string => $record->public_description),
|
||||
TextColumn::make('kind')->label('Art')->badge(),
|
||||
TextColumn::make('discount')
|
||||
->label('Vorteil')
|
||||
->state(fn (SpecialOffer $record): string => match ($record->discount_type) {
|
||||
DiscountType::Percent => "−{$record->discount_value} %",
|
||||
DiscountType::AmountPerStay => '−'.Money::format($record->discount_value),
|
||||
DiscountType::NightlyRate => Money::format($record->discount_value).' / Nacht',
|
||||
DiscountType::FreeNights => "{$record->discount_value} Nacht/Nächte gratis",
|
||||
}),
|
||||
->state(fn (SpecialOffer $record): string => $record->advantageLabel()),
|
||||
TextColumn::make('conditions')
|
||||
->label('Bedingungen')
|
||||
->state(fn (SpecialOffer $record): string => implode(' · ', $record->conditionSummary()) ?: '–')
|
||||
->wrap(),
|
||||
IconColumn::make('is_featured')->label('Hervorgehoben')->boolean(),
|
||||
TextColumn::make('priority')->label('Priorität')->sortable(),
|
||||
TextColumn::make('code')->label('Code')->placeholder('automatisch')->badge(),
|
||||
TextColumn::make('season_names')->label('Saisons')->badge()->placeholder('alle'),
|
||||
IconColumn::make('is_combinable')->label('Kombinierbar')->boolean(),
|
||||
@@ -157,8 +230,10 @@ private function discountType(Get $get): DiscountType
|
||||
return $type instanceof DiscountType ? $type : (DiscountType::tryFrom((string) $type) ?? DiscountType::Percent);
|
||||
}
|
||||
|
||||
private function isMoney(?DiscountType $type): bool
|
||||
private function kind(Get $get): OfferKind
|
||||
{
|
||||
return in_array($type, [DiscountType::AmountPerStay, DiscountType::NightlyRate], true);
|
||||
$kind = $get('kind');
|
||||
|
||||
return $kind instanceof OfferKind ? $kind : (OfferKind::tryFrom((string) $kind) ?? OfferKind::Rule);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Filament\Resources\Reviews;
|
||||
|
||||
use App\Enums\ReviewStatus;
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Reviews\Pages\CreateReview;
|
||||
use App\Filament\Resources\Reviews\Pages\EditReview;
|
||||
use App\Filament\Resources\Reviews\Pages\ListReviews;
|
||||
@@ -18,6 +19,8 @@
|
||||
|
||||
class ReviewResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Review::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedStar;
|
||||
|
||||
@@ -5,12 +5,14 @@
|
||||
use App\Filament\Resources\Appearances\Schemas\AppearanceForm;
|
||||
use App\Models\Site;
|
||||
use App\Themes\ThemeRegistry;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
use Filament\Schemas\Components\Section;
|
||||
use Filament\Schemas\Components\Utilities\Get;
|
||||
use Filament\Schemas\Schema;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
|
||||
class SiteForm
|
||||
{
|
||||
@@ -29,14 +31,26 @@ public static function configure(Schema $schema): Schema
|
||||
->helperText('Leer = Standard-Website für alle Adressen ohne eigene Zuordnung.')
|
||||
->unique(ignoreRecord: true)
|
||||
->maxLength(190),
|
||||
Select::make('theme')->label('Theme')->options(fn (): array => app(ThemeRegistry::class)->options())->default(config('themes.base'))->required()->live(),
|
||||
Select::make('theme')
|
||||
->label('Theme')
|
||||
->options(fn (): array => app(ThemeRegistry::class)->options())
|
||||
->default(config('themes.base'))
|
||||
->required()
|
||||
->live()
|
||||
->helperText(fn (Get $get): ?string => filled($get('theme')) ? app(ThemeRegistry::class)->get($get('theme'))->description : null)
|
||||
->hintAction(
|
||||
Action::make('previewTheme')
|
||||
->label('Vorschau')
|
||||
->icon('heroicon-o-eye')
|
||||
->url(fn (Get $get): string => URL::temporarySignedRoute('home', now()->addDay(), ['theme' => $get('theme') ?: config('themes.base')]), shouldOpenInNewTab: true),
|
||||
),
|
||||
Toggle::make('is_default')->label('Standard-Website')->inline(false),
|
||||
]),
|
||||
Section::make('Farben des Themes')
|
||||
->description('Grundfarben dieser Website; saisonale Erscheinungsbilder können einzelne Farben zusätzlich ändern.')
|
||||
->columns(3)
|
||||
->collapsible()
|
||||
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens')),
|
||||
->schema(fn (Get $get, ?Site $record): array => AppearanceForm::tokenFields($record?->id, 'theme_settings.tokens', $get('theme'))),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Sites;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Sites\Pages\CreateSite;
|
||||
use App\Filament\Resources\Sites\Pages\EditSite;
|
||||
use App\Filament\Resources\Sites\Pages\ListSites;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class SiteResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = Site::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedGlobeAlt;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Users\Schemas;
|
||||
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\UserRole;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -26,9 +27,15 @@ public static function configure(Schema $schema): Schema
|
||||
->maxLength(255),
|
||||
Radio::make('role')
|
||||
->label('Rolle')
|
||||
->helperText('Bestimmt, was die Person darf.')
|
||||
->options(UserRole::class)
|
||||
->required()
|
||||
->columnSpanFull(),
|
||||
Radio::make('admin_mode')
|
||||
->label('Ansicht')
|
||||
->helperText('Bestimmt nur, was im Menü erscheint. Leer = Administratoren Expertenansicht, alle anderen einfache Ansicht. Jederzeit umschaltbar über das Benutzermenü oben rechts.')
|
||||
->options(AdminMode::class)
|
||||
->columnSpanFull(),
|
||||
TextInput::make('password')
|
||||
->label(fn (string $operation): string => $operation === 'create' ? 'Passwort' : 'Neues Passwort (leer lassen = unverändert)')
|
||||
->password()
|
||||
|
||||
@@ -2,8 +2,13 @@
|
||||
|
||||
namespace App\Filament\Resources\Users\Tables;
|
||||
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Actions\DeleteAction;
|
||||
use Filament\Actions\EditAction;
|
||||
use Filament\Notifications\Notification;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Tables\Columns\IconColumn;
|
||||
use Filament\Tables\Columns\TextColumn;
|
||||
use Filament\Tables\Table;
|
||||
|
||||
@@ -16,9 +21,23 @@ public static function configure(Table $table): Table
|
||||
TextColumn::make('name')->label('Name')->searchable(),
|
||||
TextColumn::make('email')->label('E-Mail')->searchable(),
|
||||
TextColumn::make('role')->label('Rolle')->badge(),
|
||||
TextColumn::make('mode')->label('Ansicht')->state(fn (User $record): string => $record->adminMode()->getLabel()),
|
||||
IconColumn::make('two_factor')->label('2FA')->state(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))->boolean(),
|
||||
])
|
||||
->recordActions([
|
||||
EditAction::make(),
|
||||
Action::make('resetTwoFactor')
|
||||
->label('2FA zurücksetzen')
|
||||
->icon(Heroicon::OutlinedKey)
|
||||
->color('warning')
|
||||
->requiresConfirmation()
|
||||
->modalDescription('Zum Beispiel bei verlorenem Handy: Die Person richtet die Zwei-Faktor-Anmeldung bei der nächsten Anmeldung neu ein.')
|
||||
->visible(fn (User $record): bool => filled($record->getAppAuthenticationSecret()))
|
||||
->action(function (User $record): void {
|
||||
$record->saveAppAuthenticationSecret(null);
|
||||
$record->saveAppAuthenticationRecoveryCodes(null);
|
||||
Notification::make()->title('2FA zurückgesetzt')->success()->send();
|
||||
}),
|
||||
DeleteAction::make(),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Filament\Resources\Users;
|
||||
|
||||
use App\Filament\Concerns\FollowsAdminMode;
|
||||
use App\Filament\Resources\Users\Pages\CreateUser;
|
||||
use App\Filament\Resources\Users\Pages\EditUser;
|
||||
use App\Filament\Resources\Users\Pages\ListUsers;
|
||||
@@ -17,6 +18,8 @@
|
||||
|
||||
class UserResource extends Resource
|
||||
{
|
||||
use FollowsAdminMode;
|
||||
|
||||
protected static ?string $model = User::class;
|
||||
|
||||
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedUserGroup;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
<?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 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' => URL::temporarySignedRoute('offers.accept', $expires, ['booking' => $booking, 'v' => $version]),
|
||||
'rejectUrl' => URL::temporarySignedRoute('offers.reject', $expires, ['booking' => $booking, 'v' => $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 = URL::temporarySignedRoute('offers.show', now()->addDays(30), ['booking' => $booking, 'v' => $version]);
|
||||
|
||||
try {
|
||||
$action($version);
|
||||
} catch (ReservationException $exception) {
|
||||
return redirect()->to($back)->with('offer.error', $exception->getMessage());
|
||||
}
|
||||
|
||||
return redirect()->to($back)->with('offer.success', $success);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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')] : [];
|
||||
}
|
||||
}
|
||||
@@ -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'))],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,10 +11,11 @@
|
||||
|
||||
/**
|
||||
* A seasonal look of a site (e.g. summer, winter, Christmas, New Year's Eve): colour tokens, hero photo,
|
||||
* texts and banner change – the page structure does not. The period recurs every year ("MM-DD" to "MM-DD",
|
||||
* photos per section, texts and banner change – the page structure does not (sections may be limited to
|
||||
* appearances, see SectionRegistry). Offers are advertised by their own rules (OfferShowcase). The period recurs every year ("MM-DD" to "MM-DD",
|
||||
* inclusive; a period may run over the turn of the year). The default appearance applies when none matches.
|
||||
*/
|
||||
#[Fillable(['site_id', 'name', 'starts_md', 'ends_md', 'priority', 'is_default', 'is_active', 'tokens', 'overrides', 'hero_photo_id', 'featured_offer_id'])]
|
||||
#[Fillable(['site_id', 'name', 'starts_md', 'ends_md', 'priority', 'is_default', 'is_active', 'tokens', 'overrides', 'hero_photo_id', 'section_photos'])]
|
||||
class Appearance extends Model
|
||||
{
|
||||
/** @use HasFactory<AppearanceFactory> */
|
||||
@@ -46,6 +47,7 @@ protected function casts(): array
|
||||
'is_active' => 'boolean',
|
||||
'tokens' => 'array',
|
||||
'overrides' => 'array',
|
||||
'section_photos' => 'array',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -65,14 +67,6 @@ public function heroPhoto(): BelongsTo
|
||||
return $this->belongsTo(Photo::class, 'hero_photo_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<SpecialOffer, $this>
|
||||
*/
|
||||
public function featuredOffer(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(SpecialOffer::class, 'featured_offer_id');
|
||||
}
|
||||
|
||||
public function covers(CarbonInterface $date): bool
|
||||
{
|
||||
if ($this->starts_md === null || $this->ends_md === null) {
|
||||
|
||||
+15
-3
@@ -36,6 +36,8 @@
|
||||
'guests',
|
||||
'extras',
|
||||
'promo_code',
|
||||
'price_adjustment',
|
||||
'price_adjustment_label',
|
||||
'quote',
|
||||
'total',
|
||||
'deposit',
|
||||
@@ -43,9 +45,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',
|
||||
@@ -83,6 +92,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 +121,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 +132,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 +197,6 @@ 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();
|
||||
}
|
||||
}
|
||||
+13
-1
@@ -67,7 +67,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',
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
/**
|
||||
* A page of a site, composed of sections from the catalogue (App\Themes\Sections).
|
||||
@@ -59,4 +60,34 @@ public function label(): string
|
||||
{
|
||||
return $this->menu_label ?: $this->title;
|
||||
}
|
||||
|
||||
protected static function booted(): void
|
||||
{
|
||||
static::saving(function (Page $page): void {
|
||||
$page->sections = self::assignSectionIds($page->sections ?? []);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives every placed section a stable id (data.id) – new and duplicated sections get a fresh one –
|
||||
* so appearances can address sections independently of their order.
|
||||
*
|
||||
* @param list<array{type: string, data?: array<string, mixed>}> $sections
|
||||
* @return list<array{type: string, data: array<string, mixed>}>
|
||||
*/
|
||||
public static function assignSectionIds(array $sections): array
|
||||
{
|
||||
$seen = [];
|
||||
|
||||
return array_values(array_map(function (array $section) use (&$seen): array {
|
||||
$data = $section['data'] ?? [];
|
||||
$id = $data['id'] ?? null;
|
||||
if (! is_string($id) || $id === '' || isset($seen[$id])) {
|
||||
$id = (string) Str::uuid();
|
||||
}
|
||||
$seen[$id] = true;
|
||||
|
||||
return [...$section, 'data' => [...$data, 'id' => $id]];
|
||||
}, $sections));
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,10 @@
|
||||
'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
|
||||
@@ -39,10 +43,25 @@ class Property extends Model
|
||||
*
|
||||
* @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',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
namespace App\Models;
|
||||
|
||||
use App\Enums\DiscountType;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Pricing\StayRequest;
|
||||
use App\Support\Money;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Database\Factories\SpecialOfferFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
@@ -14,16 +16,19 @@
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* A discount rule such as last minute, early bird, long stay, special weekends or a code for regular guests.
|
||||
* Every condition left empty means "no restriction".
|
||||
* A discount rule such as last minute, early bird, long stay, special weekends or a code for regular guests,
|
||||
* a fixed date package or a gap filler (see OfferKind). Every condition left empty means "no restriction".
|
||||
*/
|
||||
#[Fillable([
|
||||
'property_id',
|
||||
'name',
|
||||
'kind',
|
||||
'public_description',
|
||||
'is_active',
|
||||
'is_public',
|
||||
'is_combinable',
|
||||
'priority',
|
||||
'is_featured',
|
||||
'code',
|
||||
'discount_type',
|
||||
'discount_value',
|
||||
@@ -35,6 +40,8 @@
|
||||
'max_days_before_arrival',
|
||||
'min_nights',
|
||||
'max_nights',
|
||||
'max_gap_nights',
|
||||
'waives_min_stay',
|
||||
'arrival_weekdays',
|
||||
'season_names',
|
||||
])]
|
||||
@@ -54,6 +61,9 @@ protected function casts(): array
|
||||
'is_active' => 'boolean',
|
||||
'is_public' => 'boolean',
|
||||
'is_combinable' => 'boolean',
|
||||
'is_featured' => 'boolean',
|
||||
'waives_min_stay' => 'boolean',
|
||||
'kind' => OfferKind::class,
|
||||
'discount_type' => DiscountType::class,
|
||||
'stay_from' => 'immutable_date',
|
||||
'stay_until' => 'immutable_date',
|
||||
@@ -84,13 +94,23 @@ protected function active(Builder $query): Builder
|
||||
|
||||
/**
|
||||
* Whether all conditions are met. Offers with a code only apply when the guest entered that code.
|
||||
* $gapNights is the length of the calendar gap containing the stay (null = not inside a gap); it only
|
||||
* matters for gap fillers.
|
||||
*/
|
||||
public function appliesTo(StayRequest $stay, string $arrivalSeasonName, CarbonImmutable $bookedAt): bool
|
||||
public function appliesTo(StayRequest $stay, string $arrivalSeasonName, CarbonImmutable $bookedAt, ?int $gapNights = null): bool
|
||||
{
|
||||
$nights = $stay->nights();
|
||||
$daysBeforeArrival = (int) $bookedAt->startOfDay()->diffInDays($stay->arrival, false);
|
||||
|
||||
$kindMatches = match ($this->kind ?? OfferKind::Rule) {
|
||||
OfferKind::Rule => true,
|
||||
OfferKind::FixedDates => $this->stay_from !== null && $this->stay_until !== null
|
||||
&& $stay->arrival->isSameDay($this->stay_from) && $stay->departure->isSameDay($this->stay_until),
|
||||
OfferKind::GapFiller => $gapNights !== null && ($this->max_gap_nights === null || $gapNights <= $this->max_gap_nights),
|
||||
};
|
||||
|
||||
return $this->is_active
|
||||
&& $kindMatches
|
||||
&& ($this->code === null || strcasecmp($this->code, (string) $stay->promoCode) === 0)
|
||||
&& ($this->stay_from === null || $stay->arrival->greaterThanOrEqualTo($this->stay_from))
|
||||
&& ($this->stay_until === null || $stay->departure->lessThanOrEqualTo($this->stay_until))
|
||||
@@ -118,11 +138,55 @@ public function discountFor(array $nightlyRates): int
|
||||
DiscountType::AmountPerStay => $this->discount_value,
|
||||
DiscountType::NightlyRate => array_sum(array_map(fn (int $rate): int => max(0, $rate - $this->discount_value), $nightlyRates)),
|
||||
DiscountType::FreeNights => array_sum(array_slice($this->sortedAscending($nightlyRates), 0, $this->discount_value)),
|
||||
DiscountType::FixedStayPrice => max(0, $accommodation - $this->discount_value),
|
||||
};
|
||||
|
||||
return min($discount, $accommodation);
|
||||
}
|
||||
|
||||
/**
|
||||
* Short label of the advantage, e.g. "−10 %", "59,00 € / Nacht" or "Pauschal 560,00 €".
|
||||
*/
|
||||
public function advantageLabel(): string
|
||||
{
|
||||
return match ($this->discount_type) {
|
||||
DiscountType::Percent => "−{$this->discount_value} %",
|
||||
DiscountType::AmountPerStay => '−'.Money::format($this->discount_value),
|
||||
DiscountType::NightlyRate => Money::format($this->discount_value).' / Nacht',
|
||||
DiscountType::FreeNights => $this->discount_value === 1 ? '1 Nacht gratis' : "{$this->discount_value} Nächte gratis",
|
||||
DiscountType::FixedStayPrice => 'Pauschal '.Money::format($this->discount_value),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The conditions in plain German for guests, e.g. ["ab 3 Nächten", "Anreise freitags", "bis 14 Tage vor Anreise"].
|
||||
*
|
||||
* @return list<string>
|
||||
*/
|
||||
public function conditionSummary(): array
|
||||
{
|
||||
$weekdays = [1 => 'montags', 2 => 'dienstags', 3 => 'mittwochs', 4 => 'donnerstags', 5 => 'freitags', 6 => 'samstags', 7 => 'sonntags'];
|
||||
|
||||
return array_values(array_filter([
|
||||
match (true) {
|
||||
$this->kind === OfferKind::FixedDates => null,
|
||||
$this->min_nights !== null && $this->max_nights !== null && $this->min_nights === $this->max_nights => "genau {$this->min_nights} Nächte",
|
||||
$this->min_nights !== null && $this->max_nights !== null => "{$this->min_nights} bis {$this->max_nights} Nächte",
|
||||
$this->min_nights !== null => "ab {$this->min_nights} Nächten",
|
||||
$this->max_nights !== null => "bis {$this->max_nights} Nächte",
|
||||
default => null,
|
||||
},
|
||||
empty($this->arrival_weekdays) ? null : 'Anreise '.collect($this->arrival_weekdays)->map(fn ($day): string => $weekdays[(int) $day] ?? '')->implode(' oder '),
|
||||
$this->max_days_before_arrival !== null ? "Buchung bis {$this->max_days_before_arrival} Tage vor Anreise" : null,
|
||||
$this->min_days_before_arrival !== null ? "Buchung mindestens {$this->min_days_before_arrival} Tage vor Anreise" : null,
|
||||
empty($this->season_names) ? null : 'Anreise in: '.implode(', ', $this->season_names),
|
||||
$this->kind !== OfferKind::FixedDates && ($this->stay_from || $this->stay_until)
|
||||
? 'Reisezeitraum '.($this->stay_from?->format('d.m.Y') ?? 'ab sofort').' – '.($this->stay_until?->format('d.m.Y') ?? 'offen')
|
||||
: null,
|
||||
$this->bookable_until !== null ? 'buchbar bis '.$this->bookable_until->format('d.m.Y') : null,
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<int> $rates
|
||||
* @return list<int>
|
||||
|
||||
+11
-1
@@ -3,6 +3,7 @@
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use App\Enums\AdminMode;
|
||||
use App\Enums\UserRole;
|
||||
use Database\Factories\UserFactory;
|
||||
use Filament\Auth\MultiFactor\App\Concerns\InteractsWithAppAuthentication;
|
||||
@@ -17,7 +18,7 @@
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
|
||||
#[Fillable(['name', 'email', 'role', 'password'])]
|
||||
#[Fillable(['name', 'email', 'role', 'admin_mode', 'password'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable implements FilamentUser, HasAppAuthentication, HasAppAuthenticationRecovery
|
||||
{
|
||||
@@ -32,6 +33,14 @@ public function canAccessPanel(Panel $panel): bool
|
||||
return $this->role !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The admin menu this user sees; without an explicit choice administrators get the expert mode.
|
||||
*/
|
||||
public function adminMode(): AdminMode
|
||||
{
|
||||
return $this->admin_mode ?? ($this->hasRole(UserRole::Admin) ? AdminMode::Expert : AdminMode::Simple);
|
||||
}
|
||||
|
||||
public function hasRole(UserRole ...$roles): bool
|
||||
{
|
||||
return in_array($this->role, $roles, true);
|
||||
@@ -48,6 +57,7 @@ protected function casts(): array
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'role' => UserRole::class,
|
||||
'admin_mode' => AdminMode::class,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
<?php
|
||||
|
||||
namespace App\Policies;
|
||||
|
||||
use App\Enums\UserRole;
|
||||
|
||||
class BlockedPeriodPolicy extends RolePolicy
|
||||
{
|
||||
protected function roles(): array
|
||||
{
|
||||
return [UserRole::Rentals];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing;
|
||||
|
||||
use App\Models\SpecialOffer;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
/**
|
||||
* An offer as the website shows it: for fixed dates and gap fillers with concrete dates and an example price.
|
||||
*/
|
||||
final readonly class AdvertisedOffer
|
||||
{
|
||||
/**
|
||||
* @param list<string> $conditions
|
||||
*/
|
||||
public function __construct(
|
||||
public SpecialOffer $offer,
|
||||
public string $title,
|
||||
public ?string $description,
|
||||
public string $advantage,
|
||||
public array $conditions,
|
||||
public ?CarbonImmutable $arrival = null,
|
||||
public ?CarbonImmutable $departure = null,
|
||||
public ?PriceQuote $quote = null,
|
||||
) {}
|
||||
|
||||
public function nights(): ?int
|
||||
{
|
||||
return $this->arrival && $this->departure ? (int) $this->arrival->diffInDays($this->departure) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Price before the discount (accommodation, extra guests, cleaning) – for "statt …".
|
||||
*/
|
||||
public function regularTotal(): ?int
|
||||
{
|
||||
return $this->quote ? $this->quote->total() + $this->quote->discount() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Link to the booking page, with the dates filled in when the offer has concrete dates.
|
||||
*/
|
||||
public function bookingUrl(): string
|
||||
{
|
||||
return route('booking.create', array_filter([
|
||||
'anreise' => $this->arrival?->toDateString(),
|
||||
'abreise' => $this->departure?->toDateString(),
|
||||
]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable key for the view (an offer can appear several times with different gaps).
|
||||
*/
|
||||
public function key(): string
|
||||
{
|
||||
return $this->offer->id.'-'.($this->arrival?->toDateString() ?? 'rule');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
<?php
|
||||
|
||||
namespace App\Pricing;
|
||||
|
||||
use App\Availability\AvailabilityChecker;
|
||||
use App\Availability\GapFinder;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Models\Property;
|
||||
use App\Models\SpecialOffer;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Which offers the website advertises right now – independent of the seasonal appearance.
|
||||
*
|
||||
* Shown are active, public offers without a code whose booking window is open. Fixed dates only while they
|
||||
* are still free; gap fillers once per free gap found in the calendar. Fixed dates and gaps are priced
|
||||
* with PriceCalculator, so the advertised price is exactly what the guest is quoted. Order: highlighted
|
||||
* first, then priority, then the earliest date.
|
||||
*/
|
||||
class OfferShowcase
|
||||
{
|
||||
/** Gap fillers without a lead time limit look this many days ahead. */
|
||||
public const GAP_HORIZON_DAYS = 60;
|
||||
|
||||
/** At most this many gaps per gap filler. */
|
||||
public const GAPS_PER_OFFER = 3;
|
||||
|
||||
public function __construct(
|
||||
private PriceCalculator $calculator,
|
||||
private AvailabilityChecker $availability = new AvailabilityChecker,
|
||||
private GapFinder $gaps = new GapFinder,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return Collection<int, AdvertisedOffer>
|
||||
*/
|
||||
public function current(Property $property, ?CarbonImmutable $now = null, ?int $limit = null, bool $featuredOnly = false): Collection
|
||||
{
|
||||
$now ??= CarbonImmutable::now();
|
||||
$today = $now->startOfDay();
|
||||
|
||||
$offers = $property->specialOffers()
|
||||
->active()
|
||||
->where('is_public', true)
|
||||
->whereNull('code')
|
||||
->when($featuredOnly, fn ($query) => $query->where('is_featured', true))
|
||||
->where(fn ($query) => $query->whereNull('bookable_from')->orWhere('bookable_from', '<=', $now))
|
||||
->where(fn ($query) => $query->whereNull('bookable_until')->orWhere('bookable_until', '>=', $now))
|
||||
->get();
|
||||
|
||||
$advertised = $offers->flatMap(fn (SpecialOffer $offer): array => match ($offer->kind ?? OfferKind::Rule) {
|
||||
OfferKind::Rule => $this->rule($offer, $today),
|
||||
OfferKind::FixedDates => $this->fixedDates($property, $offer, $now),
|
||||
OfferKind::GapFiller => $this->gapFiller($property, $offer, $now),
|
||||
});
|
||||
|
||||
$sorted = $advertised->sortBy([
|
||||
fn (AdvertisedOffer $a, AdvertisedOffer $b): int => $b->offer->is_featured <=> $a->offer->is_featured,
|
||||
fn (AdvertisedOffer $a, AdvertisedOffer $b): int => $b->offer->priority <=> $a->offer->priority,
|
||||
fn (AdvertisedOffer $a, AdvertisedOffer $b): int => ($a->arrival?->getTimestamp() ?? PHP_INT_MAX) <=> ($b->arrival?->getTimestamp() ?? PHP_INT_MAX),
|
||||
])->values();
|
||||
|
||||
return $limit ? $sorted->take($limit)->values() : $sorted;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<AdvertisedOffer>
|
||||
*/
|
||||
private function rule(SpecialOffer $offer, CarbonImmutable $today): array
|
||||
{
|
||||
if ($offer->stay_until !== null && $offer->stay_until->lessThanOrEqualTo($today)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [$this->advertised($offer)];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<AdvertisedOffer>
|
||||
*/
|
||||
private function fixedDates(Property $property, SpecialOffer $offer, CarbonImmutable $now): array
|
||||
{
|
||||
if ($offer->stay_from === null || $offer->stay_until === null || $offer->stay_from->lessThanOrEqualTo($now->startOfDay())) {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (! $this->availability->isAvailable($property, $offer->stay_from, $offer->stay_until)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$quote = $this->pricedWith($property, $offer, $offer->stay_from, $offer->stay_until, $now);
|
||||
|
||||
return $quote ? [$this->advertised($offer, $offer->stay_from, $offer->stay_until, $quote)] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<AdvertisedOffer>
|
||||
*/
|
||||
private function gapFiller(Property $property, SpecialOffer $offer, CarbonImmutable $now): array
|
||||
{
|
||||
$today = $now->startOfDay();
|
||||
$from = $today->addDays(max(1, $offer->min_days_before_arrival ?? 1));
|
||||
$until = $today->addDays($offer->max_days_before_arrival ?? self::GAP_HORIZON_DAYS)->addDay();
|
||||
if ($offer->stay_from !== null && $offer->stay_from->greaterThan($from)) {
|
||||
$from = $offer->stay_from;
|
||||
}
|
||||
|
||||
$advertised = [];
|
||||
foreach ($this->gaps->gaps($property, $from, $until, $offer->max_gap_nights ?? 7) as [$arrival, $departure]) {
|
||||
$quote = $this->pricedWith($property, $offer, $arrival, $departure, $now);
|
||||
if ($quote !== null) {
|
||||
$advertised[] = $this->advertised($offer, $arrival, $departure, $quote);
|
||||
}
|
||||
|
||||
if (count($advertised) >= self::GAPS_PER_OFFER) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return $advertised;
|
||||
}
|
||||
|
||||
/**
|
||||
* The quote for the stay, if the offer is actually applied to it (it may lose against a better offer
|
||||
* or fail a condition such as the minimum stay); priced for the number of guests included in the rent.
|
||||
*/
|
||||
private function pricedWith(Property $property, SpecialOffer $offer, CarbonImmutable $arrival, CarbonImmutable $departure, CarbonImmutable $now): ?PriceQuote
|
||||
{
|
||||
$quote = rescue(
|
||||
fn (): PriceQuote => $this->calculator->calculate($property, new StayRequest($arrival, $departure, max(1, $property->included_guests)), $now),
|
||||
null,
|
||||
false,
|
||||
);
|
||||
|
||||
$applied = $quote !== null && collect($quote->lines)
|
||||
->contains(fn (QuoteLine $line): bool => $line->type === QuoteLineType::Discount && $line->label === $offer->name);
|
||||
|
||||
return $applied ? $quote : null;
|
||||
}
|
||||
|
||||
private function advertised(SpecialOffer $offer, ?CarbonImmutable $arrival = null, ?CarbonImmutable $departure = null, ?PriceQuote $quote = null): AdvertisedOffer
|
||||
{
|
||||
return new AdvertisedOffer(
|
||||
offer: $offer,
|
||||
title: $offer->name,
|
||||
description: $offer->public_description,
|
||||
advantage: $offer->advantageLabel(),
|
||||
conditions: $offer->conditionSummary(),
|
||||
arrival: $arrival,
|
||||
departure: $departure,
|
||||
quote: $quote,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,9 @@
|
||||
|
||||
namespace App\Pricing;
|
||||
|
||||
use App\Availability\GapFinder;
|
||||
use App\Enums\ExtraPricing;
|
||||
use App\Enums\OfferKind;
|
||||
use App\Enums\QuoteLineType;
|
||||
use App\Models\Extra;
|
||||
use App\Models\Property;
|
||||
@@ -13,6 +15,8 @@
|
||||
|
||||
class PriceCalculator
|
||||
{
|
||||
public function __construct(private GapFinder $gaps = new GapFinder) {}
|
||||
|
||||
/**
|
||||
* Price a stay. Special offers are applied automatically; $bookedAt (default: now) decides
|
||||
* time-dependent offers such as last minute or early bird.
|
||||
@@ -32,14 +36,17 @@ public function calculate(Property $property, StayRequest $stay, ?CarbonImmutabl
|
||||
$nights = $stay->nights();
|
||||
$nightSeasons = $this->seasonPerNight($property, $stay);
|
||||
|
||||
$bookedAt ??= CarbonImmutable::now();
|
||||
$offers = $this->applicableOffers($property, $stay, $nightSeasons, $bookedAt);
|
||||
|
||||
$arrivalSeason = $nightSeasons[0];
|
||||
if ($nights < $arrivalSeason->min_nights) {
|
||||
if ($nights < $arrivalSeason->min_nights && ! $this->minimumStayRelaxed($property, $stay, $offers)) {
|
||||
throw QuoteException::minimumStay($arrivalSeason->min_nights, $arrivalSeason->name);
|
||||
}
|
||||
|
||||
$lines = $this->accommodationLines($nightSeasons);
|
||||
|
||||
$appliedOffers = $this->bestOffers($property, $stay, $nightSeasons, $bookedAt ?? CarbonImmutable::now());
|
||||
$appliedOffers = $this->bestOffers($offers, $nightSeasons);
|
||||
foreach ($appliedOffers as ['offer' => $offer, 'discount' => $discount]) {
|
||||
$lines[] = new QuoteLine(QuoteLineType::Discount, $offer->name, 1, -$discount, -$discount);
|
||||
}
|
||||
@@ -117,20 +124,61 @@ private function accommodationLines(array $nightSeasons): array
|
||||
), $runs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a stay shorter than the season's minimum is still allowed: an applicable offer waives it, or –
|
||||
* never below the property's absolute minimum – the stay fills a calendar gap completely, or it ends on the
|
||||
* typical changeover day (so the following week stays bookable).
|
||||
*
|
||||
* @param Collection<int, SpecialOffer> $offers
|
||||
*/
|
||||
private function minimumStayRelaxed(Property $property, StayRequest $stay, Collection $offers): bool
|
||||
{
|
||||
if ($offers->contains(fn (SpecialOffer $offer): bool => $offer->waives_min_stay)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if ($stay->nights() < max(1, (int) $property->min_stay_absolute)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ($property->min_stay_until_changeover && $property->changeover_weekday !== null && $stay->departure->isoWeekday() === $property->changeover_weekday) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return $property->min_stay_fill_gaps && $this->gaps->gapContaining($property, $stay->arrival, $stay->departure) === $stay->nights();
|
||||
}
|
||||
|
||||
/**
|
||||
* Active offers whose conditions the stay meets. The calendar gap is only looked up if a gap filler exists.
|
||||
*
|
||||
* @param non-empty-list<Season> $nightSeasons
|
||||
* @return Collection<int, SpecialOffer>
|
||||
*/
|
||||
private function applicableOffers(Property $property, StayRequest $stay, array $nightSeasons, CarbonImmutable $bookedAt): Collection
|
||||
{
|
||||
$offers = $property->specialOffers()->active()->get();
|
||||
|
||||
$gapNights = $offers->contains(fn (SpecialOffer $offer): bool => $offer->kind === OfferKind::GapFiller)
|
||||
? $this->gaps->gapContaining($property, $stay->arrival, $stay->departure)
|
||||
: null;
|
||||
|
||||
return $offers->filter(fn (SpecialOffer $offer): bool => $offer->appliesTo($stay, $nightSeasons[0]->name, $bookedAt, $gapNights))->values();
|
||||
}
|
||||
|
||||
/**
|
||||
* The guest gets whichever is cheaper for them: the single best non-combinable offer,
|
||||
* or all combinable offers together (capped at the accommodation price).
|
||||
*
|
||||
* @param Collection<int, SpecialOffer> $offers
|
||||
* @param non-empty-list<Season> $nightSeasons
|
||||
* @return list<array{offer: SpecialOffer, discount: int}>
|
||||
*/
|
||||
private function bestOffers(Property $property, StayRequest $stay, array $nightSeasons, CarbonImmutable $bookedAt): array
|
||||
private function bestOffers(Collection $offers, array $nightSeasons): array
|
||||
{
|
||||
$nightlyRates = array_map(fn (Season $season): int => $season->nightly_rate, $nightSeasons);
|
||||
$accommodation = array_sum($nightlyRates);
|
||||
|
||||
$candidates = $property->specialOffers()->active()->get()
|
||||
->filter(fn (SpecialOffer $offer): bool => $offer->appliesTo($stay, $nightSeasons[0]->name, $bookedAt))
|
||||
$candidates = $offers
|
||||
->map(fn (SpecialOffer $offer): array => ['offer' => $offer, 'discount' => $offer->discountFor($nightlyRates)])
|
||||
->filter(fn (array $candidate): bool => $candidate['discount'] > 0);
|
||||
|
||||
|
||||
@@ -23,6 +23,14 @@ public function __construct(
|
||||
public ?bool $promoCodeApplied = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The same quote with one more line, e.g. a manual adjustment in an offer.
|
||||
*/
|
||||
public function withLine(QuoteLine $line): self
|
||||
{
|
||||
return new self($this->arrival, $this->departure, $this->guests, [...$this->lines, $line], $this->depositPercent, $this->balanceDueOn, $this->promoCodeApplied);
|
||||
}
|
||||
|
||||
/**
|
||||
* Total of all special offer discounts as a positive amount.
|
||||
*/
|
||||
|
||||
@@ -2,8 +2,12 @@
|
||||
|
||||
namespace App\Providers;
|
||||
|
||||
use App\Support\StripImageMetadata;
|
||||
use Illuminate\Support\Facades\Event;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
use Illuminate\Support\Facades\URL;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent;
|
||||
|
||||
class AppServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -20,6 +24,14 @@ public function register(): void
|
||||
*/
|
||||
public function boot(): void
|
||||
{
|
||||
// Test environments: deliver every e-mail to one address only, so no guest gets test mails.
|
||||
if (filled(config('fewo.mail_redirect_to'))) {
|
||||
Mail::alwaysTo(config('fewo.mail_redirect_to'));
|
||||
}
|
||||
|
||||
// Photos: remove metadata (GPS position, camera data) from uploaded originals, which stay downloadable.
|
||||
Event::listen(MediaHasBeenAddedEvent::class, fn (MediaHasBeenAddedEvent $event) => StripImageMetadata::strip($event->media));
|
||||
|
||||
// On Strato the domain points at the deployment folder and .htaccess forwards to current/public;
|
||||
// without a fixed root, some URLs (e.g. /sitemap.xml) would be generated with /current/public.
|
||||
if (! $this->app->environment('local', 'testing')) {
|
||||
|
||||
@@ -2,8 +2,11 @@
|
||||
|
||||
namespace App\Providers\Filament;
|
||||
|
||||
use App\Http\Middleware\RequireTwoFactorForAdmins;
|
||||
use App\Enums\AdminMode;
|
||||
use App\Models\User;
|
||||
use Filament\Actions\Action;
|
||||
use Filament\Auth\MultiFactor\App\AppAuthentication;
|
||||
use Filament\Facades\Filament;
|
||||
use Filament\Http\Middleware\Authenticate;
|
||||
use Filament\Http\Middleware\AuthenticateSession;
|
||||
use Filament\Http\Middleware\DisableBladeIconComponents;
|
||||
@@ -12,6 +15,7 @@
|
||||
use Filament\Panel;
|
||||
use Filament\PanelProvider;
|
||||
use Filament\Support\Colors\Color;
|
||||
use Filament\Support\Icons\Heroicon;
|
||||
use Filament\Widgets\AccountWidget;
|
||||
use Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse;
|
||||
use Illuminate\Cookie\Middleware\EncryptCookies;
|
||||
@@ -22,6 +26,13 @@
|
||||
|
||||
class AdminPanelProvider extends PanelProvider
|
||||
{
|
||||
private static function currentUser(): ?User
|
||||
{
|
||||
$user = Filament::auth()->user();
|
||||
|
||||
return $user instanceof User ? $user : null;
|
||||
}
|
||||
|
||||
public function panel(Panel $panel): Panel
|
||||
{
|
||||
return $panel
|
||||
@@ -30,12 +41,22 @@ public function panel(Panel $panel): Panel
|
||||
->path('admin')
|
||||
->login()
|
||||
->profile(isSimple: false)
|
||||
// Two-factor login with an authenticator app (TOTP) and recovery codes; mandatory for administrators.
|
||||
// Two-factor login with an authenticator app (TOTP) and recovery codes; mandatory for every account.
|
||||
->multiFactorAuthentication(
|
||||
[AppAuthentication::make()->brandName('FeWo Stommer')->recoverable()],
|
||||
isRequired: true,
|
||||
)
|
||||
->multiFactorAuthenticationRequiredMiddlewareName(RequireTwoFactorForAdmins::class)
|
||||
->userMenuItems([
|
||||
'admin-mode' => Action::make('switchAdminMode')
|
||||
->label(fn (): string => (self::currentUser()?->adminMode() ?? AdminMode::Expert)->other()->switchLabel())
|
||||
->icon(fn (): Heroicon => self::currentUser()?->adminMode() === AdminMode::Simple ? Heroicon::OutlinedAdjustmentsHorizontal : Heroicon::OutlinedSparkles)
|
||||
->action(function () {
|
||||
$user = self::currentUser();
|
||||
$user?->forceFill(['admin_mode' => $user->adminMode()->other()])->save();
|
||||
|
||||
return redirect(url()->previous());
|
||||
}),
|
||||
])
|
||||
->brandName('FeWo Stommer · Verwaltung')
|
||||
->navigationGroups(['Vermietung', 'Webseite', 'System'])
|
||||
->colors([
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use Spatie\Image\Enums\ImageDriver;
|
||||
use Spatie\Image\Image;
|
||||
use Spatie\MediaLibrary\MediaCollections\Models\Media;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Re-encodes an uploaded original photo without its metadata (EXIF/XMP: GPS position, camera, owner).
|
||||
* The orientation is applied first, so the photo keeps its correct rotation. Failures never block an upload.
|
||||
*/
|
||||
class StripImageMetadata
|
||||
{
|
||||
private const TYPES = ['image/jpeg', 'image/png', 'image/webp'];
|
||||
|
||||
public static function strip(Media $media, bool $force = false): bool
|
||||
{
|
||||
if (! in_array($media->mime_type, self::TYPES, true) || ($media->getCustomProperty('metadata_stripped') && ! $force)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$path = $media->getPath();
|
||||
if (! is_file($path)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// GD on purpose: Imagick (default when installed, e.g. on Strato) keeps the EXIF data when saving.
|
||||
Image::useImageDriver(ImageDriver::Gd)->loadFile($path)->quality(90)->save($path);
|
||||
} catch (Throwable $exception) {
|
||||
report($exception);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
clearstatcache(true, $path);
|
||||
$media->size = (int) filesize($path);
|
||||
$media->setCustomProperty('metadata_stripped', true);
|
||||
$media->saveQuietly();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -2,13 +2,19 @@
|
||||
|
||||
namespace App\Themes;
|
||||
|
||||
use App\Models\Appearance;
|
||||
use App\Themes\Sections\Section;
|
||||
use Filament\Forms\Components\Builder\Block;
|
||||
use Filament\Forms\Components\Hidden;
|
||||
use Filament\Forms\Components\Select;
|
||||
use Illuminate\Contracts\View\View;
|
||||
use Illuminate\Support\Facades\View as ViewFactory;
|
||||
|
||||
/**
|
||||
* The section catalogue from config/themes.php: builder blocks for the admin and rendering for the website.
|
||||
*
|
||||
* Every placed section carries data.id (a stable UUID, see Page::assignSectionIds) so appearances can
|
||||
* address it, and data.appearances (appearance ids; empty = always shown).
|
||||
*/
|
||||
class SectionRegistry
|
||||
{
|
||||
@@ -36,13 +42,33 @@ public function blocks(): array
|
||||
{
|
||||
return array_values(array_map(
|
||||
fn (string $class): Block => Block::make($class::key())
|
||||
->label($class::label())
|
||||
->label(fn (?array $state): string => $this->blockLabel($class, $state))
|
||||
->icon($class::icon())
|
||||
->schema($class::schema()),
|
||||
->schema([
|
||||
Hidden::make('id'),
|
||||
...$class::schema(),
|
||||
Select::make('appearances')
|
||||
->label('Nur anzeigen im Erscheinungsbild')
|
||||
->helperText('Leer = immer anzeigen. Z. B. ein Weihnachts-Baustein nur im Erscheinungsbild „Weihnachten“.')
|
||||
->options(fn (): array => Appearance::query()->orderByDesc('is_default')->orderBy('name')->pluck('name', 'id')->all())
|
||||
->multiple(),
|
||||
]),
|
||||
$this->all(),
|
||||
));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a placed section is shown with the active appearance.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function isVisible(Theme $theme, array $data): bool
|
||||
{
|
||||
$appearances = array_map('intval', array_filter((array) ($data['appearances'] ?? [])));
|
||||
|
||||
return $appearances === [] || ($theme->appearance !== null && in_array($theme->appearance->id, $appearances, true));
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders the stored sections of a page; unknown or failing types are skipped (and reported),
|
||||
* so a page never breaks because of one section.
|
||||
@@ -55,7 +81,7 @@ public function render(Theme $theme, ?array $sections): array
|
||||
$views = [];
|
||||
foreach ($sections ?? [] as $index => $stored) {
|
||||
$section = $this->get($stored['type'] ?? '');
|
||||
if ($section === null || ! ViewFactory::exists($section->view())) {
|
||||
if ($section === null || ! ViewFactory::exists($section->view()) || ! $this->isVisible($theme, $stored['data'] ?? [])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -68,4 +94,22 @@ public function render(Theme $theme, ?array $sections): array
|
||||
|
||||
return $views;
|
||||
}
|
||||
|
||||
/**
|
||||
* "Text mit Bild · Ihr Zuhause an der Ostsee · nur: Winter" for the collapsed builder item.
|
||||
*
|
||||
* @param class-string<Section> $class
|
||||
* @param array<string, mixed>|null $state
|
||||
*/
|
||||
private function blockLabel(string $class, ?array $state): string
|
||||
{
|
||||
if ($state === null) {
|
||||
return $class::label();
|
||||
}
|
||||
|
||||
$appearances = array_filter((array) ($state['appearances'] ?? []));
|
||||
$only = $appearances === [] ? null : 'nur: '.Appearance::query()->whereKey($appearances)->pluck('name')->implode(', ');
|
||||
|
||||
return collect([$class::label(), $class::summary($state), $only])->filter()->implode(' · ');
|
||||
}
|
||||
}
|
||||
@@ -38,12 +38,17 @@ public static function schema(): array
|
||||
];
|
||||
}
|
||||
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return ['photo_id' => ['label' => 'Hintergrundfoto', 'type' => self::SLOT_SINGLE]];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
return [
|
||||
'title' => $theme->text('cta.title', $data['title'] ?? null),
|
||||
'text' => $theme->text('cta.text', $data['text'] ?? null),
|
||||
'photo' => isset($data['photo_id']) ? Photo::find($data['photo_id']) : null,
|
||||
'photo' => $this->seasonalPhoto($theme, $data, 'photo_id') ?? (isset($data['photo_id']) ? Photo::find($data['photo_id']) : null),
|
||||
'buttonLabel' => $data['button_label'] ?? 'Belegung & Preise',
|
||||
'buttonUrl' => $this->pageUrl($data['button_page'] ?? null) ?? route('booking.create'),
|
||||
];
|
||||
|
||||
@@ -37,16 +37,21 @@ public static function schema(): array
|
||||
];
|
||||
}
|
||||
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return ['photo_ids' => ['label' => 'Galerie', 'type' => self::SLOT_COLLECTION]];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
$category = PhotoCategory::tryFrom($data['category'] ?? '');
|
||||
|
||||
return [
|
||||
'heading' => $data['heading'] ?? null,
|
||||
'photos' => Photo::query()->published()->with('media')
|
||||
'photos' => $this->withSeasonalPhotos($theme, $data, 'photo_ids', Photo::query()->published()->with('media')
|
||||
->when($category, fn ($query) => $query->where('category', $category))
|
||||
->when(filled($data['limit'] ?? null), fn ($query) => $query->limit((int) $data['limit']))
|
||||
->get(),
|
||||
->get()),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
namespace App\Themes\Sections;
|
||||
|
||||
use App\Models\Photo;
|
||||
use App\Pricing\OfferShowcase;
|
||||
use App\Themes\Theme;
|
||||
use Filament\Forms\Components\Textarea;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
@@ -36,18 +37,31 @@ public static function schema(): array
|
||||
Textarea::make('text')->label('Text')->rows(2)->maxLength(400),
|
||||
static::photoSelect('photo_id', 'Foto (wenn das Erscheinungsbild keins vorgibt)'),
|
||||
Toggle::make('show_search')->label('Verfügbarkeitssuche anzeigen')->default(true),
|
||||
Toggle::make('show_offer')
|
||||
->label('Hervorgehobenes Sonderangebot im Titelbereich zeigen')
|
||||
->helperText('Das wichtigste als „hervorgehoben“ markierte Angebot, sofern gerade eins gilt.')
|
||||
->default(true),
|
||||
];
|
||||
}
|
||||
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return ['photo_id' => ['label' => 'Foto', 'type' => self::SLOT_SINGLE]];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
$fallback = isset($data['photo_id']) ? Photo::find($data['photo_id']) : Photo::query()->published()->first();
|
||||
$featuredOffer = ($data['show_offer'] ?? true) && $theme->property()
|
||||
? app(OfferShowcase::class)->current($theme->property(), limit: 1, featuredOnly: true)->first()
|
||||
: null;
|
||||
|
||||
return [
|
||||
'eyebrow' => $theme->text('hero.eyebrow', $data['eyebrow'] ?? null),
|
||||
'title' => $theme->text('hero.title', $data['title'] ?? $theme->site->name),
|
||||
'text' => $theme->text('hero.text', $data['text'] ?? null),
|
||||
'photo' => $theme->heroPhoto($fallback),
|
||||
'photo' => $this->seasonalPhoto($theme, $data, 'photo_id') ?? $theme->heroPhoto($fallback),
|
||||
'featuredOffer' => $featuredOffer,
|
||||
'showSearch' => (bool) ($data['show_search'] ?? true),
|
||||
'property' => $theme->property(),
|
||||
];
|
||||
|
||||
@@ -39,6 +39,11 @@ public static function schema(): array
|
||||
];
|
||||
}
|
||||
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return ['photo_ids' => ['label' => 'Bilder der Umgebung', 'type' => self::SLOT_COLLECTION]];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
$address = $theme->property()?->address;
|
||||
@@ -50,7 +55,7 @@ public function data(Theme $theme, array $data): array
|
||||
'address' => $address,
|
||||
'mapUrl' => $address ? 'https://www.openstreetmap.org/search?query='.rawurlencode($address) : null,
|
||||
'photos' => ($data['show_photos'] ?? true)
|
||||
? Photo::query()->published()->with('media')->where('category', PhotoCategory::Area)->limit(6)->get()
|
||||
? $this->withSeasonalPhotos($theme, $data, 'photo_ids', Photo::query()->published()->with('media')->where('category', PhotoCategory::Area)->limit(6)->get())
|
||||
: collect(),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -2,15 +2,24 @@
|
||||
|
||||
namespace App\Themes\Sections;
|
||||
|
||||
use App\Models\SpecialOffer;
|
||||
use App\Pricing\OfferShowcase;
|
||||
use App\Themes\Theme;
|
||||
use Filament\Forms\Components\Radio;
|
||||
use Filament\Forms\Components\TextInput;
|
||||
use Filament\Forms\Components\Toggle;
|
||||
|
||||
/**
|
||||
* Public special offers (active, promoted, without code); the appearance's featured offer comes first.
|
||||
* The offers OfferShowcase advertises right now (independent of the appearance), shown side by side,
|
||||
* as a list or one after another (rotating). The section disappears when there is no current offer.
|
||||
*/
|
||||
class OffersSection extends Section
|
||||
{
|
||||
public const DISPLAYS = [
|
||||
'grid' => 'Nebeneinander (Kacheln)',
|
||||
'list' => 'Untereinander (Liste)',
|
||||
'rotating' => 'Rollierend (eins nach dem anderen)',
|
||||
];
|
||||
|
||||
public static function key(): string
|
||||
{
|
||||
return 'offers';
|
||||
@@ -30,27 +39,22 @@ public static function schema(): array
|
||||
{
|
||||
return [
|
||||
TextInput::make('heading')->label('Überschrift')->default('Aktuelle Angebote')->maxLength(120),
|
||||
Radio::make('display')->label('Darstellung, wenn mehrere Angebote gelten')->options(self::DISPLAYS)->default('grid'),
|
||||
TextInput::make('limit')->label('Höchstens anzeigen')->integer()->minValue(1)->maxValue(12)->default(6),
|
||||
Toggle::make('featured_only')->label('Nur hervorgehobene Angebote')->default(false),
|
||||
];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
$offers = $theme->property()?->specialOffers()
|
||||
->active()
|
||||
->where('is_public', true)
|
||||
->whereNull('code')
|
||||
->where(fn ($query) => $query->whereNull('bookable_until')->orWhere('bookable_until', '>=', now()))
|
||||
->get() ?? collect();
|
||||
|
||||
$featured = $theme->appearance?->featuredOffer;
|
||||
if ($featured) {
|
||||
$offers = $offers->reject(fn (SpecialOffer $offer): bool => $offer->is($featured))->prepend($featured);
|
||||
}
|
||||
$property = $theme->property();
|
||||
|
||||
return [
|
||||
'heading' => $data['heading'] ?? null,
|
||||
'offers' => $offers,
|
||||
'featuredId' => $featured?->id,
|
||||
'display' => array_key_exists($data['display'] ?? '', self::DISPLAYS) ? $data['display'] : 'grid',
|
||||
'offers' => $property
|
||||
? app(OfferShowcase::class)->current($property, limit: (int) ($data['limit'] ?? 6) ?: 6, featuredOnly: (bool) ($data['featured_only'] ?? false))
|
||||
: collect(),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
namespace App\Themes\Sections;
|
||||
|
||||
use App\Filament\Forms\Components\PhotoSelect;
|
||||
use App\Models\Page;
|
||||
use App\Models\Photo;
|
||||
use App\Themes\Theme;
|
||||
@@ -17,6 +18,15 @@
|
||||
*/
|
||||
abstract class Section
|
||||
{
|
||||
/** One photo (field holds a photo id). */
|
||||
public const SLOT_SINGLE = 'single';
|
||||
|
||||
/** Several chosen photos (field holds a list of ids). */
|
||||
public const SLOT_MULTIPLE = 'multiple';
|
||||
|
||||
/** Photos picked automatically (e.g. by category); an appearance may replace or precede them. */
|
||||
public const SLOT_COLLECTION = 'collection';
|
||||
|
||||
abstract public static function key(): string;
|
||||
|
||||
abstract public static function label(): string;
|
||||
@@ -39,6 +49,28 @@ public static function schema(): array
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Photo places an appearance can fill with seasonal photos ("Bilder je Baustein").
|
||||
*
|
||||
* @return array<string, array{label: string, type: string, max?: int}>
|
||||
*/
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Short text identifying a placed section in admin lists, e.g. its heading.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public static function summary(array $data): ?string
|
||||
{
|
||||
$text = $data['heading'] ?? $data['title'] ?? null;
|
||||
|
||||
return filled($text) ? str(strip_tags((string) $text))->replace('*', '')->limit(50)->toString() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Variables for the view.
|
||||
*
|
||||
@@ -75,6 +107,55 @@ protected function photos(?array $ids): Collection
|
||||
return new Collection(array_values(array_filter(array_map(fn ($id) => $photos->get((int) $id), $ids))));
|
||||
}
|
||||
|
||||
/**
|
||||
* The seasonal photo the active appearance sets for a single slot of this placed section.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
protected function seasonalPhoto(Theme $theme, array $data, string $slot): ?Photo
|
||||
{
|
||||
return $this->seasonalPhotos($theme, $data, $slot)?->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* The seasonal photos the active appearance sets for a slot of this placed section, null if none.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @return Collection<int, Photo>|null
|
||||
*/
|
||||
protected function seasonalPhotos(Theme $theme, array $data, string $slot): ?Collection
|
||||
{
|
||||
$ids = $theme->sectionPhotoIds($data['id'] ?? null, $slot);
|
||||
if ($ids === []) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$photos = $this->photos($ids);
|
||||
|
||||
return $photos->isEmpty() ? null : $photos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photos of a collection slot: the automatic photos, replaced or preceded by the seasonal ones.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
* @param Collection<int, Photo> $automatic
|
||||
* @return Collection<int, Photo>
|
||||
*/
|
||||
protected function withSeasonalPhotos(Theme $theme, array $data, string $slot, Collection $automatic): Collection
|
||||
{
|
||||
$seasonal = $this->seasonalPhotos($theme, $data, $slot);
|
||||
if ($seasonal === null) {
|
||||
return $automatic;
|
||||
}
|
||||
|
||||
if ($theme->sectionPhotoMode($data['id'] ?? null) === 'prepend') {
|
||||
return $seasonal->merge($automatic)->unique('id')->values();
|
||||
}
|
||||
|
||||
return $seasonal;
|
||||
}
|
||||
|
||||
protected function pageUrl(?string $slug): ?string
|
||||
{
|
||||
if (blank($slug)) {
|
||||
@@ -85,15 +166,13 @@ protected function pageUrl(?string $slug): ?string
|
||||
}
|
||||
|
||||
/**
|
||||
* Select field listing the website photos.
|
||||
* Select field listing the website photos with thumbnails.
|
||||
*/
|
||||
protected static function photoSelect(string $name, string $label, bool $multiple = false): Select
|
||||
{
|
||||
return Select::make($name)
|
||||
return PhotoSelect::make($name)
|
||||
->label($label)
|
||||
->options(fn (): array => Photo::query()->orderBy('category')->orderBy('sort_order')->pluck('alt_text', 'id')->all())
|
||||
->multiple($multiple)
|
||||
->searchable();
|
||||
->multiple($multiple);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -40,13 +40,18 @@ public static function schema(): array
|
||||
];
|
||||
}
|
||||
|
||||
public static function photoSlots(): array
|
||||
{
|
||||
return ['photo_ids' => ['label' => 'Bilder', 'type' => self::SLOT_MULTIPLE, 'max' => 3]];
|
||||
}
|
||||
|
||||
public function data(Theme $theme, array $data): array
|
||||
{
|
||||
return [
|
||||
'eyebrow' => $data['eyebrow'] ?? null,
|
||||
'heading' => $data['heading'] ?? '',
|
||||
'text' => $this->html($data['text'] ?? null),
|
||||
'photos' => $this->photos($data['photo_ids'] ?? []),
|
||||
'photos' => $this->seasonalPhotos($theme, $data, 'photo_ids') ?? $this->photos($data['photo_ids'] ?? []),
|
||||
'imagePosition' => $data['image_position'] ?? 'right',
|
||||
'linkLabel' => $data['link_label'] ?? null,
|
||||
'linkUrl' => $this->pageUrl($data['link_page'] ?? null),
|
||||
|
||||
@@ -34,6 +34,7 @@ public function activate(): self
|
||||
{
|
||||
$paths = array_map(fn (ThemeManifest $theme): string => $theme->viewsPath(), $this->chain());
|
||||
View::replaceNamespace('theme', $paths);
|
||||
View::getFinder()->flush();
|
||||
|
||||
return $this;
|
||||
}
|
||||
@@ -96,6 +97,32 @@ public function heroPhoto(?Photo $fallback = null): ?Photo
|
||||
return $this->appearance?->heroPhoto ?? $fallback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Photo ids the active appearance sets for a slot of a placed section ("Bilder je Baustein").
|
||||
*
|
||||
* @return list<int>
|
||||
*/
|
||||
public function sectionPhotoIds(?string $sectionId, string $slot): array
|
||||
{
|
||||
if (blank($sectionId) || $this->appearance === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$ids = $this->appearance->section_photos[$sectionId][$slot] ?? null;
|
||||
|
||||
return array_values(array_map('intval', array_filter((array) $ids)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether seasonal photos replace the automatic photos of a section ('replace') or come first ('prepend').
|
||||
*/
|
||||
public function sectionPhotoMode(?string $sectionId): string
|
||||
{
|
||||
$mode = $sectionId ? ($this->appearance?->section_photos[$sectionId]['mode'] ?? null) : null;
|
||||
|
||||
return $mode === 'prepend' ? 'prepend' : 'replace';
|
||||
}
|
||||
|
||||
public function appearanceKey(): string
|
||||
{
|
||||
return $this->appearance ? str($this->appearance->name)->slug()->toString() : 'standard';
|
||||
|
||||
@@ -0,0 +1,334 @@
|
||||
<?php
|
||||
|
||||
namespace App\Themes;
|
||||
|
||||
use App\Models\Appearance;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
use Symfony\Component\Finder\Finder;
|
||||
|
||||
/**
|
||||
* Checks a theme against the theme contract (docs/THEME-ERSTELLUNG.md) so a theme built elsewhere – e.g. by a
|
||||
* design session – can be verified before it is selected: manifest, inheritance, build entry points, required
|
||||
* markup of overridden views, token-only colours, no external resources and WCAG contrast of the colour tokens
|
||||
* (theme defaults and every appearance).
|
||||
*/
|
||||
class ThemeChecker
|
||||
{
|
||||
/** Pairs [text token, background token] that must reach WCAG AA for normal text (4.5:1). */
|
||||
public const CONTRAST_PAIRS = [
|
||||
['ink', 'ground'], ['muted', 'ground'], ['accent', 'ground'],
|
||||
['ink', 'surface'], ['muted', 'surface'], ['accent', 'surface'],
|
||||
['accent-ink', 'accent'], ['band-ink', 'band'], ['band-muted', 'band'], ['banner-ink', 'banner'],
|
||||
];
|
||||
|
||||
public const MIN_CONTRAST = 4.5;
|
||||
|
||||
/** View files a theme may provide besides sections/<key> (custom partials are allowed in partials/). */
|
||||
private const KNOWN_VIEWS = ['layouts/app', 'page', 'partials/banner', 'partials/header', 'partials/footer', 'partials/image', 'partials/mobile-booking-bar'];
|
||||
|
||||
/**
|
||||
* Markup an overridden view must keep, with the reason shown when it is missing.
|
||||
*
|
||||
* @var array<string, array<string, string>>
|
||||
*/
|
||||
private const REQUIRED_MARKUP = [
|
||||
'layouts/app' => [
|
||||
"@yield('content')" => 'Seiteninhalt fehlt (@yield(\'content\')).',
|
||||
"@stack('head')" => 'Bausteine können nichts in <head> ergänzen (JSON-LD) – @stack(\'head\') fehlt.',
|
||||
'$theme->assets()' => 'CSS/JS werden nicht geladen – @vite($theme->assets()) fehlt.',
|
||||
'$theme->cssVariables()' => 'Farb-Tokens werden nicht ausgegeben – $theme->cssVariables() fehlt.',
|
||||
'@livewireStyles' => 'Buchungsformular braucht @livewireStyles.',
|
||||
'@livewireScripts' => 'Buchungsformular braucht @livewireScripts.',
|
||||
'noindex' => 'Vorschau und Testbetrieb müssen noindex setzen.',
|
||||
'id="lightbox"' => 'Galerie-Lightbox fehlt (<dialog id="lightbox"> mit img, [data-caption], [data-close]).',
|
||||
'data-appearance' => 'data-appearance am <html> fehlt (saisonale CSS-Regeln).',
|
||||
],
|
||||
'page' => [
|
||||
'$sections' => 'Die Bausteine der Seite werden nicht ausgegeben.',
|
||||
'$structuredData' => 'JSON-LD der Startseite fehlt ($structuredData).',
|
||||
],
|
||||
'partials/header' => ["menu('main')" => 'Hauptmenü fehlt ($theme->menu(\'main\')).'],
|
||||
'partials/footer' => ["menu('footer')" => 'Fußmenü (Impressum/Datenschutz) fehlt ($theme->menu(\'footer\')).'],
|
||||
'sections/hero' => [
|
||||
'name="anreise"' => 'Verfügbarkeitssuche: Feld name="anreise" fehlt.',
|
||||
'name="abreise"' => 'Verfügbarkeitssuche: Feld name="abreise" fehlt.',
|
||||
"route('booking.create')" => 'Verfügbarkeitssuche muss an route(\'booking.create\') senden.',
|
||||
],
|
||||
'sections/booking' => ['livewire:booking-request' => 'Kalender/Anfrage fehlt (<livewire:booking-request :property="$property" />).'],
|
||||
'sections/gallery' => ['data-lightbox' => 'Galerie-Links brauchen data-lightbox und data-alt.'],
|
||||
'sections/faq' => ['application/ld+json' => 'FAQ-JSON-LD fehlt.'],
|
||||
'sections/reviews' => ['nur Gäste' => 'Pflichthinweis zur Echtheit der Bewertungen (§ 5b UWG) fehlt.'],
|
||||
'sections/offers' => ['$display' => 'Darstellung (nebeneinander/Liste/rollierend) wird nicht berücksichtigt.'],
|
||||
];
|
||||
|
||||
public function __construct(private ThemeRegistry $registry) {}
|
||||
|
||||
/**
|
||||
* @return array{errors: list<string>, warnings: list<string>}
|
||||
*/
|
||||
public function check(ThemeManifest $theme): array
|
||||
{
|
||||
$errors = [];
|
||||
$warnings = [];
|
||||
|
||||
$this->checkManifest($theme, $errors, $warnings);
|
||||
$this->checkAssets($theme, $errors, $warnings);
|
||||
$this->checkViews($theme, $errors, $warnings);
|
||||
$this->checkContrast($theme, $errors, $warnings);
|
||||
|
||||
return ['errors' => $errors, 'warnings' => $warnings];
|
||||
}
|
||||
|
||||
/**
|
||||
* WCAG contrast ratio of two hex colours (1 … 21).
|
||||
*/
|
||||
public static function contrast(string $foreground, string $background): float
|
||||
{
|
||||
$luminance = function (string $hex): float {
|
||||
$hex = ltrim($hex, '#');
|
||||
if (strlen($hex) === 3) {
|
||||
$hex = $hex[0].$hex[0].$hex[1].$hex[1].$hex[2].$hex[2];
|
||||
}
|
||||
$channels = array_map(function (string $pair): float {
|
||||
$value = hexdec($pair) / 255;
|
||||
|
||||
return $value <= 0.03928 ? $value / 12.92 : (($value + 0.055) / 1.055) ** 2.4;
|
||||
}, str_split(substr($hex, 0, 6), 2));
|
||||
|
||||
return 0.2126 * $channels[0] + 0.7152 * $channels[1] + 0.0722 * $channels[2];
|
||||
};
|
||||
|
||||
[$lighter, $darker] = [max($luminance($foreground), $luminance($background)), min($luminance($foreground), $luminance($background))];
|
||||
|
||||
return round(($lighter + 0.05) / ($darker + 0.05), 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $errors
|
||||
* @param list<string> $warnings
|
||||
*/
|
||||
private function checkManifest(ThemeManifest $theme, array &$errors, array &$warnings): void
|
||||
{
|
||||
if (! preg_match('/^[a-z0-9]+(-[a-z0-9]+)*$/', $theme->key)) {
|
||||
$errors[] = "Key „{$theme->key}“: nur Kleinbuchstaben, Ziffern und Bindestriche.";
|
||||
}
|
||||
if (basename($theme->path) !== $theme->key) {
|
||||
$errors[] = 'Ordnername ('.basename($theme->path).") und key ({$theme->key}) müssen gleich sein – sonst baut Vite die Assets nicht.";
|
||||
}
|
||||
if (! preg_match('/^\d+\.\d+\.\d+$/', $theme->version)) {
|
||||
$errors[] = "version „{$theme->version}“ ist keine Versionsnummer (z. B. 0.1.0).";
|
||||
}
|
||||
if (blank($theme->description)) {
|
||||
$warnings[] = 'description fehlt – sie wird im Admin bei der Theme-Auswahl angezeigt.';
|
||||
}
|
||||
if ($theme->parent !== null) {
|
||||
if ($theme->parent === $theme->key) {
|
||||
$errors[] = 'parent verweist auf das Theme selbst.';
|
||||
} elseif (! isset($this->registry->all()[$theme->parent])) {
|
||||
$errors[] = "Eltern-Theme „{$theme->parent}“ ist nicht installiert.";
|
||||
}
|
||||
}
|
||||
foreach ($theme->tokens as $key => $token) {
|
||||
if (! is_array($token) || blank($token['label'] ?? null) || ! preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/', (string) ($token['default'] ?? ''))) {
|
||||
$errors[] = "Token „{$key}“ braucht label und default als Hex-Farbe (#RRGGBB).";
|
||||
}
|
||||
}
|
||||
$missing = array_diff(array_keys($this->registry->tokens(config('themes.base'))), array_keys($this->registry->tokens($theme->key)));
|
||||
if ($missing !== []) {
|
||||
$errors[] = 'Basis-Tokens fehlen in der Theme-Kette: '.implode(', ', $missing).' (die Basis-Vorlagen und Formulare nutzen sie).';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $errors
|
||||
* @param list<string> $warnings
|
||||
*/
|
||||
private function checkAssets(ThemeManifest $theme, array &$errors, array &$warnings): void
|
||||
{
|
||||
$css = $theme->assets['css'] ?? null;
|
||||
$js = $theme->assets['js'] ?? null;
|
||||
if ($css === null && $js === null) {
|
||||
if (is_dir($theme->viewsPath()) && Finder::create()->files()->name('*.blade.php')->in($theme->viewsPath())->hasResults()) {
|
||||
$errors[] = 'Eigene Vorlagen ohne eigene Assets: deren Tailwind-Klassen werden nicht gebaut – theme.css/theme.js anlegen (themes:make macht das) und in assets eintragen.';
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$folder = str_replace('\\', '/', ltrim(substr($theme->path, strlen(base_path())), '/\\'));
|
||||
if (! str_starts_with($folder, 'resources/themes/')) {
|
||||
$warnings[] = 'Theme liegt nicht unter resources/themes – vite.config.js baut seine Assets dort nicht automatisch.';
|
||||
}
|
||||
|
||||
foreach (['css' => 'theme.css', 'js' => 'theme.js'] as $type => $file) {
|
||||
$expected = "{$folder}/{$file}";
|
||||
$declared = $theme->assets[$type] ?? null;
|
||||
if ($declared === null) {
|
||||
$errors[] = "assets.{$type} fehlt: Ein Theme mit eigenen Assets ersetzt CSS und JS des Eltern-Themes vollständig – {$file} anlegen (darf das Eltern-Theme importieren).";
|
||||
} elseif ($declared !== $expected) {
|
||||
$errors[] = "assets.{$type} muss „{$expected}“ heißen – nur diese Datei baut Vite (vite.config.js).";
|
||||
} elseif (! is_file(base_path($declared))) {
|
||||
$errors[] = "{$declared} fehlt.";
|
||||
}
|
||||
}
|
||||
|
||||
$cssFile = $css !== null ? base_path($css) : null;
|
||||
if ($cssFile !== null && is_file($cssFile)) {
|
||||
$content = (string) file_get_contents($cssFile);
|
||||
$resolved = $this->withLocalImports($cssFile);
|
||||
|
||||
if (preg_match("~@import\s+['\"]\.\./[a-z0-9-]+/theme\.css['\"]~", $content)) {
|
||||
$warnings[] = 'theme.css importiert das theme.css eines anderen Themes – besser dessen theme-base.css importieren und die Quellen selbst angeben (siehe Anleitung).';
|
||||
}
|
||||
if (! str_contains($content, "@import 'tailwindcss'") && ! str_contains($content, '@import "tailwindcss"')) {
|
||||
$errors[] = "theme.css muss mit @import 'tailwindcss'; beginnen.";
|
||||
}
|
||||
foreach ($this->registry->chain($theme->key) as $ancestor) {
|
||||
$source = ThemeManifest::relativePath($theme->path, $ancestor->viewsPath());
|
||||
if ($ancestor->key !== $theme->key && ! str_contains($resolved, $source)) {
|
||||
$errors[] = "theme.css scannt die Vorlagen von „{$ancestor->key}“ nicht (@source '{$source}') – geerbte Bausteine wären ungestylt.";
|
||||
}
|
||||
}
|
||||
if (is_dir($theme->viewsPath()) && ! preg_match("~@source\s+['\"]\./views['\"]~", $content)) {
|
||||
$errors[] = "theme.css scannt die eigenen Vorlagen nicht (@source './views').";
|
||||
}
|
||||
if (! str_contains($resolved, 'views/livewire')) {
|
||||
$errors[] = "theme.css scannt die Buchungsformulare nicht (@source '".ThemeManifest::relativePath($theme->path, resource_path('views/livewire'))."').";
|
||||
}
|
||||
foreach (array_keys($this->registry->tokens($theme->key)) as $token) {
|
||||
if (! str_contains($resolved, "--color-{$token}:")) {
|
||||
$errors[] = "Token „{$token}“ ist nicht gemappt (@theme inline { --color-{$token}: var(--{$token}); }) – Klassen wie bg-{$token} fehlen.";
|
||||
}
|
||||
}
|
||||
$this->scanExternal($resolved, 'theme.css', $errors);
|
||||
}
|
||||
|
||||
$jsFile = $js !== null ? base_path($js) : null;
|
||||
if ($jsFile !== null && is_file($jsFile)) {
|
||||
$content = (string) file_get_contents($jsFile);
|
||||
if (! preg_match("~import\s+['\"]\.\./[a-z0-9-]+/theme\.js['\"]~", $content) && ! str_contains($content, 'data-rotator')) {
|
||||
$warnings[] = "theme.js importiert kein anderes Theme (import '../ostsee-licht/theme.js') – Lightbox, Suche und rollierende Angebote müssen dann selbst umgesetzt sein.";
|
||||
}
|
||||
$this->scanExternal($content, 'theme.js', $errors);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $errors
|
||||
* @param list<string> $warnings
|
||||
*/
|
||||
private function checkViews(ThemeManifest $theme, array &$errors, array &$warnings): void
|
||||
{
|
||||
if (! is_dir($theme->viewsPath())) {
|
||||
return;
|
||||
}
|
||||
|
||||
$sections = array_keys(app(SectionRegistry::class)->all());
|
||||
foreach (Finder::create()->files()->in($theme->viewsPath()) as $file) {
|
||||
$name = str_replace('\\', '/', $file->getRelativePathname());
|
||||
if (! str_ends_with($name, '.blade.php')) {
|
||||
if ($name !== '.gitkeep') {
|
||||
$warnings[] = "views/{$name}: keine Blade-Datei (wird ignoriert).";
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
$view = substr($name, 0, -strlen('.blade.php'));
|
||||
$isSection = str_starts_with($view, 'sections/');
|
||||
if ($isSection && ! in_array(substr($view, 9), $sections, true)) {
|
||||
$errors[] = "views/{$name}: unbekannter Baustein (erlaubt: ".implode(', ', $sections).').';
|
||||
} elseif (! $isSection && ! in_array($view, self::KNOWN_VIEWS, true) && ! str_starts_with($view, 'partials/')) {
|
||||
$warnings[] = "views/{$name}: wird vom System nicht aufgerufen (nur eigene Includes).";
|
||||
}
|
||||
|
||||
$content = $file->getContents();
|
||||
foreach (self::REQUIRED_MARKUP[$view] ?? [] as $needle => $reason) {
|
||||
if (str_contains($content, $needle)) {
|
||||
continue;
|
||||
}
|
||||
if ($view === 'sections/offers') {
|
||||
$warnings[] = "views/{$name}: {$reason}";
|
||||
} else {
|
||||
$errors[] = "views/{$name}: {$reason}";
|
||||
}
|
||||
}
|
||||
if ($isSection && ! str_contains($content, '$sectionId')) {
|
||||
$warnings[] = "views/{$name}: \$sectionId nicht genutzt (eindeutige IDs für aria-labelledby).";
|
||||
}
|
||||
if (preg_match('/\b(?:bg|text|border|ring|fill|stroke|from|via|to|outline|decoration|divide|shadow)-(?:slate|gray|zinc|neutral|stone|red|orange|amber|yellow|lime|green|emerald|teal|cyan|sky|blue|indigo|violet|purple|fuchsia|pink|rose)-(?:50|[1-9]00|950)\b|-\[(?:#|rgb)/', $content, $match)) {
|
||||
$errors[] = "views/{$name}: feste Farbe „{$match[0]}“ – nur Token-Klassen verwenden (bg-accent, text-muted …), sonst wirken Erscheinungsbilder nicht.";
|
||||
}
|
||||
if (preg_match('/style="[^"]*(?:#[0-9a-fA-F]{3,8}\b|rgba?\()/', $content)) {
|
||||
$errors[] = "views/{$name}: feste Farbe im style-Attribut – var(--token) verwenden.";
|
||||
}
|
||||
if (str_contains($content, '<iframe')) {
|
||||
$warnings[] = "views/{$name}: <iframe> eingebettet – Drittanbieter brauchen ein Einwilligungskonzept (DSGVO).";
|
||||
}
|
||||
$this->scanExternal($content, "views/{$name}", $errors);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $errors
|
||||
* @param list<string> $warnings
|
||||
*/
|
||||
private function checkContrast(ThemeManifest $theme, array &$errors, array &$warnings): void
|
||||
{
|
||||
$defaults = array_map(fn (array $token): string => (string) ($token['default'] ?? ''), $this->registry->tokens($theme->key));
|
||||
$variants = ['Theme-Standard' => $defaults];
|
||||
|
||||
if (Schema::hasTable('appearances')) {
|
||||
foreach (Appearance::query()->where('is_active', true)->get() as $appearance) {
|
||||
$variants["Erscheinungsbild „{$appearance->name}“"] = [...$defaults, ...array_filter($appearance->tokens ?? [], fn ($value): bool => is_string($value) && preg_match('/^#[0-9a-fA-F]{3,8}$/', $value) === 1)];
|
||||
}
|
||||
}
|
||||
|
||||
foreach ($variants as $label => $tokens) {
|
||||
foreach (self::CONTRAST_PAIRS as [$text, $background]) {
|
||||
if (! isset($tokens[$text], $tokens[$background]) || ! preg_match('/^#/', $tokens[$text]) || ! preg_match('/^#/', $tokens[$background])) {
|
||||
continue;
|
||||
}
|
||||
$ratio = self::contrast($tokens[$text], $tokens[$background]);
|
||||
if ($ratio < self::MIN_CONTRAST) {
|
||||
$message = "{$label}: Kontrast {$text} auf {$background} nur {$ratio}:1 (mind. ".self::MIN_CONTRAST.':1).';
|
||||
if ($label === 'Theme-Standard') {
|
||||
$errors[] = $message;
|
||||
} else {
|
||||
$warnings[] = $message;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The CSS file with its relative @imports (theme-base.css etc.) inlined, for checks across files.
|
||||
*/
|
||||
private function withLocalImports(string $file, int $depth = 0): string
|
||||
{
|
||||
$content = (string) file_get_contents($file);
|
||||
if ($depth > 3) {
|
||||
return $content;
|
||||
}
|
||||
|
||||
return preg_replace_callback("~@import\s+['\"](\.{1,2}/[^'\"]+\.css)['\"]\s*;~", function (array $match) use ($file, $depth): string {
|
||||
$imported = dirname($file).DIRECTORY_SEPARATOR.$match[1];
|
||||
|
||||
return is_file($imported) ? $this->withLocalImports($imported, $depth + 1) : $match[0];
|
||||
}, $content) ?? $content;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<string> $errors
|
||||
*/
|
||||
private function scanExternal(string $content, string $file, array &$errors): void
|
||||
{
|
||||
if (preg_match('~https?://(?:fonts\.googleapis|fonts\.gstatic|use\.typekit|[a-z0-9.-]*cdn[a-z0-9.-]*|unpkg\.com|cdnjs)[^\s"\')]*~i', $content, $match)) {
|
||||
$errors[] = "{$file}: externe Quelle „{$match[0]}“ – Schriften und Skripte selbst hosten (DSGVO, kein Cookie-Banner).";
|
||||
}
|
||||
if (preg_match('~<script[^>]+src=["\']https?://~i', $content)) {
|
||||
$errors[] = "{$file}: externes Skript – nicht erlaubt.";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,22 +18,28 @@ public function __construct(private ThemeRegistry $registry) {}
|
||||
public function forRequest(Request $request): Theme
|
||||
{
|
||||
$site = $this->site($request->getHost());
|
||||
$isSigned = ($request->query('vorschau') || $request->query('theme')) && $request->hasValidSignature();
|
||||
|
||||
$preview = null;
|
||||
if ($request->query('vorschau') && $request->hasValidSignature()) {
|
||||
$preview = $site->appearances()->find($request->query('vorschau'));
|
||||
$preview = $isSigned && $request->query('vorschau') ? $site->appearances()->find($request->query('vorschau')) : null;
|
||||
|
||||
// Theme preview: the site is shown with another installed theme without changing it (not saved).
|
||||
$previewTheme = $isSigned ? (string) $request->query('theme') : '';
|
||||
if ($previewTheme !== '' && isset($this->registry->all()[$previewTheme])) {
|
||||
$site = (clone $site)->setAttribute('theme', $previewTheme);
|
||||
|
||||
return $this->forSite($site, $preview, isPreview: true);
|
||||
}
|
||||
|
||||
return $this->forSite($site, $preview);
|
||||
}
|
||||
|
||||
public function forSite(Site $site, ?Appearance $preview = null): Theme
|
||||
public function forSite(Site $site, ?Appearance $preview = null, bool $isPreview = false): Theme
|
||||
{
|
||||
return new Theme(
|
||||
$this->registry,
|
||||
$site,
|
||||
$preview ?? ($site->exists ? $site->appearanceOn(today()) : null),
|
||||
isPreview: $preview !== null,
|
||||
isPreview: $isPreview || $preview !== null,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,4 +48,22 @@ public function viewsPath(): string
|
||||
{
|
||||
return $this->path.DIRECTORY_SEPARATOR.'views';
|
||||
}
|
||||
|
||||
/**
|
||||
* Relative path with forward slashes from one directory to another, as used in CSS @import/@source
|
||||
* and JS imports, e.g. "../ostsee-licht/views".
|
||||
*/
|
||||
public static function relativePath(string $fromDirectory, string $to): string
|
||||
{
|
||||
$normalise = fn (string $path): array => array_values(array_filter(explode('/', str_replace('\\', '/', realpath($path) ?: $path)), fn (string $part): bool => $part !== ''));
|
||||
$from = $normalise($fromDirectory);
|
||||
$target = $normalise($to);
|
||||
|
||||
while ($from !== [] && $target !== [] && strcasecmp($from[0], $target[0]) === 0) {
|
||||
array_shift($from);
|
||||
array_shift($target);
|
||||
}
|
||||
|
||||
return implode('/', [...array_fill(0, count($from), '..'), ...$target]) ?: '.';
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,21 @@ public function chain(string $key): array
|
||||
return array_values($chain);
|
||||
}
|
||||
|
||||
/**
|
||||
* Colour tokens of a theme including the inherited ones (base first, the theme's own definitions win).
|
||||
*
|
||||
* @return array<string, array{label: string, default: string}>
|
||||
*/
|
||||
public function tokens(string $key): array
|
||||
{
|
||||
$tokens = [];
|
||||
foreach (array_reverse($this->chain($key)) as $theme) {
|
||||
$tokens = [...$tokens, ...$theme->tokens];
|
||||
}
|
||||
|
||||
return $tokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?php
|
||||
|
||||
use App\Http\Middleware\ResolveTheme;
|
||||
use App\Http\Middleware\SecurityHeaders;
|
||||
use Illuminate\Foundation\Application;
|
||||
use Illuminate\Foundation\Configuration\Exceptions;
|
||||
use Illuminate\Foundation\Configuration\Middleware;
|
||||
@@ -14,6 +15,7 @@
|
||||
)
|
||||
->withMiddleware(function (Middleware $middleware): void {
|
||||
$middleware->web(append: [ResolveTheme::class]);
|
||||
$middleware->append(SecurityHeaders::class);
|
||||
})
|
||||
->withExceptions(function (Exceptions $exceptions): void {
|
||||
$exceptions->shouldRenderJsonWhen(
|
||||
|
||||
+11
-1
@@ -36,12 +36,22 @@
|
||||
'contract' => [
|
||||
'label' => 'Mietvertrag',
|
||||
'fields' => [
|
||||
'contract.intro' => ['label' => 'Einleitung', 'type' => 'textarea', 'default' => 'Zwischen Vermieter und Mieter wird folgender Mietvertrag über die Ferienwohnung geschlossen. Der Vertrag kommt mit der Buchungsbestätigung des Vermieters zustande.'],
|
||||
'contract.intro' => ['label' => 'Einleitung', 'type' => 'textarea', 'default' => 'Zwischen Vermieter und Mieter wird folgender Mietvertrag über die Ferienwohnung geschlossen. Der Vertrag kommt zustande, wenn der Mieter das Angebot des Vermieters annimmt.'],
|
||||
'contract.terms' => ['label' => 'Mietbedingungen', 'type' => 'richtext', 'default' => '<p><strong>[MUSTER – bitte durch Ihre geprüften Mietbedingungen ersetzen]</strong></p><ol><li>Die Wohnung darf nur von den im Vertrag genannten Personen genutzt werden.</li><li>Der Mieter behandelt die Wohnung und das Inventar pfleglich und meldet Schäden unverzüglich.</li><li>Die Kurtaxe ist nicht im Mietpreis enthalten und wird vor Ort entrichtet.</li></ol>'],
|
||||
'contract.closing' => ['label' => 'Schlusstext', 'type' => 'textarea', 'default' => 'Wir freuen uns auf Ihren Besuch und wünschen Ihnen schon jetzt einen erholsamen Aufenthalt an der Ostsee.'],
|
||||
],
|
||||
],
|
||||
|
||||
'offer' => [
|
||||
'label' => 'Angebot & Annahme',
|
||||
'fields' => [
|
||||
'offer.intro' => ['label' => 'Einleitung in der Angebots-E-Mail', 'type' => 'textarea', 'default' => 'vielen Dank für Ihre Anfrage. Gern machen wir Ihnen folgendes Angebot – den Vertragsentwurf mit allen Bedingungen finden Sie im Anhang.'],
|
||||
'offer.contract_note' => ['label' => 'Hinweis im Vertragsentwurf', 'type' => 'textarea', 'default' => 'Dies ist ein Angebot. Der Mietvertrag wird verbindlich, sobald Sie das Angebot über den Link in unserer E-Mail annehmen.'],
|
||||
'offer.accept_note' => ['label' => 'Hinweis über dem Annahme-Button', 'type' => 'textarea', 'default' => 'Mit Klick auf den Button nehmen Sie unser Angebot verbindlich an. Damit kommt der Mietvertrag zu den oben genannten Bedingungen zustande und die genannten Zahlungen werden fällig.'],
|
||||
'offer.accept_button' => ['label' => 'Beschriftung des Annahme-Buttons', 'type' => 'text', 'default' => 'Angebot zahlungspflichtig annehmen'],
|
||||
],
|
||||
],
|
||||
|
||||
'legal' => [
|
||||
'label' => 'Rechtliches',
|
||||
'fields' => [
|
||||
|
||||
@@ -46,6 +46,27 @@
|
||||
*/
|
||||
'guest_retention_years' => (int) env('FEWO_GUEST_RETENTION_YEARS', 10),
|
||||
|
||||
/*
|
||||
| Further retention periods (docs/LOESCHKONZEPT.md). The defaults are PROPOSALS – please have them
|
||||
| confirmed according to the general legal opinion (tax advisor / legal advice) and adjust here.
|
||||
*/
|
||||
// Test environments: every e-mail goes to this address only (instead of guests/landlord). Empty = normal delivery.
|
||||
'mail_redirect_to' => env('FEWO_MAIL_REDIRECT_TO'),
|
||||
|
||||
// Daily database backup (php artisan backup:database): number of dumps kept in storage/app/private/backups.
|
||||
'backup' => [
|
||||
'keep' => (int) env('FEWO_BACKUP_KEEP', 14),
|
||||
],
|
||||
|
||||
'retention' => [
|
||||
// Requests/offers that never became a binding booking: guest data anonymised after … months.
|
||||
'inquiry_months' => (int) env('FEWO_RETENTION_INQUIRY_MONTHS', 6),
|
||||
// Text excerpt of processed portal e-mails (may contain names) is removed after … days.
|
||||
'portal_email_excerpt_days' => (int) env('FEWO_RETENTION_PORTAL_EMAIL_EXCERPT_DAYS', 90),
|
||||
// Marketing attribution (UTM parameters, "how did you hear about us") is removed after … months.
|
||||
'attribution_months' => (int) env('FEWO_RETENTION_ATTRIBUTION_MONTHS', 24),
|
||||
],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Portal synchronisation
|
||||
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('special_offers', function (Blueprint $table) {
|
||||
$table->string('kind', 20)->default('rule')->after('name');
|
||||
$table->unsignedSmallInteger('max_gap_nights')->nullable()->after('max_nights');
|
||||
$table->boolean('waives_min_stay')->default(false)->after('max_gap_nights');
|
||||
$table->integer('priority')->default(0)->after('is_combinable');
|
||||
$table->boolean('is_featured')->default(false)->after('priority');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('special_offers', function (Blueprint $table) {
|
||||
$table->dropColumn(['kind', 'max_gap_nights', 'waives_min_stay', 'priority', 'is_featured']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Offers are advertised by their own rules now (OfferShowcase) instead of per appearance;
|
||||
* appearances get photos per section instead.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('appearances', function (Blueprint $table) {
|
||||
$table->dropConstrainedForeignId('featured_offer_id');
|
||||
$table->json('section_photos')->nullable()->after('hero_photo_id');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('appearances', function (Blueprint $table) {
|
||||
$table->dropColumn('section_photos');
|
||||
$table->foreignId('featured_offer_id')->nullable()->constrained('special_offers')->nullOnDelete();
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use App\Models\Page;
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Existing pages: every placed section gets its stable id (see Page::assignSectionIds).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
DB::table('pages')->orderBy('id')->each(function (object $page): void {
|
||||
$sections = json_decode((string) $page->sections, true);
|
||||
if (! is_array($sections)) {
|
||||
return;
|
||||
}
|
||||
|
||||
DB::table('pages')->where('id', $page->id)->update(['sections' => json_encode(Page::assignSectionIds($sections))]);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids are harmless when rolling back; nothing to undo.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
//
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Run the migrations.
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->string('admin_mode', 20)->nullable()->after('role');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('users', function (Blueprint $table) {
|
||||
$table->dropColumn('admin_mode');
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Booking path 1: request → offer by the landlord → acceptance by the guest (docs/KONZEPT.md §6a).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->unsignedSmallInteger('offer_version')->default(0)->after('hold_expires_at');
|
||||
$table->timestamp('offer_sent_at')->nullable()->after('offer_version');
|
||||
$table->text('offer_message')->nullable()->after('offer_sent_at');
|
||||
$table->string('offer_path')->nullable()->after('offer_message');
|
||||
$table->integer('price_adjustment')->nullable()->after('promo_code');
|
||||
$table->string('price_adjustment_label')->nullable()->after('price_adjustment');
|
||||
$table->timestamp('accepted_at')->nullable()->after('confirmed_at');
|
||||
$table->json('acceptance')->nullable()->after('accepted_at');
|
||||
$table->string('declined_by', 10)->nullable()->after('acceptance');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('bookings', function (Blueprint $table) {
|
||||
$table->dropColumn(['offer_version', 'offer_sent_at', 'offer_message', 'offer_path', 'price_adjustment', 'price_adjustment_label', 'accepted_at', 'acceptance', 'declined_by']);
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Database\Migrations\Migration;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\Schema;
|
||||
|
||||
return new class extends Migration
|
||||
{
|
||||
/**
|
||||
* Relaxations of the seasons' minimum stay (see Property::minimumStayRules / PriceCalculator).
|
||||
*/
|
||||
public function up(): void
|
||||
{
|
||||
Schema::table('properties', function (Blueprint $table) {
|
||||
$table->unsignedTinyInteger('changeover_weekday')->nullable()->after('check_out_time');
|
||||
$table->boolean('min_stay_fill_gaps')->default(true)->after('changeover_weekday');
|
||||
$table->boolean('min_stay_until_changeover')->default(false)->after('min_stay_fill_gaps');
|
||||
$table->unsignedTinyInteger('min_stay_absolute')->default(2)->after('min_stay_until_changeover');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reverse the migrations.
|
||||
*/
|
||||
public function down(): void
|
||||
{
|
||||
Schema::table('properties', function (Blueprint $table) {
|
||||
$table->dropColumn(['changeover_weekday', 'min_stay_fill_gaps', 'min_stay_until_changeover', 'min_stay_absolute']);
|
||||
});
|
||||
}
|
||||
};
|
||||
+18
-3
@@ -103,11 +103,14 @@ ## 7. Zugang zur Verwaltung (`/admin`)
|
||||
"cd test.fewo-stommer.de/current && /opt/RZphp84/bin/php-cli artisan users:create lars@stommer.com --name='Lars Stommer' --role=admin"
|
||||
```
|
||||
|
||||
Weitere Benutzer legt ein Administrator in der Verwaltung an (System › Benutzer). Rollen: `admin` (alles inkl. Benutzer), `rentals` (Vermietung), `content` (Inhalte); ohne Rolle kein Zugang.
|
||||
Weitere Benutzer legt ein Administrator in der Verwaltung an (System › Benutzer): Name, E-Mail, **Rolle** (was die Person darf) und **Ansicht** (was das Menü zeigt), Passwort. Rollen: `admin` (alles inkl. Benutzer), `rentals` (Vermietung), `content` (Inhalte); ohne Rolle kein Zugang. Festlegung 22.10.2026: Lars und Brigitte beide `admin` (dürfen alles); Brigitte mit **einfacher Ansicht** (beim Anlegen „Ansicht: Einfach“ wählen, sonst erhalten Administratoren die Expertenansicht).
|
||||
|
||||
**Ansichten:** *Einfache Ansicht* – Anfragen & Buchungen (Angebot senden, Mietvertrag, Zahlungen), Sperrzeiten, **Preise & Angebote** (Saisons, Sonderangebote/Rabattcodes, Extras), Gäste, Portal-Aufgaben, Bewertungen, Bilder. *Expertenansicht* – alle Einstellungen, die die Rolle erlaubt (Preise, Angebote, Portale, Webseite, System). Ohne Auswahl: Administratoren Experten-, alle anderen einfache Ansicht. Umschalten jederzeit über das Benutzermenü oben rechts („Zur … Ansicht wechseln“). Die Ansicht blendet nur Menüpunkte aus; Rechte regelt allein die Rolle.
|
||||
|
||||
**Passwort vergessen:** Ein Administrator vergibt unter System › Benutzer › Bearbeiten ein neues Passwort (eine Selbst-Zurücksetzung per E-Mail gibt es bewusst nicht). **Handy verloren:** dort Aktion „2FA zurücksetzen“ – die Person richtet die 2FA bei der nächsten Anmeldung neu ein.
|
||||
|
||||
**Zwei-Faktor-Anmeldung (2FA):** Filament-eigene Lösung mit Authenticator-App (TOTP, z. B. Bitwarden/Vaultwarden, Google oder Microsoft Authenticator) und Wiederherstellungscodes.
|
||||
- **Pflicht für Administratoren:** Nach der ersten Anmeldung wird man auf die Einrichtungsseite geleitet (QR-Code scannen, Code bestätigen, Wiederherstellungscodes sichern). Umgesetzt mit `App\Http\Middleware\RequireTwoFactorForAdmins`.
|
||||
- **Freiwillig für andere Rollen:** im Profil (Avatar oben rechts › Profil).
|
||||
- **Pflicht für alle Konten** (Entscheidung 22.10.2026): Nach der ersten Anmeldung wird man auf die Einrichtungsseite geleitet (QR-Code scannen, Code bestätigen, Wiederherstellungscodes sichern). Filament-Standard (`multiFactorAuthentication(isRequired: true)`).
|
||||
- Schlüssel und Codes liegen verschlüsselt (mit `APP_KEY`) in `users.app_authentication_secret` / `app_authentication_recovery_codes`.
|
||||
- **Handy verloren:** Anmeldung mit einem Wiederherstellungscode. Sind auch die weg, setzt ein Administrator mit Serverzugang die 2FA zurück:
|
||||
```bash
|
||||
@@ -117,6 +120,18 @@ ## 7. Zugang zur Verwaltung (`/admin`)
|
||||
|
||||
Lokal (nur Entwicklung, `php artisan migrate:fresh --seed`): `admin@example.com` / `password`, 2FA wird bei der ersten Anmeldung eingerichtet.
|
||||
|
||||
## 7a. Datensicherung, Löschfristen, Automationen
|
||||
|
||||
- **Datenbank-Backup:** täglich 02:30 per Scheduler (`php artisan backup:database`) als `shared/storage/app/private/backups/fewo-<datum>.sql.gz`; es bleiben die neuesten 14 (`FEWO_BACKUP_KEEP`). Wiederherstellen: Datei entpacken und mit `mysql` bzw. phpMyAdmin (Strato) einspielen.
|
||||
- **Sicherung aufs NAS / einen Rechner** (holt eine frische Datenbank-Sicherung plus Fotos und Verträge; auf dem Server wird nichts verändert):
|
||||
```bash
|
||||
bash scripts/backup-pull.sh staging /pfad/zum/nas/fewo-backup
|
||||
```
|
||||
Regelmäßig z. B. per Aufgabenplanung des NAS/PC ausführen (braucht den SSH-Schlüssel aus §4).
|
||||
- **Löschfristen** (Vorschläge, rechtlich zu bestätigen – `config/fewo.php` bzw. `.env`): Gästedaten 10 Jahre nach letztem Aufenthalt (`FEWO_GUEST_RETENTION_YEARS`), nie verbindlich gewordene Anfragen/Angebote 6 Monate (`FEWO_RETENTION_INQUIRY_MONTHS`), Textauszüge von Portal-Mails 90 Tage (`FEWO_RETENTION_PORTAL_EMAIL_EXCERPT_DAYS`), Herkunftsangaben/UTM 24 Monate (`FEWO_RETENTION_ATTRIBUTION_MONTHS`). Läuft täglich 03:00. Anonymisierung ersetzt Name, Kontaktdaten, Nachrichten, Notizen, Herkunft und Bewertungs-Anzeigenamen; Buchung, Preise und Zahlungen bleiben als Beleg.
|
||||
- **Automationen (n8n):** Token bitte als Header `Authorization: Bearer <token>` senden (landet nicht in Server-Logs); `?token=` funktioniert übergangsweise weiter.
|
||||
- **Fotos:** Beim Hochladen werden Metadaten (GPS, Kamera) aus dem Original entfernt; bestehende Fotos einmalig: `php artisan photos:strip-metadata` (`--force` bearbeitet auch bereits markierte erneut). Hinweis: bewusst mit GD – Imagick (auf Strato installiert) behält EXIF beim Speichern.
|
||||
|
||||
## 8. Bekannte Eigenheiten und Lösungen
|
||||
|
||||
| Problem | Ursache | Lösung (umgesetzt) |
|
||||
|
||||
Loaded 100 of 189 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user