diff --git a/AGENTS.md b/AGENTS.md index 16e9fbe..c9da897 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,7 +13,7 @@ # Ferienwohnung Stommer - 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/` (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 `, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request. -- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. +- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. - Deployment: `scripts/deploy.sh 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//`); 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). diff --git a/CLAUDE.md b/CLAUDE.md index 16e9fbe..c9da897 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -13,7 +13,7 @@ # Ferienwohnung Stommer - 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/` (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 `, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request. -- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for admins via `RequireTwoFactorForAdmins`. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. +- Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. - Deployment: `scripts/deploy.sh 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//`); 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). diff --git a/app/Actions/AcceptOffer.php b/app/Actions/AcceptOffer.php new file mode 100644 index 0000000..55c11f9 --- /dev/null +++ b/app/Actions/AcceptOffer.php @@ -0,0 +1,67 @@ +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(); + } + } +} diff --git a/app/Actions/AnonymizeGuests.php b/app/Actions/AnonymizeGuests.php index 8b387a8..85a6b69 100644 --- a/app/Actions/AnonymizeGuests.php +++ b/app/Actions/AnonymizeGuests.php @@ -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]); } } diff --git a/app/Actions/ConfirmBooking.php b/app/Actions/ConfirmBooking.php index a085327..e7eb6f2 100644 --- a/app/Actions/ConfirmBooking.php +++ b/app/Actions/ConfirmBooking.php @@ -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'); } diff --git a/app/Actions/CreateReservation.php b/app/Actions/CreateReservation.php index aea5f48..faad372 100644 --- a/app/Actions/CreateReservation.php +++ b/app/Actions/CreateReservation.php @@ -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 $guestData + * @return array{0: Guest, 1: list} + */ + 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. */ diff --git a/app/Actions/DeclineBooking.php b/app/Actions/DeclineBooking.php index 8b2f42d..80870eb 100644 --- a/app/Actions/DeclineBooking.php +++ b/app/Actions/DeclineBooking.php @@ -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'); } diff --git a/app/Actions/ExpireReservations.php b/app/Actions/ExpireReservations.php index 98c0541..432e6ff 100644 --- a/app/Actions/ExpireReservations.php +++ b/app/Actions/ExpireReservations.php @@ -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(); diff --git a/app/Actions/RejectOffer.php b/app/Actions/RejectOffer.php new file mode 100644 index 0000000..69c5ce7 --- /dev/null +++ b/app/Actions/RejectOffer.php @@ -0,0 +1,42 @@ +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); + } + } +} diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php new file mode 100644 index 0000000..8d23a68 --- /dev/null +++ b/app/Actions/SendOffer.php @@ -0,0 +1,120 @@ +} $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)); + } +} diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php index 1dd1d2e..e7f07fa 100644 --- a/app/Actions/SyncChannel.php +++ b/app/Actions/SyncChannel.php @@ -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', ]; diff --git a/app/Console/Commands/BackupDatabase.php b/app/Console/Commands/BackupDatabase.php new file mode 100644 index 0000000..eb7d3d4 --- /dev/null +++ b/app/Console/Commands/BackupDatabase.php @@ -0,0 +1,117 @@ +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 + */ + 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)); + } +} diff --git a/app/Console/Commands/CreateUser.php b/app/Console/Commands/CreateUser.php index 7e93e9a..5bc536b 100644 --- a/app/Console/Commands/CreateUser.php +++ b/app/Console/Commands/CreateUser.php @@ -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; } diff --git a/app/Console/Commands/StripPhotoMetadata.php b/app/Console/Commands/StripPhotoMetadata.php new file mode 100644 index 0000000..35a8173 --- /dev/null +++ b/app/Console/Commands/StripPhotoMetadata.php @@ -0,0 +1,29 @@ +where('collection_name', Photo::COLLECTION)->get() + ->filter(fn (Media $media): bool => StripImageMetadata::strip($media)) + ->count(); + + $this->info("{$cleaned} Original-Foto(s) bereinigt."); + + return self::SUCCESS; + } +} diff --git a/app/Documents/RentalContract.php b/app/Documents/RentalContract.php index 633e449..f4b8d3f 100644 --- a/app/Documents/RentalContract.php +++ b/app/Documents/RentalContract.php @@ -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; } } diff --git a/app/Enums/BookingStatus.php b/app/Enums/BookingStatus.php index e7d27f8..4c8f872 100644 --- a/app/Enums/BookingStatus.php +++ b/app/Enums/BookingStatus.php @@ -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 + */ + public static function holding(): array + { + return [self::Reserved, self::OfferSent]; + } + /** * Statuses that occupy the calendar regardless of any hold time. * diff --git a/app/Enums/QuoteLineType.php b/app/Enums/QuoteLineType.php index 37f76da..0659a95 100644 --- a/app/Enums/QuoteLineType.php +++ b/app/Enums/QuoteLineType.php @@ -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); } } diff --git a/app/Exceptions/ReservationException.php b/app/Exceptions/ReservationException.php index bbae688..76fb248 100644 --- a/app/Exceptions/ReservationException.php +++ b/app/Exceptions/ReservationException.php @@ -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."); diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index f547c56..4e979fc 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -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,80 @@ 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('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 +130,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 +144,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 +195,45 @@ protected function getHeaderActions(): array ]; } + /** + * Form data of the offer modal as SendOffer changes (euro input → cents). + * + * @param array $data + * @return array + */ + 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; diff --git a/app/Http/Controllers/ChannelController.php b/app/Http/Controllers/ChannelController.php index abe204b..2f2e75d 100644 --- a/app/Http/Controllers/ChannelController.php +++ b/app/Http/Controllers/ChannelController.php @@ -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 " (preferred – does not end up in web server logs) + * or, for older automations, as ?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); + } } diff --git a/app/Http/Controllers/OfferController.php b/app/Http/Controllers/OfferController.php new file mode 100644 index 0000000..eae6df8 --- /dev/null +++ b/app/Http/Controllers/OfferController.php @@ -0,0 +1,75 @@ +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); + } +} diff --git a/app/Http/Controllers/PageController.php b/app/Http/Controllers/PageController.php index 981d2ba..dece92b 100644 --- a/app/Http/Controllers/PageController.php +++ b/app/Http/Controllers/PageController.php @@ -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']); diff --git a/app/Http/Middleware/RequireTwoFactorForAdmins.php b/app/Http/Middleware/RequireTwoFactorForAdmins.php deleted file mode 100644 index 786a2cf..0000000 --- a/app/Http/Middleware/RequireTwoFactorForAdmins.php +++ /dev/null @@ -1,28 +0,0 @@ -user(); - - if (! $user instanceof User || ! $user->hasRole(UserRole::Admin)) { - return $next($request); - } - - return parent::handle($request, $next); - } -} diff --git a/app/Http/Middleware/SecurityHeaders.php b/app/Http/Middleware/SecurityHeaders.php new file mode 100644 index 0000000..14efc24 --- /dev/null +++ b/app/Http/Middleware/SecurityHeaders.php @@ -0,0 +1,30 @@ +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; + } +} diff --git a/app/Mail/OfferAnswered.php b/app/Mail/OfferAnswered.php new file mode 100644 index 0000000..77604d5 --- /dev/null +++ b/app/Mail/OfferAnswered.php @@ -0,0 +1,32 @@ +accepted ? 'Angebot angenommen: ' : 'Angebot abgelehnt: ').$this->booking->reference, + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.offer-answered'); + } +} diff --git a/app/Mail/OfferMade.php b/app/Mail/OfferMade.php new file mode 100644 index 0000000..95a8b26 --- /dev/null +++ b/app/Mail/OfferMade.php @@ -0,0 +1,46 @@ +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 + */ + 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')] : []; + } +} diff --git a/app/Mail/ReservationReceived.php b/app/Mail/ReservationReceived.php index 8d33c8c..05d4cd9 100644 --- a/app/Mail/ReservationReceived.php +++ b/app/Mail/ReservationReceived.php @@ -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'))], ); } diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 7e5dcf1..bfb7a89 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -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 $query * @return Builder @@ -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(); } } diff --git a/app/Models/Guest.php b/app/Models/Guest.php index f07a669..20e62fb 100644 --- a/app/Models/Guest.php +++ b/app/Models/Guest.php @@ -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', diff --git a/app/Pricing/PriceQuote.php b/app/Pricing/PriceQuote.php index 7c9959d..1febf2a 100644 --- a/app/Pricing/PriceQuote.php +++ b/app/Pricing/PriceQuote.php @@ -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. */ diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 0b38b1b..6fe6651 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -2,8 +2,11 @@ namespace App\Providers; +use App\Support\StripImageMetadata; +use Illuminate\Support\Facades\Event; use Illuminate\Support\Facades\URL; use Illuminate\Support\ServiceProvider; +use Spatie\MediaLibrary\MediaCollections\Events\MediaHasBeenAddedEvent; class AppServiceProvider extends ServiceProvider { @@ -20,6 +23,9 @@ public function register(): void */ public function boot(): void { + // 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')) { diff --git a/app/Providers/Filament/AdminPanelProvider.php b/app/Providers/Filament/AdminPanelProvider.php index a33c727..4591a74 100644 --- a/app/Providers/Filament/AdminPanelProvider.php +++ b/app/Providers/Filament/AdminPanelProvider.php @@ -3,7 +3,6 @@ namespace App\Providers\Filament; use App\Enums\AdminMode; -use App\Http\Middleware\RequireTwoFactorForAdmins; use App\Models\User; use Filament\Actions\Action; use Filament\Auth\MultiFactor\App\AppAuthentication; @@ -42,12 +41,11 @@ 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()) diff --git a/app/Support/StripImageMetadata.php b/app/Support/StripImageMetadata.php new file mode 100644 index 0000000..480240f --- /dev/null +++ b/app/Support/StripImageMetadata.php @@ -0,0 +1,43 @@ +mime_type, self::TYPES, true) || $media->getCustomProperty('metadata_stripped')) { + return false; + } + + $path = $media->getPath(); + if (! is_file($path)) { + return false; + } + + try { + Image::load($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; + } +} diff --git a/bootstrap/app.php b/bootstrap/app.php index db53fb8..bd2307c 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -1,6 +1,7 @@ withMiddleware(function (Middleware $middleware): void { $middleware->web(append: [ResolveTheme::class]); + $middleware->append(SecurityHeaders::class); }) ->withExceptions(function (Exceptions $exceptions): void { $exceptions->shouldRenderJsonWhen( diff --git a/config/content.php b/config/content.php index 33b8638..77c0ab3 100644 --- a/config/content.php +++ b/config/content.php @@ -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' => '

[MUSTER – bitte durch Ihre geprüften Mietbedingungen ersetzen]

  1. Die Wohnung darf nur von den im Vertrag genannten Personen genutzt werden.
  2. Der Mieter behandelt die Wohnung und das Inventar pfleglich und meldet Schäden unverzüglich.
  3. Die Kurtaxe ist nicht im Mietpreis enthalten und wird vor Ort entrichtet.
'], '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' => [ diff --git a/config/fewo.php b/config/fewo.php index fa20593..2c6d294 100644 --- a/config/fewo.php +++ b/config/fewo.php @@ -46,6 +46,24 @@ */ '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. + */ + // 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 diff --git a/database/migrations/2026_10_22_211911_add_offer_fields_to_bookings_table.php b/database/migrations/2026_10_22_211911_add_offer_fields_to_bookings_table.php new file mode 100644 index 0000000..f447457 --- /dev/null +++ b/database/migrations/2026_10_22_211911_add_offer_fields_to_bookings_table.php @@ -0,0 +1,36 @@ +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']); + }); + } +}; diff --git a/docs/BETRIEB.md b/docs/BETRIEB.md index 2ef8124..f1eeed8 100644 --- a/docs/BETRIEB.md +++ b/docs/BETRIEB.md @@ -110,8 +110,7 @@ ## 7. Zugang zur Verwaltung (`/admin`) **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 @@ -121,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-.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 ` 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`. + ## 8. Bekannte Eigenheiten und Lösungen | Problem | Ursache | Lösung (umgesetzt) | diff --git a/public/brand/apple-touch-icon.png b/public/brand/apple-touch-icon.png new file mode 100644 index 0000000..cbf73d0 Binary files /dev/null and b/public/brand/apple-touch-icon.png differ diff --git a/public/brand/coastal-illustration-1200.webp b/public/brand/coastal-illustration-1200.webp new file mode 100644 index 0000000..64a9951 Binary files /dev/null and b/public/brand/coastal-illustration-1200.webp differ diff --git a/public/brand/favicon.svg b/public/brand/favicon.svg new file mode 100644 index 0000000..71cf564 --- /dev/null +++ b/public/brand/favicon.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/public/brand/icon-apartment.svg b/public/brand/icon-apartment.svg new file mode 100644 index 0000000..7bb50f8 --- /dev/null +++ b/public/brand/icon-apartment.svg @@ -0,0 +1,9 @@ + + Ferienwohnung + + + + + + + diff --git a/public/brand/icon-location.svg b/public/brand/icon-location.svg new file mode 100644 index 0000000..c6a1522 --- /dev/null +++ b/public/brand/icon-location.svg @@ -0,0 +1,10 @@ + + Lage + + + + + + + + diff --git a/public/brand/icon-sea.svg b/public/brand/icon-sea.svg new file mode 100644 index 0000000..2ab8794 --- /dev/null +++ b/public/brand/icon-sea.svg @@ -0,0 +1,5 @@ + + Ostsee + + + diff --git a/public/brand/icon-terrace.svg b/public/brand/icon-terrace.svg new file mode 100644 index 0000000..4e6125f --- /dev/null +++ b/public/brand/icon-terrace.svg @@ -0,0 +1,11 @@ + + Terrasse und Strand + + + + + + + + + diff --git a/public/brand/logo-600.png b/public/brand/logo-600.png new file mode 100644 index 0000000..5c33d1e Binary files /dev/null and b/public/brand/logo-600.png differ diff --git a/public/brand/logo.svg b/public/brand/logo.svg new file mode 100644 index 0000000..9cc1a77 --- /dev/null +++ b/public/brand/logo.svg @@ -0,0 +1,20 @@ + + FeWo Stommer – Ferienwohnung in Kühlungsborn + + + + + + + + + + + + + + FeWo Stommer + + + FERIENWOHNUNG IN KÜHLUNGSBORN + diff --git a/public/brand/mark.svg b/public/brand/mark.svg new file mode 100644 index 0000000..a9dca48 --- /dev/null +++ b/public/brand/mark.svg @@ -0,0 +1,14 @@ + + FeWo Stommer + + + + + + + + + + + + diff --git a/public/brand/wave-divider.svg b/public/brand/wave-divider.svg new file mode 100644 index 0000000..15db63d --- /dev/null +++ b/public/brand/wave-divider.svg @@ -0,0 +1,9 @@ + diff --git a/resources/themes/ostsee-licht/theme-base.css b/resources/themes/ostsee-licht/theme-base.css index 300a93c..71b4c6c 100644 --- a/resources/themes/ostsee-licht/theme-base.css +++ b/resources/themes/ostsee-licht/theme-base.css @@ -30,6 +30,15 @@ @theme inline { --font-sans: 'Figtree', ui-sans-serif, system-ui, sans-serif; } +/* Brand graphics (public/brand, inlined via partials/brand): navy follows the text colour, so the logo stays + visible in dark appearances; teal, light wave and sun keep the brand colours unless a theme overrides them. */ +:root { + --brand-navy: var(--ink); + --brand-teal: #0286a2; + --brand-wave: #6dbfc2; + --brand-sun: #f2c27a; +} + @layer base { html { scroll-behavior: smooth; diff --git a/resources/themes/ostsee-licht/views/layouts/app.blade.php b/resources/themes/ostsee-licht/views/layouts/app.blade.php index 727f794..a54d041 100644 --- a/resources/themes/ostsee-licht/views/layouts/app.blade.php +++ b/resources/themes/ostsee-licht/views/layouts/app.blade.php @@ -20,6 +20,8 @@ @endisset + + @if ($theme->isPreview || ! app()->isProduction()) @endif diff --git a/resources/themes/ostsee-licht/views/partials/brand.blade.php b/resources/themes/ostsee-licht/views/partials/brand.blade.php new file mode 100644 index 0000000..14c1e9f --- /dev/null +++ b/resources/themes/ostsee-licht/views/partials/brand.blade.php @@ -0,0 +1,16 @@ +{{-- + Inline brand graphic from public/brand/.svg (mark, logo, wave-divider, icon-apartment, icon-sea, + icon-terrace, icon-location). Inline, so the colours follow the CSS variables --brand-navy/-teal/-wave/-sun + (theme-base.css maps navy to the text colour, so it stays visible in dark appearances). + Variables: $name, $class (optional), $label (optional; without it the graphic is decorative). +--}} +@php + static $brandSvgs = []; + $brandSvgs[$name] ??= is_file(public_path("brand/{$name}.svg")) ? file_get_contents(public_path("brand/{$name}.svg")) : ''; + $brandUid = 'b'.\Illuminate\Support\Str::lower(\Illuminate\Support\Str::random(6)); + $brandSvg = preg_replace(['/\s(role|aria-label)="[^"]*"/', '/.*?<\/title>/s'], '', $brandSvgs[$name]); + $brandSvg = preg_replace(['/id="([^"]+)"/', '/url\(#([^)]+)\)/'], ['id="$1-'.$brandUid.'"', 'url(#$1-'.$brandUid.')'], $brandSvg); + $brandAttributes = 'class="'.e($class ?? '').'" '.(isset($label) ? 'role="img" aria-label="'.e($label).'"' : 'aria-hidden="true" focusable="false"'); + $brandSvg = preg_replace('/<svg\s/', '<svg '.$brandAttributes.' ', $brandSvg, 1); +@endphp +{!! $brandSvg !!} diff --git a/resources/themes/ostsee-licht/views/partials/footer.blade.php b/resources/themes/ostsee-licht/views/partials/footer.blade.php index 5df684f..7a86870 100644 --- a/resources/themes/ostsee-licht/views/partials/footer.blade.php +++ b/resources/themes/ostsee-licht/views/partials/footer.blade.php @@ -1,7 +1,10 @@ -<footer class="mt-8 border-t border-line"> +<div class="mt-16 px-4" aria-hidden="true"> + @include('theme::partials.brand', ['name' => 'wave-divider', 'class' => 'mx-auto block h-auto w-full max-w-4xl']) +</div> +<footer class="border-t border-line"> <div class="mx-auto flex max-w-7xl flex-wrap justify-between gap-x-16 gap-y-6 px-4 py-14 text-sm text-muted sm:px-8"> <div> - <span class="font-display text-2xl text-ink">{{ $theme->site->name }}</span><br> + <span class="flex items-center gap-2 font-display text-2xl text-ink">@include('theme::partials.brand', ['name' => 'mark', 'class' => 'h-7 w-auto']){{ $theme->site->name }}</span> {{ $theme->property()?->address }} </div> <div> diff --git a/resources/themes/ostsee-licht/views/partials/header.blade.php b/resources/themes/ostsee-licht/views/partials/header.blade.php index f172493..f5e264b 100644 --- a/resources/themes/ostsee-licht/views/partials/header.blade.php +++ b/resources/themes/ostsee-licht/views/partials/header.blade.php @@ -1,8 +1,11 @@ <header class="relative z-20"> <div class="mx-auto flex max-w-7xl items-center justify-between gap-6 px-4 py-5 sm:px-8"> - <a href="{{ route('home') }}" class="flex flex-col leading-tight"> - <span class="font-display text-[1.875rem] font-semibold tracking-wide">{{ str($theme->site->name)->afterLast(' ') }}</span> - <span class="text-[11px] tracking-[0.24em] text-muted uppercase">Ferienwohnung · Kühlungsborn</span> + <a href="{{ route('home') }}" class="flex items-center gap-3 leading-tight" aria-label="{{ $theme->site->name }} – Startseite"> + @include('theme::partials.brand', ['name' => 'mark', 'class' => 'h-11 w-auto shrink-0 sm:h-12']) + <span class="flex flex-col"> + <span class="font-display text-[1.875rem] font-semibold tracking-wide">{{ str($theme->site->name)->afterLast(' ') }}</span> + <span class="text-[11px] tracking-[0.24em] text-muted uppercase">Ferienwohnung · Kühlungsborn</span> + </span> </a> <nav aria-label="Hauptnavigation" class="hidden lg:block"> diff --git a/resources/themes/ostsee-licht/views/partials/image.blade.php b/resources/themes/ostsee-licht/views/partials/image.blade.php index 52a63aa..02e8357 100644 --- a/resources/themes/ostsee-licht/views/partials/image.blade.php +++ b/resources/themes/ostsee-licht/views/partials/image.blade.php @@ -10,5 +10,7 @@ decoding="async" class="{{ $class ?? '' }}"> @else - <div class="{{ $class ?? '' }} flex items-center justify-center bg-line/60 text-sm text-muted" role="img" aria-label="Bild folgt">Bild folgt</div> + <div class="{{ $class ?? '' }} flex items-center justify-center bg-surface" role="img" aria-label="Bild folgt"> + <img src="{{ asset('brand/coastal-illustration-1200.webp') }}" alt="" loading="lazy" decoding="async" class="h-full max-h-full w-full object-contain p-6 opacity-90"> + </div> @endif diff --git a/resources/themes/ostsee-licht/views/sections/facts.blade.php b/resources/themes/ostsee-licht/views/sections/facts.blade.php index 8b97e12..82d8823 100644 --- a/resources/themes/ostsee-licht/views/sections/facts.blade.php +++ b/resources/themes/ostsee-licht/views/sections/facts.blade.php @@ -2,16 +2,16 @@ @if ($heading)<h2 id="{{ $sectionId }}-title" class="heading-display mb-8">{{ $heading }}</h2>@endif <ul class="reveal grid grid-cols-2 gap-6 border-y border-line lg:grid-cols-4"> @if ($property?->size_sqm) - <li class="py-7"><span class="block font-display text-[2.5rem] leading-none">{{ $property->size_sqm }} m²</span><span class="text-sm text-muted">Wohnfläche</span></li> + <li class="py-7">@include('theme::partials.brand', ['name' => 'icon-apartment', 'class' => 'mb-3 size-12'])<span class="block font-display text-[2.5rem] leading-none">{{ $property->size_sqm }} m²</span><span class="text-sm text-muted">Wohnfläche</span></li> @endif @if ($property) - <li class="py-7"><span class="block font-display text-[2.5rem] leading-none">1–{{ $property->max_guests }}</span><span class="text-sm text-muted">Gäste</span></li> + <li class="py-7">@include('theme::partials.brand', ['name' => 'icon-terrace', 'class' => 'mb-3 size-12'])<span class="block font-display text-[2.5rem] leading-none">1–{{ $property->max_guests }}</span><span class="text-sm text-muted">Gäste</span></li> @endif @if ($fromPrice) - <li class="py-7"><span class="block font-display text-[2.5rem] leading-none">ab {{ \App\Support\Money::format((int) $fromPrice) }}</span><span class="text-sm text-muted">pro Nacht</span></li> + <li class="py-7">@include('theme::partials.brand', ['name' => 'icon-sea', 'class' => 'mb-3 size-12'])<span class="block font-display text-[2.5rem] leading-none">ab {{ \App\Support\Money::format((int) $fromPrice) }}</span><span class="text-sm text-muted">pro Nacht</span></li> @endif @if ($highlights->isNotEmpty()) - <li class="py-7"><span class="block font-display text-[2.5rem] leading-none">inklusive</span><span class="text-sm text-muted">{{ $highlights->take(3)->implode(', ') }}</span></li> + <li class="py-7">@include('theme::partials.brand', ['name' => 'icon-location', 'class' => 'mb-3 size-12'])<span class="block font-display text-[2.5rem] leading-none">inklusive</span><span class="text-sm text-muted">{{ $highlights->take(3)->implode(', ') }}</span></li> @endif </ul> </section> diff --git a/resources/themes/ostsee-licht/views/sections/location.blade.php b/resources/themes/ostsee-licht/views/sections/location.blade.php index 1a0a509..b9de34c 100644 --- a/resources/themes/ostsee-licht/views/sections/location.blade.php +++ b/resources/themes/ostsee-licht/views/sections/location.blade.php @@ -5,8 +5,10 @@ <h2 id="{{ $sectionId }}-title" class="heading-display">{{ $heading }}</h2> @if ($text)<div class="mt-6 text-band-muted [&_a]:underline [&_p]:mb-4">{{ $text }}</div>@endif @if ($address) - <p class="mt-6 text-band-muted">{{ $address }}<br> - <a href="{{ $mapUrl }}" class="font-semibold text-band-ink underline" rel="noopener" target="_blank">Auf der Karte ansehen</a> + <p class="mt-6 flex items-start gap-3 text-band-muted [--brand-navy:var(--band-ink)]"> + @include('theme::partials.brand', ['name' => 'icon-location', 'class' => 'size-10 shrink-0']) + <span>{{ $address }}<br> + <a href="{{ $mapUrl }}" class="font-semibold text-band-ink underline" rel="noopener" target="_blank">Auf der Karte ansehen</a></span> </p> @endif </div> diff --git a/resources/views/livewire/booking-request.blade.php b/resources/views/livewire/booking-request.blade.php index 386f1c6..c0917bc 100644 --- a/resources/views/livewire/booking-request.blade.php +++ b/resources/views/livewire/booking-request.blade.php @@ -215,10 +215,10 @@ class="mt-1 w-full rounded-lg border-line"> @disabled(! $pricing['quote']) wire:loading.attr="disabled" class="mt-5 w-full rounded-xl bg-accent px-4 py-3 font-semibold text-accent-ink transition hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50"> - <span wire:loading.remove wire:target="submit">Termin vormerken & Angebot erhalten</span> + <span wire:loading.remove wire:target="submit">Unverbindlich anfragen</span> <span wire:loading wire:target="submit">Wird gesendet …</span> </button> - <p class="mt-2 text-center text-xs text-muted">Kostenlos und unverbindlich. Verbindlich wird die Buchung erst mit unserer Bestätigung.</p> + <p class="mt-2 text-center text-xs text-muted">Kostenlos und unverbindlich. Wir halten den Termin für Sie frei und senden Ihnen ein Angebot per E-Mail – verbindlich wird die Buchung erst, wenn Sie es annehmen.</p> </form> </section> </div> diff --git a/resources/views/mail/booking-confirmed.blade.php b/resources/views/mail/booking-confirmed.blade.php index cef70e3..02ba611 100644 --- a/resources/views/mail/booking-confirmed.blade.php +++ b/resources/views/mail/booking-confirmed.blade.php @@ -3,7 +3,11 @@ Guten Tag {{ $booking->guest->full_name }}, +@if ($booking->accepted_at) +vielen Dank – Sie haben unser Angebot am {{ $booking->accepted_at->format('d.m.Y') }} um {{ $booking->accepted_at->format('H:i') }} Uhr angenommen. Damit ist Ihre Buchung der **{{ $booking->property->name }}** verbindlich. +@else wir freuen uns, Ihre Buchung der **{{ $booking->property->name }}** verbindlich zu bestätigen. +@endif **Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif<br> **Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif<br> diff --git a/resources/views/mail/new-reservation.blade.php b/resources/views/mail/new-reservation.blade.php index 4e51215..b786c44 100644 --- a/resources/views/mail/new-reservation.blade.php +++ b/resources/views/mail/new-reservation.blade.php @@ -20,6 +20,6 @@ @endif <x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])"> -Anfrage bestätigen oder ablehnen +Angebot senden oder Anfrage ablehnen </x-mail::button> </x-mail::message> diff --git a/resources/views/mail/offer-answered.blade.php b/resources/views/mail/offer-answered.blade.php new file mode 100644 index 0000000..89d6f1b --- /dev/null +++ b/resources/views/mail/offer-answered.blade.php @@ -0,0 +1,15 @@ +<x-mail::message> +@if ($accepted) +# Angebot angenommen + +{{ $booking->guest->full_name }} hat das Angebot **{{ $booking->reference }}** ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}, {{ \App\Support\Money::format($booking->total) }}) am {{ $booking->accepted_at?->format('d.m.Y') }} um {{ $booking->accepted_at?->format('H:i') }} Uhr angenommen. Die Buchung ist verbindlich; Bestätigung und Mietvertrag wurden an den Gast gesendet. +@else +# Angebot abgelehnt + +{{ $booking->guest->full_name }} hat das Angebot **{{ $booking->reference }}** ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) abgelehnt. Der Zeitraum ist im Kalender wieder frei. +@endif + +<x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])"> +Buchung öffnen +</x-mail::button> +</x-mail::message> diff --git a/resources/views/mail/offer-made.blade.php b/resources/views/mail/offer-made.blade.php new file mode 100644 index 0000000..05db821 --- /dev/null +++ b/resources/views/mail/offer-made.blade.php @@ -0,0 +1,31 @@ +<x-mail::message> +# Ihr Angebot für die {{ $booking->property->name }} + +Guten Tag {{ $booking->guest->full_name }}, + +{{ \App\Support\Content::get('offer.intro') }} + +**Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br> +**Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br> +**Personen:** {{ $booking->guests }}<br> +**Angebotsnummer:** {{ $booking->reference }} + +@include('mail.partials.quote') + +@if ($booking->offer_message) +{{ $booking->offer_message }} +@endif + +Das Angebot gilt **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr**; bis dahin halten wir den Zeitraum für Sie frei. + +<x-mail::button :url="$offerUrl"> +Angebot ansehen und annehmen +</x-mail::button> + +Auf der Angebotsseite können Sie das Angebot annehmen oder ablehnen. Erst mit Ihrer Annahme wird die Buchung verbindlich; Sie erhalten dann sofort die Buchungsbestätigung mit dem Mietvertrag. + +Bei Fragen antworten Sie einfach auf diese E-Mail oder rufen Sie uns an: {{ config('fewo.owner.phone') }} + +Herzliche Grüße<br> +{{ config('fewo.owner.name') }} +</x-mail::message> diff --git a/resources/views/mail/reservation-expired.blade.php b/resources/views/mail/reservation-expired.blade.php index d023dbd..8ae5a1b 100644 --- a/resources/views/mail/reservation-expired.blade.php +++ b/resources/views/mail/reservation-expired.blade.php @@ -1,9 +1,9 @@ <x-mail::message> -# Vormerkung abgelaufen +# {{ $booking->offer_version > 0 ? 'Angebot abgelaufen' : 'Vormerkung abgelaufen' }} -Die Anfrage **{{ $booking->reference }}** von {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) wurde nicht rechtzeitig bestätigt. Der Zeitraum ist im Kalender wieder frei. +Die Anfrage **{{ $booking->reference }}** von {{ $booking->guest->full_name }} ({{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}) {{ $booking->offer_version > 0 ? 'wurde vom Gast nicht rechtzeitig angenommen' : 'wurde nicht rechtzeitig beantwortet' }}. Der Zeitraum ist im Kalender wieder frei. -Sie können die Anfrage weiterhin bestätigen, sofern der Zeitraum noch frei ist. +Sie können weiterhin ein (neues) Angebot senden, sofern der Zeitraum noch frei ist. <x-mail::button :url="\App\Filament\Resources\Bookings\BookingResource::getUrl('view', ['record' => $booking])"> Anfrage öffnen diff --git a/resources/views/mail/reservation-received.blade.php b/resources/views/mail/reservation-received.blade.php index b309b21..5ff8e83 100644 --- a/resources/views/mail/reservation-received.blade.php +++ b/resources/views/mail/reservation-received.blade.php @@ -3,16 +3,18 @@ Guten Tag {{ $booking->guest->full_name }}, -wir haben Ihre Anfrage für die **{{ $booking->property->name }}** erhalten und den Zeitraum für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**. +wir haben Ihre unverbindliche Anfrage für die **{{ $booking->property->name }}** erhalten und den Zeitraum für Sie **bis {{ $booking->hold_expires_at->format('d.m.Y, H:i') }} Uhr vorgemerkt**. **Anreise:** {{ $booking->arrival->translatedFormat('l, d.m.Y') }}<br> **Abreise:** {{ $booking->departure->translatedFormat('l, d.m.Y') }}<br> **Personen:** {{ $booking->guests }}<br> **Anfragenummer:** {{ $booking->reference }} +**Voraussichtlicher Preis laut Preisliste:** + @include('mail.partials.quote') -Wir prüfen Ihre Anfrage und melden uns in Kürze mit der Buchungsbestätigung. Erst mit unserer Bestätigung ist die Buchung verbindlich. +Wir prüfen Ihre Anfrage und senden Ihnen in Kürze **unser Angebot** per E-Mail. Verbindlich wird die Buchung erst, wenn Sie dieses Angebot annehmen. @if ($booking->message) **Ihre Nachricht:**<br> diff --git a/resources/views/offer.blade.php b/resources/views/offer.blade.php new file mode 100644 index 0000000..0abc18e --- /dev/null +++ b/resources/views/offer.blade.php @@ -0,0 +1,93 @@ +@php($money = fn (int $cents): string => \App\Support\Money::format($cents)) +@extends('theme::layouts.app', ['title' => 'Ihr Angebot']) + +@push('head') + <meta name="robots" content="noindex"> +@endpush + +@section('content') + <div class="mx-auto max-w-3xl px-4 py-14 sm:px-8"> + <p class="eyebrow">Angebot {{ $booking->reference }}</p> + <h1 class="heading-display">{{ $booking->property->name }}</h1> + <p class="mt-2 text-muted">für {{ $booking->guest->full_name }}</p> + + @if (session('offer.success')) + <div class="mt-8 rounded border border-accent bg-surface p-5" role="status">{{ session('offer.success') }}</div> + @endif + @if (session('offer.error') || $problem) + <div class="mt-8 rounded border border-line bg-surface p-5" role="alert">{{ session('offer.error') ?? $problem }}</div> + @endif + @if (! session('offer.success') && ! $problem) + @if ($booking->status === \App\Enums\BookingStatus::Declined) + <div class="mt-8 rounded border border-line bg-surface p-5">Dieses Angebot wurde abgelehnt.</div> + @elseif (in_array($booking->status, \App\Enums\BookingStatus::occupying(), true)) + <div class="mt-8 rounded border border-accent bg-surface p-5">Dieses Angebot wurde @if ($booking->accepted_at) am {{ $booking->accepted_at->format('d.m.Y') }} @endif angenommen – Ihre Buchung ist verbindlich.</div> + @elseif ($booking->status === \App\Enums\BookingStatus::Expired) + <div class="mt-8 rounded border border-line bg-surface p-5">{{ \App\Exceptions\ReservationException::offerExpired()->getMessage() }}</div> + @endif + @endif + + <section class="mt-10 rounded bg-surface p-7" aria-labelledby="offer-stay"> + <h2 id="offer-stay" class="font-display text-2xl">Ihr Aufenthalt</h2> + <dl class="mt-4 grid grid-cols-[auto_1fr] gap-x-6 gap-y-1"> + <dt class="text-muted">Anreise</dt><dd>{{ $booking->arrival->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_in_time) ab {{ substr($booking->property->check_in_time, 0, 5) }} Uhr @endif</dd> + <dt class="text-muted">Abreise</dt><dd>{{ $booking->departure->translatedFormat('l, d.m.Y') }}@if ($booking->property->check_out_time) bis {{ substr($booking->property->check_out_time, 0, 5) }} Uhr @endif</dd> + <dt class="text-muted">Nächte</dt><dd>{{ $booking->nights() }}</dd> + <dt class="text-muted">Personen</dt><dd>{{ $booking->guests }}</dd> + @if ($booking->status === \App\Enums\BookingStatus::OfferSent) + <dt class="text-muted">Gültig bis</dt><dd>{{ $booking->hold_expires_at?->format('d.m.Y, H:i') }} Uhr</dd> + @endif + </dl> + + <h2 class="mt-8 font-display text-2xl">Preis</h2> + <table class="mt-3 w-full"> + @foreach ($booking->quote['lines'] ?? [] as $line) + <tr class="border-b border-line"><td class="py-2">{{ $line['label'] }}</td><td class="py-2 text-right whitespace-nowrap">{{ $money($line['amount']) }}</td></tr> + @endforeach + <tr class="font-semibold"><td class="pt-3">Gesamtpreis</td><td class="pt-3 text-right">{{ $money($booking->total) }}</td></tr> + </table> + <p class="mt-3 text-sm text-muted"> + @if ($booking->balance_due_on->lessThanOrEqualTo(today()->addDays(config('fewo.deposit_due_days')))) + Da die Anreise kurz bevorsteht, ist der Gesamtbetrag innerhalb von {{ config('fewo.deposit_due_days') }} Tagen nach Buchung fällig. + @else + Anzahlung {{ $money($booking->deposit) }} innerhalb von {{ config('fewo.deposit_due_days') }} Tagen nach Buchung, + Restbetrag {{ $money($booking->total - $booking->deposit) }} bis {{ $booking->balance_due_on->format('d.m.Y') }}. + @endif + Die Kurtaxe ist nicht enthalten und wird vor Ort entrichtet. + </p> + + @if ($booking->offer_message) + <p class="mt-6 rounded border border-line p-4">{{ $booking->offer_message }}</p> + @endif + + <h2 class="mt-8 font-display text-2xl">Bedingungen</h2> + <div class="prose-theme mt-3">{{ \App\Support\Content::html('contract.terms') }}</div> + @if (\App\Support\Content::get('stay.cancellation')) + <h3 class="mt-6 font-semibold">Rücktritt / Stornierung</h3> + <div class="prose-theme mt-2">{{ \App\Support\Content::html('stay.cancellation') }}</div> + @endif + <p class="mt-4 text-sm text-muted">Den vollständigen Vertragsentwurf finden Sie als PDF im Anhang unserer E-Mail.</p> + </section> + + @if ($canAnswer) + <section class="mt-8 rounded bg-surface p-7" aria-label="Angebot annehmen oder ablehnen"> + <form method="post" action="{{ $acceptUrl }}"> + @csrf + <label class="flex items-start gap-3"> + <input type="checkbox" name="terms" value="1" required class="mt-1"> + <span>Ich habe die Angaben und Bedingungen dieses Angebots gelesen.</span> + </label> + @error('terms')<p class="mt-1 text-sm" role="alert">{{ $message }}</p>@enderror + <p class="mt-4 text-sm text-muted">{{ \App\Support\Content::get('offer.accept_note') }}</p> + <button type="submit" class="btn-accent mt-4 w-full sm:w-auto">{{ \App\Support\Content::get('offer.accept_button') }}</button> + </form> + <form method="post" action="{{ $rejectUrl }}" class="mt-6 border-t border-line pt-4"> + @csrf + <button type="submit" class="text-sm text-muted underline hover:text-ink">Angebot ablehnen</button> + </form> + </section> + @endif + + <p class="mt-8 text-sm text-muted">Fragen? {{ config('fewo.owner.name') }} · {{ config('fewo.owner.phone') }} · <a class="underline" href="mailto:{{ config('fewo.owner.email') }}">{{ config('fewo.owner.email') }}</a></p> + </div> +@endsection diff --git a/resources/views/pdf/contract.blade.php b/resources/views/pdf/contract.blade.php index 1e0c852..6be8106 100644 --- a/resources/views/pdf/contract.blade.php +++ b/resources/views/pdf/contract.blade.php @@ -25,8 +25,14 @@ <body> <div class="footer">{{ config('fewo.owner.name') }} · {{ config('fewo.owner.street') }} · {{ config('fewo.owner.city') }} · {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }}</div> - <h1>Mietvertrag Ferienwohnung</h1> - <p class="muted">Buchungsnummer {{ $booking->reference }} · ausgestellt am {{ ($booking->confirmed_at ?? now())->format('d.m.Y') }}</p> + @if ($draft ?? false) + <h1>Angebot und Mietvertrag (Entwurf)</h1> + <p class="muted">Angebot {{ $booking->reference }} · Version {{ $booking->offer_version }} · erstellt am {{ ($booking->offer_sent_at ?? now())->format('d.m.Y') }} · gültig bis {{ $booking->hold_expires_at?->format('d.m.Y, H:i') }} Uhr</p> + <p><strong>{{ \App\Support\Content::get('offer.contract_note') }}</strong></p> + @else + <h1>Mietvertrag Ferienwohnung</h1> + <p class="muted">Buchungsnummer {{ $booking->reference }} · ausgestellt am {{ ($booking->confirmed_at ?? now())->format('d.m.Y') }}@if ($booking->accepted_at) · Angebot angenommen am {{ $booking->accepted_at->format('d.m.Y, H:i') }} Uhr @endif</p> + @endif <p>{{ \App\Support\Content::get('contract.intro') }}</p> diff --git a/routes/console.php b/routes/console.php index c1ffcfd..aac0c34 100644 --- a/routes/console.php +++ b/routes/console.php @@ -35,5 +35,10 @@ Schedule::call(fn (AnonymizeGuests $anonymizeGuests) => $anonymizeGuests->handle()) ->name('guests:anonymize') - ->monthlyOn(1, '03:00') + ->dailyAt('03:00') + ->withoutOverlapping(); + +Schedule::command('backup:database') + ->name('backup:database') + ->dailyAt('02:30') ->withoutOverlapping(); diff --git a/routes/web.php b/routes/web.php index 382ec17..75a280e 100644 --- a/routes/web.php +++ b/routes/web.php @@ -2,15 +2,20 @@ use App\Http\Controllers\ChannelController; use App\Http\Controllers\MarketingConsentController; +use App\Http\Controllers\OfferController; use App\Http\Controllers\PageController; use App\Models\Booking; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; use Illuminate\Support\Facades\Route; Route::middleware('signed')->group(function () { - Route::get('/bewertung/{booking}', fn (Booking $booking) => view('review', ['booking' => $booking]))->name('reviews.create'); + Route::get('/bewertung/{booking}', fn (Booking $booking) => view('review', ['booking' => $booking]))->name('reviews.create')->middleware('throttle:30,1'); Route::get('/angebote/bestaetigen/{guest}', [MarketingConsentController::class, 'confirm'])->name('marketing.confirm'); Route::get('/angebote/abmelden/{guest}', [MarketingConsentController::class, 'unsubscribe'])->name('marketing.unsubscribe'); + // Booking path 1: the guest's offer page (docs/KONZEPT.md §6a) + Route::get('/angebot/{booking}', [OfferController::class, 'show'])->name('offers.show')->middleware('throttle:30,1'); + Route::post('/angebot/{booking}/annehmen', [OfferController::class, 'accept'])->name('offers.accept')->middleware('throttle:10,1'); + Route::post('/angebot/{booking}/ablehnen', [OfferController::class, 'reject'])->name('offers.reject')->middleware('throttle:10,1'); }); Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); diff --git a/scripts/backup-pull.sh b/scripts/backup-pull.sh new file mode 100644 index 0000000..12cae38 --- /dev/null +++ b/scripts/backup-pull.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# +# Fetches a fresh backup from the server to a local folder (e.g. the NAS) – nothing is changed on the server +# except creating the new database dump. +# +# scripts/backup-pull.sh <environment> <target folder> +# +# Copies: the newest database dump (backup:database) and the uploaded files (photos, contracts) from shared/storage/app. +# Uses the same settings as scripts/deploy.sh (scripts/deploy.<environment>.env). +set -euo pipefail + +ENVIRONMENT="${1:?Umgebung angeben, z. B. production}" +TARGET="${2:?Zielordner angeben, z. B. /volume1/backup/fewo}" +ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +# shellcheck source=/dev/null +source "$ROOT/scripts/deploy.$ENVIRONMENT.env" +DEPLOY_SSH_KEY="${DEPLOY_SSH_KEY/#\~/$HOME}" +SSH=(ssh -p "${DEPLOY_PORT:-22}" -o BatchMode=yes ${DEPLOY_SSH_KEY:+-i "$DEPLOY_SSH_KEY"} "${DEPLOY_USER:+$DEPLOY_USER@}$DEPLOY_HOST") +STAMP="$(date +%Y%m%d-%H%M%S)" +mkdir -p "$TARGET/$STAMP" + +echo "▶ Datenbank sichern" +"${SSH[@]}" "cd '$DEPLOY_PATH/current' && '${DEPLOY_PHP:-/opt/RZphp84/bin/php-cli}' artisan backup:database --no-interaction" +LATEST="$("${SSH[@]}" "ls -1 '$DEPLOY_PATH/shared/storage/app/private/backups/' | sort | tail -n 1")" +"${SSH[@]}" "cat '$DEPLOY_PATH/shared/storage/app/private/backups/$LATEST'" > "$TARGET/$STAMP/$LATEST" + +echo "▶ Dateien sichern (Fotos, Verträge)" +"${SSH[@]}" "tar -czf - -C '$DEPLOY_PATH/shared/storage/app' --exclude='private/backups' ." > "$TARGET/$STAMP/files.tar.gz" + +echo "✓ Gesichert nach $TARGET/$STAMP ($(du -sh "$TARGET/$STAMP" | cut -f1))" diff --git a/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_24-1.png b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_24-1.png new file mode 100644 index 0000000..5ee3b2b Binary files /dev/null and b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_24-1.png differ diff --git a/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_43-2.png b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_43-2.png new file mode 100644 index 0000000..4e91e32 Binary files /dev/null and b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_43-2.png differ diff --git a/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_46-3.png b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_46-3.png new file mode 100644 index 0000000..98f02c1 Binary files /dev/null and b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_46-3.png differ diff --git a/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_49-4.png b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_49-4.png new file mode 100644 index 0000000..3fbf878 Binary files /dev/null and b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_49-4.png differ diff --git a/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_50-5.png b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_50-5.png new file mode 100644 index 0000000..d651f72 Binary files /dev/null and b/styles/satz2/ChatGPT-Bild 22. Okt. 2026, 21_20_50-5.png differ diff --git a/tests/Feature/OfferWorkflowTest.php b/tests/Feature/OfferWorkflowTest.php new file mode 100644 index 0000000..91551ef --- /dev/null +++ b/tests/Feature/OfferWorkflowTest.php @@ -0,0 +1,191 @@ +<?php + +namespace Tests\Feature; + +use App\Actions\ExpireReservations; +use App\Actions\SendOffer; +use App\Availability\AvailabilityChecker; +use App\Enums\BookingStatus; +use App\Enums\QuoteLineType; +use App\Filament\Resources\Bookings\Pages\ViewBooking; +use App\Mail\BookingConfirmed; +use App\Mail\OfferAnswered; +use App\Mail\OfferMade; +use App\Models\Booking; +use App\Models\Property; +use App\Models\SpecialOffer; +use App\Models\User; +use Carbon\CarbonImmutable; +use Database\Seeders\PropertySeeder; +use Database\Seeders\SiteSeeder; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Storage; +use Illuminate\Support\Facades\URL; +use Livewire\Livewire; +use Tests\TestCase; + +class OfferWorkflowTest extends TestCase +{ + use RefreshDatabase; + + private Property $property; + + private Booking $booking; + + protected function setUp(): void + { + parent::setUp(); + + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + $this->seed([PropertySeeder::class, SiteSeeder::class]); + $this->property = Property::sole(); + Mail::fake(); + Storage::fake('local'); + $this->withoutVite(); + + $this->booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create([ + 'arrival' => '2026-11-07', + 'departure' => '2026-11-10', + 'guests' => 2, + ]); + } + + public function test_offer_recalculates_the_price_with_adjustment_and_promo_code_and_updates_the_guest(): void + { + SpecialOffer::factory()->for($this->property)->create(['name' => 'Stammgast', 'code' => 'OSTSEE', 'discount_value' => 10]); + + $offer = app(SendOffer::class)->handle($this->booking, [ + 'departure' => '2026-11-11', + 'promo_code' => 'ostsee', + 'price_adjustment' => -2000, + 'price_adjustment_label' => 'Nachlass für Wiederkehrer', + 'valid_until' => '2026-10-25 18:00', + 'offer_message' => 'Wir freuen uns auf Sie!', + 'guest' => ['first_name' => 'Erika', 'last_name' => 'Musterfrau', 'street' => 'Seeweg 1', 'postal_code' => '18225', 'city' => 'Kühlungsborn'], + ]); + + $lines = collect($offer->quote['lines']); + $this->assertSame(BookingStatus::OfferSent, $offer->status); + $this->assertSame([1, '2026-11-11', 'ostsee', -2000], [$offer->offer_version, $offer->departure->toDateString(), $offer->promo_code, $offer->price_adjustment]); + $this->assertSame('2026-10-25 18:00', $offer->hold_expires_at->format('Y-m-d H:i')); + $this->assertTrue($lines->contains(fn (array $line): bool => $line['label'] === 'Stammgast' && $line['amount'] < 0)); + $this->assertTrue($lines->contains(fn (array $line): bool => $line['type'] === QuoteLineType::Adjustment->value && $line['amount'] === -2000 && $line['label'] === 'Nachlass für Wiederkehrer')); + $this->assertSame($lines->sum('amount'), $offer->total); + $this->assertSame(['Erika', 'Kühlungsborn'], [$offer->guest->first_name, $offer->guest->city]); + Storage::disk('local')->assertExists($offer->offer_path); + Mail::assertSent(OfferMade::class, fn (OfferMade $mail): bool => $mail->hasTo($offer->guest->email) && str_contains($mail->offerUrl, 'signature=')); + } + + public function test_guest_accepts_the_offer_and_the_booking_becomes_binding(): void + { + $url = $this->sendOffer(); + + $this->get($url)->assertOk()->assertSee('Angebot zahlungspflichtig annehmen')->assertSee('Gesamtpreis')->assertSee('Gesamtbetrag'); + $acceptUrl = $this->formAction($url, 'annehmen'); + + $this->post($acceptUrl, [])->assertSessionHasErrors('terms'); + $this->followingRedirects()->post($acceptUrl, ['terms' => '1'])->assertOk()->assertSee('Ihre Buchung ist verbindlich'); + + $booking = $this->booking->fresh(); + $this->assertSame(BookingStatus::Confirmed, $booking->status); + $this->assertNotNull($booking->accepted_at); + $this->assertSame(1, $booking->acceptance['offer_version']); + $this->assertSame($booking->total, $booking->acceptance['total']); + Storage::disk('local')->assertExists($booking->contract_path); + Mail::assertSent(BookingConfirmed::class); + Mail::assertSent(OfferAnswered::class, fn (OfferAnswered $mail): bool => $mail->accepted); + + $html = $this->get($url)->getContent(); + preg_match('~<main.*</main>~s', $html, $m); + dump(strip_tags($m[0] ?? substr($html, 0, 3000))); + } + + public function test_link_of_an_older_offer_version_cannot_be_used(): void + { + $oldUrl = $this->sendOffer(); + $this->sendOffer(); + + $this->get($oldUrl)->assertOk()->assertSee('aktualisiertes Angebot')->assertDontSee('Angebot zahlungspflichtig annehmen'); + $this->post(URL::temporarySignedRoute('offers.accept', now()->addDay(), ['booking' => $this->booking, 'v' => 1]), ['terms' => '1']); + + $this->assertSame(BookingStatus::OfferSent, $this->booking->fresh()->status); + } + + public function test_offer_holds_the_dates_until_it_expires(): void + { + $url = $this->sendOffer(['valid_until' => '2026-10-24 10:00']); + $availability = new AvailabilityChecker; + + $this->assertFalse($availability->isAvailable($this->property, $this->booking->arrival, $this->booking->departure)); + + $this->travelTo(CarbonImmutable::parse('2026-10-24 11:00')); + $this->assertTrue($availability->isAvailable($this->property, $this->booking->arrival, $this->booking->departure)); + $this->assertSame(1, app(ExpireReservations::class)->handle()); + $this->assertSame(BookingStatus::Expired, $this->booking->fresh()->status); + $this->get($url)->assertForbidden(); + } + + public function test_guest_declines_the_offer(): void + { + $url = $this->sendOffer(); + + $this->post($this->formAction($url, 'ablehnen'))->assertRedirect(); + + $booking = $this->booking->fresh(); + $this->assertSame([BookingStatus::Declined, 'guest'], [$booking->status, $booking->declined_by]); + $this->assertTrue((new AvailabilityChecker)->isAvailable($this->property, $booking->arrival, $booking->departure)); + Mail::assertSent(OfferAnswered::class, fn (OfferAnswered $mail): bool => ! $mail->accepted); + } + + public function test_offer_page_needs_a_valid_signature(): void + { + $this->sendOffer(); + + $this->get('/angebot/'.$this->booking->id.'?v=1')->assertForbidden(); + $this->post('/angebot/'.$this->booking->id.'/annehmen?v=1', ['terms' => '1'])->assertForbidden(); + } + + public function test_landlord_sends_the_offer_from_the_booking_page(): void + { + $this->actingAs(User::factory()->create()); + + Livewire::test(ViewBooking::class, ['record' => $this->booking->getRouteKey()]) + ->callAction('sendOffer', [ + 'arrival' => '2026-11-07', + 'departure' => '2026-11-10', + 'guests' => 2, + 'price_adjustment' => '-25.50', + 'price_adjustment_label' => 'Sonderpreis', + 'valid_until' => '2026-10-26 12:00', + 'guest' => ['first_name' => 'Max', 'last_name' => 'Muster'], + ]) + ->assertHasNoFormErrors() + ->assertNotified('Angebot gesendet'); + + $this->assertSame([BookingStatus::OfferSent, -2550], [$this->booking->fresh()->status, $this->booking->fresh()->price_adjustment]); + Mail::assertSent(OfferMade::class); + } + + /** + * @param array<string, mixed> $changes + */ + private function sendOffer(array $changes = []): string + { + $send = app(SendOffer::class); + $booking = $send->handle($this->booking->fresh(), $changes); + + return $send->offerUrl($booking); + } + + /** + * The signed form action of the offer page ("annehmen" or "ablehnen"). + */ + private function formAction(string $pageUrl, string $action): string + { + preg_match('~action="([^"]*/'.$action.'[^"]*)"~', $this->get($pageUrl)->getContent(), $match); + $this->assertNotEmpty($match, "form for {$action} not found"); + + return html_entity_decode($match[1]); + } +} diff --git a/tests/Feature/PrivacyHardeningTest.php b/tests/Feature/PrivacyHardeningTest.php new file mode 100644 index 0000000..0b533b7 --- /dev/null +++ b/tests/Feature/PrivacyHardeningTest.php @@ -0,0 +1,139 @@ +<?php + +namespace Tests\Feature; + +use App\Actions\AnonymizeGuests; +use App\Actions\CreateReservation; +use App\Enums\BookingStatus; +use App\Enums\PortalEmailStatus; +use App\Enums\PortalEmailType; +use App\Models\Booking; +use App\Models\Channel; +use App\Models\Guest; +use App\Models\Photo; +use App\Models\PortalEmail; +use App\Models\Property; +use App\Models\Review; +use App\Pricing\StayRequest; +use Carbon\CarbonImmutable; +use Database\Seeders\PropertySeeder; +use Illuminate\Foundation\Testing\RefreshDatabase; +use Illuminate\Http\UploadedFile; +use Illuminate\Support\Facades\Mail; +use Illuminate\Support\Facades\Storage; +use Tests\TestCase; + +class PrivacyHardeningTest extends TestCase +{ + use RefreshDatabase; + + protected function setUp(): void + { + parent::setUp(); + + $this->travelTo(CarbonImmutable::parse('2026-10-22 10:00')); + Mail::fake(); + } + + public function test_anonymisation_also_removes_notes_attribution_and_review_details(): void + { + $booking = Booking::factory()->create(['internal_notes' => 'ruft abends an', 'utm_source' => 'newsletter', 'offer_message' => 'Hallo Frau Muster']); + $review = Review::factory()->create(['booking_id' => $booking->id, 'display_name' => 'Erika M.', 'private_feedback' => 'Nachbar laut']); + + $booking->guest->anonymize(); + + $booking->refresh(); + $this->assertSame([null, null, null], [$booking->internal_notes, $booking->utm_source, $booking->offer_message]); + $this->assertSame(['Gast', null], [$review->fresh()->display_name, $review->fresh()->private_feedback]); + } + + public function test_guests_with_only_unbinding_requests_are_anonymised_after_the_inquiry_period(): void + { + $inquiry = Booking::factory()->create(['status' => BookingStatus::Expired, 'confirmed_at' => null]); + $customer = Booking::factory()->create(['status' => BookingStatus::Completed, 'confirmed_at' => now()]); + Guest::query()->update(['updated_at' => now()]); + Booking::query()->update(['updated_at' => now()]); + + $this->travel(7)->months(); + app(AnonymizeGuests::class)->handle(); + + $this->assertNotNull($inquiry->guest->fresh()->anonymized_at); + $this->assertNull($customer->guest->fresh()->anonymized_at); + } + + public function test_portal_mail_excerpts_and_old_attribution_are_removed_after_their_periods(): void + { + $mail = PortalEmail::query()->create(['channel_id' => Channel::factory()->create()->id, 'message_id' => 'x@portal', 'from' => 'noreply@portal.example', 'subject' => 'Neue Buchung', 'received_at' => now(), 'type' => PortalEmailType::Booking, 'status' => PortalEmailStatus::Blocked, 'excerpt' => 'Gast: Erika Musterfrau']); + $booking = Booking::factory()->create(['utm_source' => 'instagram', 'referral_source' => null]); + + $this->travel(100)->days(); + app(AnonymizeGuests::class)->handle(); + $this->assertNull($mail->fresh()->excerpt); + $this->assertSame('instagram', $booking->fresh()->utm_source); + + $this->travel(2)->years(); + app(AnonymizeGuests::class)->handle(); + $this->assertNull($booking->fresh()->utm_source); + } + + public function test_request_with_a_known_email_does_not_overwrite_the_guest_file(): void + { + $this->seed(PropertySeeder::class); + $guest = Guest::factory()->create(['email' => 'erika@example.com', 'first_name' => 'Erika', 'last_name' => 'Muster', 'city' => 'Rostock', 'phone' => null]); + + $booking = app(CreateReservation::class)->handle( + Property::sole(), + new StayRequest(CarbonImmutable::parse('2026-11-07'), CarbonImmutable::parse('2026-11-10'), 2), + ['first_name' => 'Erika', 'last_name' => 'Muster', 'email' => 'Erika@Example.com', 'city' => 'Berlin', 'phone' => '0170 1'], + sendMails: false, + ); + + $guest->refresh(); + $this->assertSame($guest->id, $booking->guest_id); + $this->assertSame(['Rostock', '0170 1'], [$guest->city, $guest->phone], 'existing data stays, empty fields are completed'); + $this->assertStringContainsString('Ort: Berlin (Kartei: Rostock)', $booking->internal_notes); + } + + public function test_automation_tokens_are_accepted_as_bearer_header(): void + { + config(['fewo.scheduler_token' => 'geheim']); + + $this->get('/automation/scheduler', ['Authorization' => 'Bearer geheim'])->assertOk(); + $this->get('/automation/scheduler', ['Authorization' => 'Bearer falsch'])->assertNotFound(); + } + + public function test_responses_carry_security_headers(): void + { + $this->get('/up') + ->assertHeader('X-Content-Type-Options', 'nosniff') + ->assertHeader('X-Frame-Options', 'SAMEORIGIN') + ->assertHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + } + + public function test_uploaded_photo_originals_are_stripped_of_metadata(): void + { + Storage::fake('public'); + $photo = Photo::factory()->create(); + + $media = $photo->addMedia(UploadedFile::fake()->image('drohne.jpg', 1200, 800))->toMediaCollection(Photo::COLLECTION); + + $this->assertTrue($media->fresh()->getCustomProperty('metadata_stripped')); + $this->artisan('photos:strip-metadata')->expectsOutputToContain('0 Original-Foto(s) bereinigt.')->assertSuccessful(); + } + + public function test_database_backup_is_written_and_rotated(): void + { + Storage::fake('local'); + Guest::factory()->create(['last_name' => "O'Brien"]); + + $this->artisan('backup:database', ['--keep' => 1])->assertSuccessful(); + $this->travel(1)->minutes(); + $this->artisan('backup:database', ['--keep' => 1])->assertSuccessful(); + + $files = Storage::disk('local')->files('backups'); + $this->assertCount(1, $files); + $dump = gzdecode(Storage::disk('local')->get($files[0])); + $this->assertStringContainsString('CREATE TABLE "guests"', $dump); + $this->assertStringContainsString("O''Brien", $dump); + } +} diff --git a/tests/Feature/TwoFactorAuthenticationTest.php b/tests/Feature/TwoFactorAuthenticationTest.php index 18f0785..403c642 100644 --- a/tests/Feature/TwoFactorAuthenticationTest.php +++ b/tests/Feature/TwoFactorAuthenticationTest.php @@ -31,11 +31,12 @@ public function test_admin_with_two_factor_enters_the_admin(): void $this->get(BookingResource::getUrl('index'))->assertOk(); } - public function test_other_roles_may_work_without_two_factor(): void + public function test_every_role_must_set_up_two_factor(): void { $this->actingAs(User::factory()->role(UserRole::Rentals)->withoutTwoFactor()->create()); - $this->get(BookingResource::getUrl('index'))->assertOk(); + $this->get(BookingResource::getUrl('index')) + ->assertRedirect(Filament::getPanel('admin')->getSetUpRequiredMultiFactorAuthenticationUrl()); } public function test_two_factor_secret_is_stored_encrypted(): void