diff --git a/app/Actions/CancelBookingByGuest.php b/app/Actions/CancelBookingByGuest.php new file mode 100644 index 0000000..3e2fb9b --- /dev/null +++ b/app/Actions/CancelBookingByGuest.php @@ -0,0 +1,98 @@ +property; + $freeUntil = $booking->arrival->subDays($property->free_cancellation_days); + + return match ($property->cancellation_mode) { + CancellationMode::Instant => CancellationMode::Instant, + CancellationMode::InstantWhenFree => today()->lessThanOrEqualTo($freeUntil) ? CancellationMode::Instant : CancellationMode::Request, + default => CancellationMode::Request, + }; + } + + /** + * @return CancellationMode|null what happened (Instant = cancelled, Request = request recorded); null when it had happened before + * + * @throws ReservationException + */ + public function handle(Booking $booking, ?string $message = null): ?CancellationMode + { + $outcome = DB::transaction(function () use ($booking, $message): ?CancellationMode { + $booking->lockForTransition(); + + $alreadyAsked = BookingTask::query()->where('booking_id', $booking->id)->where('kind', BookingTaskKind::CancellationRequest)->exists(); + if ($booking->status === BookingStatus::Cancelled || $alreadyAsked) { + return null; + } + if (! in_array($booking->status, BookingStatus::occupying(), true) || $booking->arrival->isPast()) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'storniert'); + } + + $mode = $this->modeFor($booking); + if ($mode === CancellationMode::Instant) { + $booking->update(['status' => BookingStatus::Cancelled, 'cancelled_at' => now()]); + } + BookingTask::query()->create([ + 'booking_id' => $booking->id, + 'kind' => BookingTaskKind::CancellationRequest, + 'status' => BookingTaskStatus::Open, + 'note' => trim(($mode === CancellationMode::Instant ? 'Vom Gast storniert – bitte Stornokosten und Rückzahlung prüfen. ' : '').($message ?? '')) ?: null, + ]); + + return $mode; + }); + + if ($outcome !== null) { + $this->notify($booking, $outcome); + } + + return $outcome; + } + + private function notify(Booking $booking, CancellationMode $mode): void + { + $booking->loadMissing(['guest', 'property']); + $cancelled = $mode === CancellationMode::Instant; + + $sends = [ + fn () => Mail::to(Settings::notificationRecipients())->send(new CancellationRequested($booking, $cancelled)), + fn () => $booking->guest?->email ? Mail::to($booking->guest->email, $booking->guest->full_name)->send(new BookingCancelled($booking, $cancelled)) : null, + ]; + foreach ($sends as $send) { + try { + $send(); + } catch (Throwable $exception) { + Log::warning('Stornomitteilung nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + } + } +} diff --git a/app/Actions/ReleaseReservation.php b/app/Actions/ReleaseReservation.php new file mode 100644 index 0000000..f782e47 --- /dev/null +++ b/app/Actions/ReleaseReservation.php @@ -0,0 +1,53 @@ +lockForTransition(); + + if ($booking->status === BookingStatus::Declined && $booking->declined_by === 'guest') { + return false; + } + if (! in_array($booking->status, BookingStatus::holding(), true)) { + throw ReservationException::invalidTransition($booking->status->getLabel(), 'freigegeben'); + } + + $booking->update(['status' => BookingStatus::Declined, 'declined_by' => 'guest', 'hold_expires_at' => null]); + + return true; + }); + + if ($released) { + try { + Mail::to(Settings::notificationRecipients())->send(new OfferAnswered($booking, accepted: false)); + } catch (Throwable $exception) { + Log::warning('Meldung über Freigabe nicht zugestellt', ['booking' => $booking->id, 'exception' => $exception::class]); + } + } + + return $released; + } +} diff --git a/app/Actions/SendBookingReminders.php b/app/Actions/SendBookingReminders.php index f5ea022..af36055 100644 --- a/app/Actions/SendBookingReminders.php +++ b/app/Actions/SendBookingReminders.php @@ -3,22 +3,27 @@ namespace App\Actions; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; +use App\Enums\BookingTaskStatus; use App\Mail\ArrivalInformation; -use App\Mail\PaymentReminder; use App\Models\Booking; +use App\Models\BookingTask; use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Collection; use Illuminate\Support\Facades\Mail; /** - * Daily booking workflow: payment requests and reminders, arrival information, completion after departure. - * Every message is sent at most once per booking. + * Daily booking workflow. Payments are never chased automatically: due payments become tasks for the landlord + * (BookingTask, once per booking and kind) who checks the payment and sends the reminder on a click + * ({@see SendPaymentReminder}). Only the arrival information goes out by itself, once per booking, the configured + * number of days before arrival. Completion after departure. */ class SendBookingReminders { private const BALANCE_REQUEST_DAYS_BEFORE = 7; - private const ARRIVAL_INFO_DAYS_BEFORE = 7; + /** Upper bound of the per-property setting; the property decides the actual day. */ + private const ARRIVAL_INFO_MAX_DAYS_BEFORE = 14; /** * @return array{deposit_overdue: int, balance_request: int, balance_overdue: int, arrival_info: int, completed: int} @@ -33,7 +38,7 @@ public function handle(): array ->whereNull('deposit_reminded_at') ->whereDate('deposit_due_on', '<', $today)) ->filter(fn (Booking $booking): bool => $booking->openDeposit() > 0); - $this->remind($depositOverdue, PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'); + $depositTasks = $this->createTasks($depositOverdue, BookingTaskKind::DepositReminder, fn (Booking $booking) => $booking->deposit_due_on); $balanceRequest = $this->bookings(fn (Builder $query) => $query ->whereIn('status', $unpaid) @@ -41,20 +46,21 @@ public function handle(): array ->whereDate('balance_due_on', '>=', $today) ->whereDate('balance_due_on', '<=', $today->copy()->addDays(self::BALANCE_REQUEST_DAYS_BEFORE))) ->filter(fn (Booking $booking): bool => ! $booking->requiresFullPayment() && $booking->openAmount() > 0 && $booking->status === BookingStatus::DepositPaid); - $this->remind($balanceRequest, PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'); + $requestTasks = $this->createTasks($balanceRequest, BookingTaskKind::BalanceRequest, fn (Booking $booking) => $booking->balance_due_on); $balanceOverdue = $this->bookings(fn (Builder $query) => $query ->whereIn('status', $unpaid) ->whereNull('balance_reminded_at') ->whereDate('balance_due_on', '<', $today)) ->filter(fn (Booking $booking): bool => $booking->openAmount() > 0 && ($booking->status === BookingStatus::DepositPaid || $booking->requiresFullPayment())); - $this->remind($balanceOverdue, PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'); + $overdueTasks = $this->createTasks($balanceOverdue, BookingTaskKind::BalanceReminder, fn (Booking $booking) => $booking->balance_due_on); $arrivals = $this->bookings(fn (Builder $query) => $query ->whereIn('status', BookingStatus::occupying()) ->whereNull('arrival_info_sent_at') ->whereDate('arrival', '>=', $today) - ->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_DAYS_BEFORE))); + ->whereDate('arrival', '<=', $today->copy()->addDays(self::ARRIVAL_INFO_MAX_DAYS_BEFORE))) + ->filter(fn (Booking $booking): bool => $booking->arrival->lessThanOrEqualTo($today->copy()->addDays($booking->property->arrival_info_days_before))); foreach ($arrivals as $booking) { Mail::to($booking->guest->email, $booking->guest->full_name)->send(new ArrivalInformation($booking)); $booking->update(['arrival_info_sent_at' => now()]); @@ -67,9 +73,9 @@ public function handle(): array $completed->each->update(['status' => BookingStatus::Completed]); return [ - 'deposit_overdue' => $depositOverdue->count(), - 'balance_request' => $balanceRequest->count(), - 'balance_overdue' => $balanceOverdue->count(), + 'deposit_overdue' => $depositTasks, + 'balance_request' => $requestTasks, + 'balance_overdue' => $overdueTasks, 'arrival_info' => $arrivals->count(), 'completed' => $completed->count(), ]; @@ -81,7 +87,7 @@ public function handle(): array */ private function bookings(callable $constraints): Collection { - return $constraints(Booking::query()->with(['guest', 'property', 'payments'])) + return $constraints(Booking::query()->with(['guest', 'property', 'payments', 'importChannel', 'originChannel'])) ->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', '')) ->get() ->toBase(); @@ -89,12 +95,20 @@ private function bookings(callable $constraints): Collection /** * @param Collection $bookings + * @param callable(Booking): mixed $dueOn + * @return int the number of tasks created now */ - private function remind(Collection $bookings, string $kind, string $sentAtColumn): void + private function createTasks(Collection $bookings, BookingTaskKind $kind, callable $dueOn): int { - foreach ($bookings as $booking) { - Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind)); - $booking->update([$sentAtColumn => now()]); + $created = 0; + foreach ($bookings->filter(fn (Booking $booking): bool => $booking->wantsPaymentTasks()) as $booking) { + $task = BookingTask::query()->firstOrCreate( + ['booking_id' => $booking->id, 'kind' => $kind], + ['status' => BookingTaskStatus::Open, 'due_on' => $dueOn($booking)], + ); + $created += $task->wasRecentlyCreated ? 1 : 0; } + + return $created; } } diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index f943eb6..013f190 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -12,6 +12,7 @@ use App\Filament\Resources\Bookings\BookingResource; use App\Mail\OfferMade; use App\Models\Booking; +use App\Models\ContractTemplate; use App\Pricing\PriceCalculator; use App\Pricing\PriceQuote; use App\Pricing\QuoteException; @@ -42,7 +43,7 @@ public function __construct( ) {} /** - * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, guest?: array} $changes + * @param array{arrival?: string, departure?: string, guests?: int, promo_code?: ?string, price_adjustment?: ?int, price_adjustment_label?: ?string, valid_until?: ?string, offer_message?: ?string, contract_template_id?: int|string|null, guest?: array} $changes * * @throws QuoteException * @throws ReservationException @@ -97,7 +98,7 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t 'offer_version' => $booking->offer_version + 1, 'offer_sent_at' => now(), 'offer_message' => $changes['offer_message'] ?? null, - 'offer_terms' => OfferTerms::capture(), + 'offer_terms' => OfferTerms::capture($this->templateFor($booking, $changes)), ]); $booking->refresh(); $booking->update(['offer_hash' => OfferTerms::hash($booking)]); @@ -113,6 +114,20 @@ public function handle(Booking $booking, array $changes = [], bool $sendMail = t return $booking; } + /** + * The contract template of this offer: chosen explicitly, else the portal's default, else the property's. + * + * @param array $changes + */ + private function templateFor(Booking $booking, array $changes): ?ContractTemplate + { + $id = filled($changes['contract_template_id'] ?? null) + ? (int) $changes['contract_template_id'] + : ($booking->importChannel ?? $booking->originChannel)?->contract_template_id ?? $booking->property->contract_template_id; + + return $id ? ContractTemplate::query()->find($id) : null; + } + /** * Sends the offer mail. The offer is already saved (and its validity runs), so a failing mail server is * recorded in the admin inbox and reported to the caller instead of being lost. diff --git a/app/Actions/SendPaymentReminder.php b/app/Actions/SendPaymentReminder.php new file mode 100644 index 0000000..cc0eefa --- /dev/null +++ b/app/Actions/SendPaymentReminder.php @@ -0,0 +1,39 @@ +kind->reminder(); + $booking = $task->booking->loadMissing(['guest', 'property', 'payments']); + + if ($reminder === null) { + throw new ReservationException('Zu dieser Aufgabe gibt es keine Zahlungs-E-Mail.'); + } + if (blank($booking->guest?->email)) { + throw new ReservationException('Der Gast hat keine E-Mail-Adresse.'); + } + if ($booking->openAmount() <= 0) { + throw new ReservationException('Die Buchung ist bereits vollständig bezahlt.'); + } + + [$kind, $column] = $reminder; + Mail::to($booking->guest->email, $booking->guest->full_name)->send(new PaymentReminder($booking, $kind)); + $booking->update([$column => now()]); + $task->complete($by); + } +} diff --git a/app/Documents/OfferTerms.php b/app/Documents/OfferTerms.php index 23f7d15..a72c582 100644 --- a/app/Documents/OfferTerms.php +++ b/app/Documents/OfferTerms.php @@ -3,6 +3,7 @@ namespace App\Documents; use App\Models\Booking; +use App\Models\ContractTemplate; use App\Support\Content; use Filament\Forms\Components\RichEditor\RichContentRenderer; use Illuminate\Support\HtmlString; @@ -28,13 +29,16 @@ class OfferTerms ]; /** - * @return array{captured_at: string, texts: array, deposit_due_days: int, owner: array, bank: array} + * @return array{captured_at: string, template: ?array{id: int, name: string, version: int}, texts: array, deposit_due_days: int, owner: array, bank: array} */ - public static function capture(): array + public static function capture(?ContractTemplate $template = null): array { + $overrides = $template?->overrides() ?? []; + return [ 'captured_at' => now()->toIso8601String(), - 'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => Content::get($key)])->all(), + 'template' => $template ? ['id' => $template->id, 'name' => $template->name, 'version' => $template->version] : null, + 'texts' => collect(self::TEXT_KEYS)->mapWithKeys(fn (string $key): array => [$key => $overrides[$key] ?? Content::get($key)])->all(), 'deposit_due_days' => (int) config('fewo.deposit_due_days'), 'owner' => (array) config('fewo.owner'), 'bank' => (array) config('fewo.bank'), diff --git a/app/Documents/RentalContract.php b/app/Documents/RentalContract.php index fc0c268..b04508c 100644 --- a/app/Documents/RentalContract.php +++ b/app/Documents/RentalContract.php @@ -28,12 +28,18 @@ public function generate(Booking $booking, bool $draft = false): string // fetching anything over the network. Each website has its own (A14). $logo = $booking->website()?->brandPath(Site::BRAND_DOCUMENT_LOGO); - Storage::disk(self::DISK)->put($path, Pdf::loadView('pdf.contract', [ + // The final contract is a document of record: once stored it is never rewritten (confirmation resends reuse it). + if (! $draft && $booking->contract_path !== null && Storage::disk(self::DISK)->exists($booking->contract_path)) { + return $booking->contract_path; + } + + $pdf = Pdf::loadView('pdf.contract', [ 'booking' => $booking, 'draft' => $draft, 'logo' => $logo, - ])->setPaper('a4')->output()); - $booking->update([$draft ? 'offer_path' : 'contract_path' => $path]); + ])->setPaper('a4')->output(); + Storage::disk(self::DISK)->put($path, $pdf); + $booking->update([$draft ? 'offer_path' : 'contract_path' => $path, $draft ? 'offer_pdf_sha256' : 'contract_pdf_sha256' => hash('sha256', $pdf)]); return $path; } diff --git a/app/Enums/AdminMode.php b/app/Enums/AdminMode.php index 7d42518..1b46276 100644 --- a/app/Enums/AdminMode.php +++ b/app/Enums/AdminMode.php @@ -6,6 +6,7 @@ use App\Filament\Pages\PricesAndOffers; use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource; use App\Filament\Resources\Bookings\BookingResource; +use App\Filament\Resources\BookingTasks\BookingTaskResource; use App\Filament\Resources\Channels\ChannelResource; use App\Filament\Resources\ChannelTasks\ChannelTaskResource; use App\Filament\Resources\Guests\GuestResource; @@ -37,6 +38,7 @@ enum AdminMode: string implements HasDescription, HasLabel PricesAndOffers::class, GuestResource::class, ChannelTaskResource::class, + BookingTaskResource::class, ChannelResource::class, ReviewResource::class, PhotoResource::class, diff --git a/app/Enums/BookingTaskKind.php b/app/Enums/BookingTaskKind.php new file mode 100644 index 0000000..8c51362 --- /dev/null +++ b/app/Enums/BookingTaskKind.php @@ -0,0 +1,48 @@ + 'Anzahlung überfällig – anmahnen', + self::BalanceRequest => 'Restzahlung bald fällig – anfordern', + self::BalanceReminder => 'Restzahlung überfällig – anmahnen', + self::CancellationRequest => 'Stornierungswunsch des Gastes', + }; + } + + public function isPayment(): bool + { + return $this !== self::CancellationRequest; + } + + /** + * The mail kind (App\Mail\PaymentReminder) and the booking column that records its dispatch. + * + * @return array{0: string, 1: string}|null + */ + public function reminder(): ?array + { + return match ($this) { + self::DepositReminder => [PaymentReminder::DEPOSIT_OVERDUE, 'deposit_reminded_at'], + self::BalanceRequest => [PaymentReminder::BALANCE_REQUEST, 'balance_requested_at'], + self::BalanceReminder => [PaymentReminder::BALANCE_OVERDUE, 'balance_reminded_at'], + self::CancellationRequest => null, + }; + } +} diff --git a/app/Enums/BookingTaskStatus.php b/app/Enums/BookingTaskStatus.php new file mode 100644 index 0000000..c04ba5b --- /dev/null +++ b/app/Enums/BookingTaskStatus.php @@ -0,0 +1,31 @@ + 'Offen', + self::Done => 'Erledigt', + self::Dismissed => 'Verworfen', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Open => 'warning', + self::Done => 'success', + self::Dismissed => 'gray', + }; + } +} diff --git a/app/Enums/CancellationMode.php b/app/Enums/CancellationMode.php new file mode 100644 index 0000000..76a21c8 --- /dev/null +++ b/app/Enums/CancellationMode.php @@ -0,0 +1,29 @@ + 'Nur Stornierungswunsch – ich entscheide', + self::Instant => 'Sofort stornieren (Ein-Klick)', + self::InstantWhenFree => 'Sofort stornieren bis zur Frist der kostenfreien Stornierung, danach Wunsch', + }; + } +} diff --git a/app/Enums/DigestSection.php b/app/Enums/DigestSection.php index 06e460c..f823dd7 100644 --- a/app/Enums/DigestSection.php +++ b/app/Enums/DigestSection.php @@ -25,7 +25,7 @@ public function getLabel(): string self::Requests => 'Offene Anfragen und Angebote', self::News => 'Neu seit der letzten Übersicht', self::Stays => 'An- und Abreisen', - self::Payments => 'Überfällige Zahlungen', + self::Payments => 'Zahlungsaufgaben und Gästewünsche', self::Portals => 'Portale: Aufgaben und Klärungsfälle', self::Reviews => 'Bewertungen zur Freigabe', }; @@ -38,7 +38,7 @@ public function getDescription(): string self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist', self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen', self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage', - self::Payments => 'Anzahlungen und Restzahlungen nach Fälligkeit', + self::Payments => 'Offene Aufgaben: fällige Zahlungen (nur wo Sie selbst mahnen) und Stornierungswünsche', self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler', self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind', }; diff --git a/app/Filament/Resources/BookingTasks/BookingTaskResource.php b/app/Filament/Resources/BookingTasks/BookingTaskResource.php new file mode 100644 index 0000000..2c3697a --- /dev/null +++ b/app/Filament/Resources/BookingTasks/BookingTaskResource.php @@ -0,0 +1,59 @@ +open()->count(); + + return $open > 0 ? (string) $open : null; + } + + public static function getNavigationBadgeColor(): string + { + return 'warning'; + } + + public static function getPages(): array + { + return [ + 'index' => ListBookingTasks::route('/'), + ]; + } +} diff --git a/app/Filament/Resources/BookingTasks/Pages/ListBookingTasks.php b/app/Filament/Resources/BookingTasks/Pages/ListBookingTasks.php new file mode 100644 index 0000000..dd3bde5 --- /dev/null +++ b/app/Filament/Resources/BookingTasks/Pages/ListBookingTasks.php @@ -0,0 +1,21 @@ +whereHas('booking', fn (Builder $booking) => $booking->where('property_id', $property->id)); + } +} diff --git a/app/Filament/Resources/BookingTasks/Tables/BookingTasksTable.php b/app/Filament/Resources/BookingTasks/Tables/BookingTasksTable.php new file mode 100644 index 0000000..084c33d --- /dev/null +++ b/app/Filament/Resources/BookingTasks/Tables/BookingTasksTable.php @@ -0,0 +1,80 @@ +defaultSort('created_at', 'desc') + ->description('Fällige Zahlungen und Wünsche von Gästen. Es wird nichts automatisch an Gäste gesendet: Bitte erst den Zahlungseingang prüfen, dann die Erinnerung per Klick senden oder die Aufgabe abhaken.') + ->columns([ + TextColumn::make('booking.reference')->label('Buchung')->weight('medium')->description(fn (BookingTask $record): string => $record->booking->guest?->full_name ?? ''), + TextColumn::make('kind')->label('Aufgabe')->badge(), + TextColumn::make('due_on')->label('Fällig seit')->date('d.m.Y')->placeholder('–'), + TextColumn::make('open')->label('Offen')->state(fn (BookingTask $record): string => Money::format($record->booking->openAmount())), + TextColumn::make('status')->label('Status')->badge() + ->description(fn (BookingTask $record): ?string => $record->completed_by ? "{$record->completed_by}, {$record->completed_at?->format('d.m. H:i')}" : null), + TextColumn::make('note')->label('Hinweis')->wrap()->placeholder('–'), + ]) + ->filters([ + SelectFilter::make('status')->label('Status')->options(BookingTaskStatus::class)->default(BookingTaskStatus::Open->value), + ]) + ->recordActions([ + Action::make('booking') + ->label('Buchung') + ->icon(Heroicon::OutlinedArrowTopRightOnSquare) + ->color('gray') + ->url(fn (BookingTask $record): string => BookingResource::getUrl('view', ['record' => $record->booking])), + Action::make('send') + ->label('Mail an Gast senden') + ->icon(Heroicon::OutlinedEnvelope) + ->requiresConfirmation() + ->modalDescription('Haben Sie den Zahlungseingang geprüft? Der Gast erhält die Zahlungs-E-Mail sofort.') + ->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open && $record->kind->reminder() !== null) + ->action(function (BookingTask $record, SendPaymentReminder $send): void { + try { + $send->handle($record, auth()->user()->name); + } catch (ReservationException $exception) { + Notification::make()->title('Nicht möglich')->body($exception->getMessage())->danger()->send(); + + return; + } catch (Throwable) { + Notification::make()->title('E-Mail konnte nicht gesendet werden')->body('Die Aufgabe bleibt offen.')->danger()->send(); + + return; + } + + Notification::make()->title('E-Mail gesendet')->success()->send(); + }), + Action::make('done') + ->label('Erledigt') + ->icon(Heroicon::OutlinedCheck) + ->color('success') + ->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open) + ->action(fn (BookingTask $record) => $record->complete(auth()->user()->name)), + Action::make('dismiss') + ->label('Verwerfen') + ->icon(Heroicon::OutlinedXMark) + ->color('gray') + ->requiresConfirmation() + ->visible(fn (BookingTask $record): bool => $record->status === BookingTaskStatus::Open) + ->action(fn (BookingTask $record) => $record->update(['status' => BookingTaskStatus::Dismissed])), + ]); + } +} diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index d23e125..95171a8 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -11,6 +11,7 @@ use App\Filament\Actions\AssignGuestAction; use App\Filament\Resources\Bookings\BookingResource; use App\Models\Booking; +use App\Models\ContractTemplate; use App\Pricing\PriceCalculator; use App\Pricing\QuoteException; use App\Pricing\StayRequest; @@ -20,6 +21,7 @@ use Filament\Actions\ActionGroup; use Filament\Forms\Components\DatePicker; use Filament\Forms\Components\DateTimePicker; +use Filament\Forms\Components\Select; use Filament\Forms\Components\Textarea; use Filament\Forms\Components\TextInput; use Filament\Forms\Components\Toggle; @@ -85,6 +87,13 @@ protected function getHeaderActions(): array TextInput::make('price_adjustment_label')->label('Bezeichnung')->placeholder('Nachlass / Zuschlag')->maxLength(80), Text::make(fn (Get $get): string => $this->offerPricePreview($get))->columnSpanFull(), ]), + Section::make('Vertragsvorlage')->schema([ + Select::make('contract_template_id') + ->label('Vorlage für dieses Angebot') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) + ->placeholder('Standard (Portal / Wohnung / Webseite)') + ->helperText('Die Texte werden beim Versand fest im Angebot abgelegt.'), + ]), Section::make('Gültigkeit & Nachricht')->columns(2)->schema([ DateTimePicker::make('valid_until') ->label('Angebot gültig bis') @@ -187,16 +196,6 @@ protected function getHeaderActions(): array ->visible(fn (): bool => $this->record->contract_path !== null) ->action(fn (RentalContract $contract) => response()->download($contract->absolutePath($this->record) ?? abort(404), "Mietvertrag-{$this->record->reference}.pdf")), ActionGroup::make([ - Action::make('regenerateContract') - ->label('Mietvertrag neu erzeugen') - ->icon(Heroicon::OutlinedArrowPath) - ->visible(fn (): bool => in_array($this->record->status, [...BookingStatus::occupying()], true)) - ->requiresConfirmation() - ->modalDescription('Der Vertrag wird mit den Bedingungen des angenommenen Angebots neu erstellt. Der Gast erhält ihn nicht automatisch.') - ->action(function (RentalContract $contract): void { - $contract->generate($this->record); - Notification::make()->title('Mietvertrag neu erzeugt')->success()->send(); - }), Action::make('notes') ->label('Interne Notiz bearbeiten') ->icon(Heroicon::OutlinedPencilSquare) diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index b425da4..5419f7a 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -74,7 +74,7 @@ public static function configure(Schema $schema): Schema ->visible(fn (Booking $record): bool => $record->isDirect()), TextEntry::make('offer') ->label('Angebot') - ->state(fn (Booking $record): string => 'Version '.$record->offer_version.', gesendet '.$record->offer_sent_at?->format('d.m.Y, H:i').' · Prüfsumme '.substr((string) $record->offer_hash, 0, 12)) + ->state(fn (Booking $record): string => 'Version '.$record->offer_version.', gesendet '.$record->offer_sent_at?->format('d.m.Y, H:i').' · Prüfsumme '.substr((string) $record->offer_hash, 0, 12).(isset($record->offer_terms['template']) ? ' · Vorlage '.$record->offer_terms['template']['name'].' v'.$record->offer_terms['template']['version'] : '')) ->visible(fn (Booking $record): bool => $record->offer_version > 0), TextEntry::make('accepted_at')->label('Angenommen am')->dateTime('d.m.Y, H:i:s')->visible(fn (Booking $record): bool => $record->accepted_at !== null), TextEntry::make('confirmation') diff --git a/app/Filament/Resources/Channels/Schemas/ChannelForm.php b/app/Filament/Resources/Channels/Schemas/ChannelForm.php index 3b495bb..f9bf67d 100644 --- a/app/Filament/Resources/Channels/Schemas/ChannelForm.php +++ b/app/Filament/Resources/Channels/Schemas/ChannelForm.php @@ -8,6 +8,7 @@ use App\Enums\ChannelExportMode; use App\Enums\ChannelStatus; use App\Models\Channel; +use App\Models\ContractTemplate; use App\Models\Property; use App\Support\CurrentProperty; use Filament\Forms\Components\DateTimePicker; @@ -49,7 +50,20 @@ public static function configure(Schema $schema, bool $selectProperty = false): ->maxLength(100), Select::make('status')->label('Kanalstatus')->options(ChannelStatus::class)->default(ChannelStatus::Setup)->required(), Select::make('booking_model')->label('Buchungsmodell')->options(ChannelBookingModel::class)->default(ChannelBookingModel::Mixed)->required() - ->helperText('Fachliche Einordnung; löst keine automatischen Buchungsentscheidungen aus.'), + ->helperText('„Portalbuchung“ und „Gemischt“ gelten als Sofortbuchung: automatische Angebote für diese Wohnung warten, bis das Portal unseren Kalender abgerufen hat. „Vermittlung / Anfrage“: keine Sofortbuchung.'), + Select::make('contract_template_id') + ->label('Vertragsvorlage für dieses Portal') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) + ->placeholder('Standard der Wohnung') + ->helperText('Für Angebote zu Buchungen, die über dieses Portal kommen und dessen Vorgaben (z. B. Stornofristen) entsprechen müssen.'), + Toggle::make('payment_tasks_inquiry') + ->label('Zahlungsaufgaben bei Anfragen über dieses Portal') + ->helperText('Fällige Anzahlungen/Restzahlungen erscheinen als Aufgabe (Mails an Gäste gehen nie automatisch).') + ->default(true), + Toggle::make('payment_tasks_reservation') + ->label('Zahlungsaufgaben bei Reservierungen über dieses Portal') + ->helperText('Aus, wenn das Portal das Geld einzieht und mahnt (z. B. FeWo-direkt Online-Buchung).') + ->default(false), Select::make('connector') ->label('Kalenderanbindung') ->helperText('Diese Verbindung gleicht Belegungszeiträume über iCal ab. Weitere Portalfunktionen benötigen eine eigene Anbindung.') diff --git a/app/Filament/Resources/ContractTemplates/ContractTemplateResource.php b/app/Filament/Resources/ContractTemplates/ContractTemplateResource.php new file mode 100644 index 0000000..2f84269 --- /dev/null +++ b/app/Filament/Resources/ContractTemplates/ContractTemplateResource.php @@ -0,0 +1,67 @@ +isUsed(); + } + + public static function canDelete(Model $record): bool + { + return ! $record->isUsed(); + } + + public static function getPages(): array + { + return [ + 'index' => ListContractTemplates::route('/'), + 'create' => CreateContractTemplate::route('/create'), + 'edit' => EditContractTemplate::route('/{record}/edit'), + ]; + } +} diff --git a/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php b/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php new file mode 100644 index 0000000..63cf955 --- /dev/null +++ b/app/Filament/Resources/ContractTemplates/Pages/CreateContractTemplate.php @@ -0,0 +1,24 @@ + $data + * @return array + */ + protected function mutateFormDataBeforeCreate(array $data): array + { + $data['version'] = 1; + + return $data; + } +} diff --git a/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php b/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php new file mode 100644 index 0000000..9e13660 --- /dev/null +++ b/app/Filament/Resources/ContractTemplates/Pages/EditContractTemplate.php @@ -0,0 +1,17 @@ + RichEditor::make("texts.{$field}") + ->label($label) + ->toolbarButtons([['bold', 'italic', 'link'], ['bulletList', 'orderedList']]) + ->columnSpanFull(); + + return $schema + ->components([ + TextInput::make('name')->label('Name der Vorlage')->required()->maxLength(120) + ->helperText('z. B. „Direktbuchung“ oder „Portal XY“. Versionen derselben Vorlage haben denselben Namen.'), + TextInput::make('version')->label('Version')->integer()->default(1)->disabled()->dehydrated(false) + ->helperText('Neue Versionen entstehen über „Neue Version“ in der Liste. Eine Vorlage, die in einem Angebot verwendet wurde, kann nicht mehr geändert werden.'), + Section::make('Texte dieser Vorlage') + ->description('Nur ausgefüllte Felder ersetzen die Texte der Webseite (Texte › Aufenthalt / Vertrag); leere Felder übernehmen den Webseitentext. Beim Versand des Angebots wird eine Kopie fest abgelegt.') + ->columnSpanFull() + ->schema([ + $editor('terms', 'Mietbedingungen'), + $editor('cancellation', 'Rücktritt / Stornierung'), + $editor('house_rules', 'Hausordnung'), + Textarea::make('texts.intro')->label('Vertragseinleitung')->rows(3)->columnSpanFull(), + Textarea::make('texts.closing')->label('Vertragsschluss')->rows(3)->columnSpanFull(), + Textarea::make('texts.contract_note')->label('Hinweis im Angebots-PDF')->rows(3)->columnSpanFull(), + ]), + Textarea::make('notes')->label('Interne Notiz')->rows(2)->columnSpanFull(), + ]); + } +} diff --git a/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php b/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php new file mode 100644 index 0000000..3fa8bb4 --- /dev/null +++ b/app/Filament/Resources/ContractTemplates/Tables/ContractTemplatesTable.php @@ -0,0 +1,41 @@ +defaultSort('name') + ->columns([ + TextColumn::make('name')->label('Vorlage')->searchable()->weight('medium'), + TextColumn::make('version')->label('Version')->badge(), + IconColumn::make('used')->label('In Angeboten verwendet')->boolean()->state(fn (ContractTemplate $record): bool => $record->isUsed()), + TextColumn::make('updated_at')->label('Geändert')->dateTime('d.m.Y, H:i'), + ]) + ->recordActions([ + EditAction::make(), + Action::make('newVersion') + ->label('Neue Version') + ->icon(Heroicon::OutlinedDocumentDuplicate) + ->requiresConfirmation() + ->modalDescription('Es wird eine Kopie mit der nächsten Versionsnummer angelegt, die Sie dann bearbeiten können. Die bisherige Version bleibt unverändert.') + ->action(function (ContractTemplate $record): void { + $copy = $record->newVersion(); + Notification::make()->title('Version '.$copy->version.' angelegt')->success()->send(); + }), + DeleteAction::make(), + ]); + } +} diff --git a/app/Filament/Resources/Properties/Schemas/PropertyForm.php b/app/Filament/Resources/Properties/Schemas/PropertyForm.php index 85ab799..0bcb81f 100644 --- a/app/Filament/Resources/Properties/Schemas/PropertyForm.php +++ b/app/Filament/Resources/Properties/Schemas/PropertyForm.php @@ -2,9 +2,11 @@ namespace App\Filament\Resources\Properties\Schemas; +use App\Enums\CancellationMode; use App\Enums\OfferMode; use App\Filament\Forms\Components\EuroInput; use App\ImageWorlds\ImageWorldRegistry; +use App\Models\ContractTemplate; use App\Models\Site; use Closure; use Filament\Forms\Components\Select; @@ -116,6 +118,34 @@ public static function configure(Schema $schema): Schema ->minValue(1) ->suffix('Stunden') ->default(48), + Select::make('cancellation_mode') + ->label('Stornierungslink in der Buchungsbestätigung') + ->options(CancellationMode::class) + ->default(CancellationMode::Request) + ->required() + ->live() + ->helperText('Bei Sofort-Stornierung wird der Zeitraum frei; Kosten und Rückzahlung bleiben immer Ihre Aufgabe.'), + TextInput::make('free_cancellation_days') + ->label('Kostenfrei stornierbar bis') + ->integer() + ->minValue(0) + ->suffix('Tage vor Anreise') + ->default(14) + ->visible(fn (Get $get): bool => $get('cancellation_mode') === CancellationMode::InstantWhenFree->value || $get('cancellation_mode') === CancellationMode::InstantWhenFree), + Select::make('contract_template_id') + ->label('Standard-Vertragsvorlage') + ->options(fn (): array => ContractTemplate::query()->orderBy('name')->orderBy('version')->get()->mapWithKeys(fn (ContractTemplate $template): array => [$template->id => $template->label()])->all()) + ->placeholder('Texte der Webseite') + ->helperText('Wird bei neuen Angeboten verwendet, sofern das Portal keine eigene Vorlage hat.'), + TextInput::make('arrival_info_days_before') + ->label('Anreise-E-Mail senden') + ->helperText('Automatische Mail mit den letzten Hinweisen (Texte unter Texte › Aufenthalt).') + ->required() + ->integer() + ->minValue(1) + ->maxValue(14) + ->suffix('Tage vor Anreise') + ->default(3), Toggle::make('pre_reservation_enabled') ->label('Anfrage blockiert den Kalender (Vorreservierung)') ->helperText('Aus: eine bloße Anfrage sperrt keinen Zeitraum. Dann ist kein automatisches Angebot möglich.') diff --git a/app/Http/Controllers/SelfServiceController.php b/app/Http/Controllers/SelfServiceController.php new file mode 100644 index 0000000..4d0ca39 --- /dev/null +++ b/app/Http/Controllers/SelfServiceController.php @@ -0,0 +1,89 @@ +loadMissing(['guest', 'property']); + + return view('self-service.release', [ + 'booking' => $booking, + 'canRelease' => in_array($booking->status, BookingStatus::holding(), true) && $booking->isHoldActive(), + 'released' => $booking->status === BookingStatus::Declined && $booking->declined_by === 'guest', + 'action' => $this->signed('reservations.release.confirm', $booking, now()->addHour()), + 'title' => 'Zeitraum freigeben', + ]); + } + + public function release(Booking $booking, ReleaseReservation $release): RedirectResponse + { + try { + $release->handle($booking); + } catch (ReservationException $exception) { + return redirect()->to($this->signed('reservations.release', $booking, now()->addDays(2)))->with('self-service.error', $exception->getMessage()); + } + + return redirect()->to($this->signed('reservations.release', $booking, now()->addDays(30)))->with('self-service.success', 'Vielen Dank – der Zeitraum ist wieder freigegeben.'); + } + + public function showCancel(Booking $booking, CancelBookingByGuest $cancel): View + { + $booking->loadMissing(['guest', 'property']); + $open = in_array($booking->status, BookingStatus::occupying(), true) && ! $booking->arrival->isPast(); + + return view('self-service.cancel', [ + 'booking' => $booking, + 'canCancel' => $open && ! $booking->cancellationRequested(), + 'alreadyAsked' => $booking->status === BookingStatus::Cancelled || $booking->cancellationRequested(), + 'instant' => $cancel->modeFor($booking) === CancellationMode::Instant, + 'action' => $this->signed('bookings.cancel.confirm', $booking, now()->addHour()), + 'title' => 'Buchung stornieren', + ]); + } + + public function cancel(Request $request, Booking $booking, CancelBookingByGuest $cancel): RedirectResponse + { + $data = $request->validate(['message' => ['nullable', 'string', 'max:1000']]); + $back = fn (int $days): string => $this->signed('bookings.cancel', $booking, now()->addDays($days)); + + try { + $outcome = $cancel->handle($booking, $data['message'] ?? null); + } catch (ReservationException $exception) { + return redirect()->to($back(2))->with('self-service.error', $exception->getMessage()); + } + + $success = match ($outcome) { + CancellationMode::Instant => 'Ihre Buchung ist storniert. Eine Bestätigung haben wir Ihnen per E-Mail gesendet.', + CancellationMode::Request => 'Wir haben Ihren Stornierungswunsch erhalten. Ihre Buchung bleibt bestehen, bis wir uns bei Ihnen gemeldet haben.', + default => 'Ihr Stornierungswunsch liegt uns bereits vor.', + }; + + return redirect()->to($back(30))->with('self-service.success', $success); + } + + private function signed(string $name, Booking $booking, DateTimeInterface $expiration): string + { + $parameters = ['booking' => $booking]; + + return $booking->website()?->temporarySignedRoute($name, $expiration, $parameters) + ?? URL::temporarySignedRoute($name, $expiration, $parameters); + } +} diff --git a/app/Mail/BookingCancelled.php b/app/Mail/BookingCancelled.php new file mode 100644 index 0000000..02da4e2 --- /dev/null +++ b/app/Mail/BookingCancelled.php @@ -0,0 +1,34 @@ +cancelled ? 'Stornierung ' : 'Ihr Stornierungswunsch ').$this->booking->reference, + replyTo: [new Address(config('fewo.owner.email'), config('fewo.owner.name'))], + ); + } + + public function content(): Content + { + return new Content(markdown: 'mail.booking-cancelled'); + } +} diff --git a/app/Mail/CancellationRequested.php b/app/Mail/CancellationRequested.php new file mode 100644 index 0000000..a47f613 --- /dev/null +++ b/app/Mail/CancellationRequested.php @@ -0,0 +1,30 @@ +cancelled ? 'Storniert: ' : 'Stornierungswunsch: ').$this->booking->reference.' – '.$this->booking->guest->full_name); + } + + public function content(): Content + { + return new Content(markdown: 'mail.cancellation-requested'); + } +} diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 7976c22..9fce7e0 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -4,6 +4,8 @@ use App\Documents\OfferTerms; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; +use App\Enums\ChannelBookingModel; use App\Enums\ReferralSource; use App\Models\Concerns\BelongsToTenant; use App\Models\Concerns\HasChannelProvenance; @@ -57,6 +59,8 @@ 'offer_path', 'offer_terms', 'offer_hash', + 'offer_pdf_sha256', + 'contract_pdf_sha256', 'message', 'internal_notes', 'confirmed_at', @@ -266,6 +270,31 @@ public function requiresFullPayment(): bool return $this->deposit_due_on !== null && $this->balance_due_on->lessThanOrEqualTo($this->deposit_due_on); } + /** + * Whether the landlord chases payments of this booking. Own bookings: always. Portal bookings: as configured + * per channel and kind – a reservation whose payment the portal collects (e.g. instant booking) needs no + * tasks, a mere inquiry passed on by the portal does. + */ + public function wantsPaymentTasks(): bool + { + $channel = $this->importChannel ?? $this->originChannel; + if ($channel === null) { + return true; + } + + return $channel->booking_model === ChannelBookingModel::PortalBooking + ? $channel->payment_tasks_reservation + : $channel->payment_tasks_inquiry; + } + + /** + * Whether the guest already asked to cancel (or cancelled) through the cancellation link. + */ + public function cancellationRequested(): bool + { + return BookingTask::query()->where('booking_id', $this->id)->where('kind', BookingTaskKind::CancellationRequest)->exists(); + } + public function nights(): int { return (int) $this->arrival->diffInDays($this->departure); diff --git a/app/Models/BookingTask.php b/app/Models/BookingTask.php new file mode 100644 index 0000000..3763085 --- /dev/null +++ b/app/Models/BookingTask.php @@ -0,0 +1,60 @@ + + */ + protected function casts(): array + { + return [ + 'kind' => BookingTaskKind::class, + 'status' => BookingTaskStatus::class, + 'due_on' => 'immutable_date', + 'completed_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function booking(): BelongsTo + { + return $this->belongsTo(Booking::class); + } + + /** + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function open(Builder $query): Builder + { + return $query->where('status', BookingTaskStatus::Open); + } + + public function complete(string $by): void + { + $this->update(['status' => BookingTaskStatus::Done, 'completed_by' => $by, 'completed_at' => now()]); + } +} diff --git a/app/Models/Channel.php b/app/Models/Channel.php index 8c4665f..0504847 100644 --- a/app/Models/Channel.php +++ b/app/Models/Channel.php @@ -26,7 +26,7 @@ * A sales channel (portal) of a property. Our system leads: occupations are imported from the * channel and every channel gets its own export feed without its own occupations. */ -#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at'])] +#[Fillable(['property_id', 'name', 'connector', 'settings', 'is_active', 'requires_manual_blocking', 'manage_url', 'status', 'booking_model', 'import_enabled', 'export_enabled', 'export_mode', 'external_poll_minutes', 'echo_behavior', 'echo_notes', 'operating_notes', 'portal_verified_at', 'payment_tasks_inquiry', 'payment_tasks_reservation', 'contract_template_id'])] #[Hidden(['export_token', 'previous_export_token', 'export_snapshot', 'settings', 'ical_analysis'])] class Channel extends Model { @@ -72,6 +72,8 @@ protected function casts(): array 'booking_model' => ChannelBookingModel::class, 'echo_behavior' => ChannelEchoBehavior::class, 'portal_verified_at' => 'immutable_datetime', + 'payment_tasks_inquiry' => 'boolean', + 'payment_tasks_reservation' => 'boolean', 'export_mode' => ChannelExportMode::class, 'import_enabled' => 'boolean', 'export_enabled' => 'boolean', diff --git a/app/Models/ContractTemplate.php b/app/Models/ContractTemplate.php new file mode 100644 index 0000000..cb0ac0b --- /dev/null +++ b/app/Models/ContractTemplate.php @@ -0,0 +1,78 @@ + website text key it replaces in an offer. */ + public const TEXTS = [ + 'intro' => 'contract.intro', + 'terms' => 'contract.terms', + 'closing' => 'contract.closing', + 'cancellation' => 'stay.cancellation', + 'house_rules' => 'stay.house_rules', + 'contract_note' => 'offer.contract_note', + ]; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return ['texts' => 'array', 'version' => 'integer']; + } + + public function label(): string + { + return $this->name.' (Version '.$this->version.')'; + } + + /** + * Texts by website text key; blank ones fall back to the website texts. + * + * @return array + */ + public function overrides(): array + { + $overrides = []; + foreach (self::TEXTS as $field => $key) { + $value = $this->texts[$field] ?? null; + if (filled($value) && trim(strip_tags((string) $value)) !== '') { + $overrides[$key] = (string) $value; + } + } + + return $overrides; + } + + public function isUsed(): bool + { + return Booking::query()->where('offer_terms->template->id', $this->id)->exists(); + } + + public function newVersion(): self + { + $latest = static::query()->where('name', $this->name)->max('version'); + + return static::query()->create([ + 'name' => $this->name, + 'version' => $latest + 1, + 'texts' => $this->texts, + 'notes' => $this->notes, + ]); + } +} diff --git a/app/Models/Property.php b/app/Models/Property.php index 94a81a3..98305d7 100644 --- a/app/Models/Property.php +++ b/app/Models/Property.php @@ -2,6 +2,7 @@ namespace App\Models; +use App\Enums\CancellationMode; use App\Enums\OfferMode; use App\Models\Concerns\BelongsToTenant; use Carbon\CarbonImmutable; @@ -32,6 +33,10 @@ 'hold_hours', 'offer_mode', 'pre_reservation_enabled', + 'arrival_info_days_before', + 'cancellation_mode', + 'free_cancellation_days', + 'contract_template_id', 'check_in_time', 'check_out_time', 'changeover_weekday', @@ -61,6 +66,9 @@ class Property extends Model 'min_stay_absolute' => 2, 'offer_mode' => 'manual', 'pre_reservation_enabled' => true, + 'arrival_info_days_before' => 3, + 'cancellation_mode' => 'request', + 'free_cancellation_days' => 14, ]; protected function casts(): array @@ -69,6 +77,9 @@ protected function casts(): array 'is_active' => 'boolean', 'offer_mode' => OfferMode::class, 'pre_reservation_enabled' => 'boolean', + 'arrival_info_days_before' => 'integer', + 'cancellation_mode' => CancellationMode::class, + 'free_cancellation_days' => 'integer', 'min_stay_fill_gaps' => 'boolean', 'min_stay_until_changeover' => 'boolean', 'changeover_weekday' => 'integer', diff --git a/app/Support/DigestReport.php b/app/Support/DigestReport.php index 5591045..6671aca 100644 --- a/app/Support/DigestReport.php +++ b/app/Support/DigestReport.php @@ -8,12 +8,14 @@ use App\Enums\ReviewStatus; use App\Filament\Pages\OccupancyCalendar; use App\Filament\Resources\Bookings\BookingResource; +use App\Filament\Resources\BookingTasks\BookingTaskResource; use App\Filament\Resources\ChannelTasks\ChannelTaskResource; use App\Filament\Resources\InboxMessages\InboxMessageResource; use App\Filament\Resources\PortalOccupations\PortalOccupationResource; use App\Filament\Resources\Reviews\ReviewResource; use App\Models\BlockedPeriod; use App\Models\Booking; +use App\Models\BookingTask; use App\Models\Channel; use App\Models\ChannelTask; use App\Models\InboxMessage; @@ -50,7 +52,7 @@ public function build(array $sections, bool $weekly, CarbonImmutable $since): ar DigestSection::Requests => ['Offene Anfragen und Angebote', $this->requests(), BookingResource::getUrl('index'), 'Buchungen öffnen'], DigestSection::News => ['Neu seit '.$since->format('d.m. H:i').' Uhr', $this->news($since), BookingResource::getUrl('index'), 'Buchungen öffnen'], DigestSection::Stays => [$weekly ? 'An- und Abreisen der nächsten 7 Tage' : 'An- und Abreisen heute und morgen', $this->stays($weekly ? 7 : 2), OccupancyCalendar::getUrl(), 'Belegungsplan öffnen'], - DigestSection::Payments => ['Überfällige Zahlungen', $this->payments(), BookingResource::getUrl('index'), 'Buchungen öffnen'], + DigestSection::Payments => ['Zahlungsaufgaben und Gästewünsche', $this->payments(), BookingTaskResource::getUrl('index'), 'Aufgaben öffnen'], DigestSection::Portals => ['Portale: Aufgaben und Klärungsfälle', $this->portals(), ChannelTaskResource::getUrl('index'), 'Portal-Aufgaben öffnen'], DigestSection::Reviews => ['Bewertungen zur Freigabe', $this->reviews(), ReviewResource::getUrl('index'), 'Bewertungen öffnen'], }; @@ -149,13 +151,8 @@ private function stayEvents(array &$events, CarbonImmutable $from, CarbonImmutab */ private function payments(): Collection { - return Booking::query()->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid])->with(['guest', 'property', 'payments'])->orderBy('arrival')->get() - ->map(fn (Booking $booking): ?string => match (true) { - $booking->status === BookingStatus::Confirmed && $booking->deposit_due_on?->isPast() && $booking->openDeposit() > 0 => $this->booking($booking).' – Anzahlung '.Money::format($booking->openDeposit()).' seit '.$booking->deposit_due_on->format('d.m.').' fällig', - $booking->balance_due_on?->isPast() && $booking->openAmount() > 0 => $this->booking($booking).' – offen '.Money::format($booking->openAmount()).' seit '.$booking->balance_due_on->format('d.m.').' fällig', - default => null, - }) - ->filter() + return BookingTask::query()->open()->with('booking.guest', 'booking.property')->oldest()->get() + ->map(fn (BookingTask $task): string => $this->booking($task->booking).' – '.$task->kind->getLabel().($task->due_on ? ' (seit '.$task->due_on->format('d.m.').')' : '')) ->values(); } diff --git a/app/Support/SelfServiceLinks.php b/app/Support/SelfServiceLinks.php new file mode 100644 index 0000000..c4e455e --- /dev/null +++ b/app/Support/SelfServiceLinks.php @@ -0,0 +1,34 @@ +hold_expires_at ?? now()->addDays(14)); + } + + /** Cancels (or asks to cancel) a binding booking; valid until the day of arrival. */ + public static function cancel(Booking $booking): string + { + return self::signed('bookings.cancel', $booking, CarbonImmutable::parse($booking->arrival)->endOfDay()); + } + + private static function signed(string $route, Booking $booking, \DateTimeInterface $until): string + { + $parameters = ['booking' => $booking]; + + return $booking->website()?->temporarySignedRoute($route, $until, $parameters) + ?? URL::temporarySignedRoute($route, $until, $parameters); + } +} diff --git a/config/content.php b/config/content.php index 77c0ab3..f8bd7fc 100644 --- a/config/content.php +++ b/config/content.php @@ -29,6 +29,9 @@ 'fields' => [ 'stay.house_rules' => ['label' => 'Hausregeln', 'type' => 'richtext', 'default' => null], 'stay.arrival_info' => ['label' => 'Anreiseinformationen (für Gäste-E-Mail vor Anreise)', 'type' => 'richtext', 'default' => null], + 'stay.key_handover' => ['label' => 'Schlüsselübergabe (Anreise-E-Mail)', 'type' => 'richtext', 'default' => null], + 'stay.parking' => ['label' => 'Parken (Anreise-E-Mail)', 'type' => 'richtext', 'default' => null], + 'stay.arrival_day' => ['label' => 'Der entspannte Ankunftstag (Anreise-E-Mail)', 'type' => 'richtext', 'default' => null], 'stay.cancellation' => ['label' => 'Stornobedingungen', 'type' => 'richtext', 'default' => null], ], ], diff --git a/database/migrations/2026_10_30_123153_create_booking_tasks_and_payment_policy.php b/database/migrations/2026_10_30_123153_create_booking_tasks_and_payment_policy.php new file mode 100644 index 0000000..f7a3099 --- /dev/null +++ b/database/migrations/2026_10_30_123153_create_booking_tasks_and_payment_policy.php @@ -0,0 +1,54 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->foreignId('booking_id')->constrained()->cascadeOnDelete(); + $table->string('kind', 30); + $table->string('status', 12)->default('open'); + $table->date('due_on')->nullable(); + $table->text('note')->nullable(); + $table->string('completed_by')->nullable(); + $table->timestamp('completed_at')->nullable(); + $table->timestamps(); + $table->unique(['booking_id', 'kind']); + $table->index(['tenant_id', 'status']); + }); + + Schema::table('channels', function (Blueprint $table) { + $table->boolean('payment_tasks_inquiry')->default(true)->after('operating_notes'); + $table->boolean('payment_tasks_reservation')->default(false)->after('payment_tasks_inquiry'); + }); + + Schema::table('properties', function (Blueprint $table) { + $table->unsignedTinyInteger('arrival_info_days_before')->default(3)->after('offer_mode'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('properties', function (Blueprint $table) { + $table->dropColumn('arrival_info_days_before'); + }); + Schema::table('channels', function (Blueprint $table) { + $table->dropColumn(['payment_tasks_inquiry', 'payment_tasks_reservation']); + }); + Schema::dropIfExists('booking_tasks'); + } +}; diff --git a/database/migrations/2026_10_30_123544_add_cancellation_policy_to_properties_table.php b/database/migrations/2026_10_30_123544_add_cancellation_policy_to_properties_table.php new file mode 100644 index 0000000..17ffa5c --- /dev/null +++ b/database/migrations/2026_10_30_123544_add_cancellation_policy_to_properties_table.php @@ -0,0 +1,30 @@ +string('cancellation_mode', 20)->default('request')->after('arrival_info_days_before'); + $table->unsignedSmallInteger('free_cancellation_days')->default(14)->after('cancellation_mode'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('properties', function (Blueprint $table) { + $table->dropColumn(['cancellation_mode', 'free_cancellation_days']); + }); + } +}; diff --git a/database/migrations/2026_10_30_124055_create_contract_templates_and_document_hashes.php b/database/migrations/2026_10_30_124055_create_contract_templates_and_document_hashes.php new file mode 100644 index 0000000..3b98992 --- /dev/null +++ b/database/migrations/2026_10_30_124055_create_contract_templates_and_document_hashes.php @@ -0,0 +1,54 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->string('name'); + $table->unsignedInteger('version')->default(1); + $table->json('texts')->nullable(); + $table->text('notes')->nullable(); + $table->timestamps(); + $table->unique(['tenant_id', 'name', 'version']); + }); + + Schema::table('properties', function (Blueprint $table) { + $table->foreignId('contract_template_id')->nullable()->after('free_cancellation_days')->constrained('contract_templates')->nullOnDelete(); + }); + Schema::table('channels', function (Blueprint $table) { + $table->foreignId('contract_template_id')->nullable()->after('payment_tasks_reservation')->constrained('contract_templates')->nullOnDelete(); + }); + Schema::table('bookings', function (Blueprint $table) { + $table->string('offer_pdf_sha256', 64)->nullable()->after('offer_hash'); + $table->string('contract_pdf_sha256', 64)->nullable()->after('offer_pdf_sha256'); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + Schema::table('bookings', function (Blueprint $table) { + $table->dropColumn(['offer_pdf_sha256', 'contract_pdf_sha256']); + }); + Schema::table('channels', function (Blueprint $table) { + $table->dropConstrainedForeignId('contract_template_id'); + }); + Schema::table('properties', function (Blueprint $table) { + $table->dropConstrainedForeignId('contract_template_id'); + }); + Schema::dropIfExists('contract_templates'); + } +}; diff --git a/resources/views/mail/arrival-information.blade.php b/resources/views/mail/arrival-information.blade.php index 3e8a2d0..1a8246c 100644 --- a/resources/views/mail/arrival-information.blade.php +++ b/resources/views/mail/arrival-information.blade.php @@ -11,10 +11,28 @@ @if (\App\Support\Content::get('stay.arrival_info')) {{ \App\Support\Content::html('stay.arrival_info') }} -@else +@endif + +@if (\App\Support\Content::get('stay.key_handover')) +## Schlüsselübergabe + +{{ \App\Support\Content::html('stay.key_handover') }} +@elseif (! \App\Support\Content::get('stay.arrival_info')) Zur Schlüsselübergabe melden wir uns noch persönlich bei Ihnen. @endif +@if (\App\Support\Content::get('stay.parking')) +## Parken + +{{ \App\Support\Content::html('stay.parking') }} +@endif + +@if (\App\Support\Content::get('stay.arrival_day')) +## Ihr entspannter Ankunftstag + +{{ \App\Support\Content::html('stay.arrival_day') }} +@endif + @if (\App\Support\Content::get('stay.house_rules')) ## Hausregeln diff --git a/resources/views/mail/booking-cancelled.blade.php b/resources/views/mail/booking-cancelled.blade.php new file mode 100644 index 0000000..3760337 --- /dev/null +++ b/resources/views/mail/booking-cancelled.blade.php @@ -0,0 +1,22 @@ + +@if ($cancelled) +# Ihre Buchung {{ $booking->reference }} ist storniert + +Guten Tag {{ $booking->guest->full_name }}, + +wir haben Ihre Buchung der **{{ $booking->property->name }}** vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} wie gewünscht storniert. Der Zeitraum ist wieder frei. + +Ob und in welcher Höhe Stornokosten nach den vereinbarten Stornobedingungen anfallen, teilen wir Ihnen separat mit. +@else +# Ihr Stornierungswunsch {{ $booking->reference }} + +Guten Tag {{ $booking->guest->full_name }}, + +wir haben Ihren Wunsch erhalten, die Buchung der **{{ $booking->property->name }}** vom {{ $booking->arrival->format('d.m.Y') }} bis {{ $booking->departure->format('d.m.Y') }} zu stornieren. **Die Buchung bleibt zunächst bestehen**, bis wir uns bei Ihnen gemeldet haben. Wir prüfen Ihre Anfrage anhand der vereinbarten Stornobedingungen und melden uns zeitnah. +@endif + +Bei Fragen erreichen Sie uns unter {{ config('fewo.owner.phone') }}. + +Herzliche Grüße
+{{ config('fewo.owner.name') }} +
diff --git a/resources/views/mail/booking-confirmed.blade.php b/resources/views/mail/booking-confirmed.blade.php index 757de2c..7fabdf1 100644 --- a/resources/views/mail/booking-confirmed.blade.php +++ b/resources/views/mail/booking-confirmed.blade.php @@ -28,7 +28,9 @@ Ihren **Mietvertrag** finden Sie als PDF im Anhang. -Eine Woche vor Ihrer Anreise erhalten Sie von uns alle Informationen zu Schlüsselübergabe, Parken und WLAN. +Falls Sie Ihre Buchung stornieren müssen: [Buchung stornieren oder Stornierung anfragen]({{ \App\Support\SelfServiceLinks::cancel($booking) }}). Dort sehen Sie auch die vereinbarten Stornobedingungen. + +Kurz vor Ihrer Anreise erhalten Sie von uns alle Informationen zu Schlüsselübergabe, Parken und WLAN. Herzliche Grüße
{{ config('fewo.owner.name') }} diff --git a/resources/views/mail/cancellation-requested.blade.php b/resources/views/mail/cancellation-requested.blade.php new file mode 100644 index 0000000..feee037 --- /dev/null +++ b/resources/views/mail/cancellation-requested.blade.php @@ -0,0 +1,17 @@ + +# {{ $cancelled ? 'Buchung vom Gast storniert' : 'Stornierungswunsch eines Gastes' }} + +**{{ $booking->guest->full_name }}** · Buchung **{{ $booking->reference }}** · {{ $booking->property->name }}
+**Zeitraum:** {{ $booking->arrival->format('d.m.Y') }} – {{ $booking->departure->format('d.m.Y') }}
+**Gesamtpreis:** {{ \App\Support\Money::format($booking->total) }}, bezahlt {{ \App\Support\Money::format($booking->paidAmount()) }} + +@if ($cancelled) +Die Buchung wurde sofort storniert und der Zeitraum ist frei. **Stornokosten und eine mögliche Rückzahlung bitte von Hand prüfen** (Aufgabe unter „Zahlungen & Wünsche“). +@else +Die Buchung besteht weiter. Bitte entscheiden Sie (Aufgabe unter „Zahlungen & Wünsche“) und melden Sie sich beim Gast. +@endif + + +Buchung öffnen + +
diff --git a/resources/views/mail/reservation-received.blade.php b/resources/views/mail/reservation-received.blade.php index 8d48ab6..5d3f8e2 100644 --- a/resources/views/mail/reservation-received.blade.php +++ b/resources/views/mail/reservation-received.blade.php @@ -21,6 +21,10 @@ {{ $booking->message }} @endif +@if ($booking->isHoldActive()) +**Sie brauchen den Zeitraum nicht mehr?** [Zeitraum freigeben]({{ \App\Support\SelfServiceLinks::release($booking) }}) – dann können ihn andere Gäste buchen. +@endif + Bei Fragen antworten Sie einfach auf diese E-Mail oder rufen Sie uns an: {{ config('fewo.owner.phone') }} Herzliche Grüße
diff --git a/resources/views/self-service/cancel.blade.php b/resources/views/self-service/cancel.blade.php new file mode 100644 index 0000000..62855fc --- /dev/null +++ b/resources/views/self-service/cancel.blade.php @@ -0,0 +1,51 @@ +@extends('theme::layouts.app', ['title' => 'Buchung stornieren']) + +@push('head') + +@endpush + +@section('content') +
+

Buchung {{ $booking->reference }}

+

{{ $booking->property->name }}

+ + @if (session('self-service.success')) +
{{ session('self-service.success') }}
+ @endif + @if (session('self-service.error')) + + @endif + +
+

{{ $booking->arrival->translatedFormat('l, d.m.Y') }} bis {{ $booking->departure->translatedFormat('l, d.m.Y') }}, {{ $booking->guests }} Personen · Gesamtpreis {{ \App\Support\Money::format($booking->total) }}

+ + @if ($alreadyAsked && ! session('self-service.success')) +

+ @if ($booking->status === \App\Enums\BookingStatus::Cancelled) Diese Buchung ist storniert. + @else Ihr Stornierungswunsch liegt uns vor; wir melden uns bei Ihnen. @endif +

+ @elseif ($canCancel) + @if ($booking->offerText('stay.cancellation')) +

Stornobedingungen Ihrer Buchung

+
{{ $booking->offerHtml('stay.cancellation') }}
+ @endif + +
+ @csrf + @if ($instant) +

Mit Klick auf den Button wird Ihre Buchung sofort storniert und der Zeitraum freigegeben. Ob Stornokosten nach den oben genannten Bedingungen anfallen, teilen wir Ihnen danach mit.

+ @else +

Mit Klick auf den Button senden Sie uns Ihren Stornierungswunsch. Ihre Buchung bleibt bestehen, bis wir uns bei Ihnen gemeldet haben; wir prüfen sie anhand der oben genannten Bedingungen.

+ @endif + + + +
+ @else +

Diese Buchung kann über diesen Link nicht mehr storniert werden. Bitte kontaktieren Sie uns.

+ @endif +
+ +

Fragen? {{ config('fewo.owner.name') }} · {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }}

+
+@endsection diff --git a/resources/views/self-service/release.blade.php b/resources/views/self-service/release.blade.php new file mode 100644 index 0000000..a229a70 --- /dev/null +++ b/resources/views/self-service/release.blade.php @@ -0,0 +1,37 @@ +@extends('theme::layouts.app', ['title' => 'Zeitraum freigeben']) + +@push('head') + +@endpush + +@section('content') +
+

Anfrage {{ $booking->reference }}

+

{{ $booking->property->name }}

+ + @if (session('self-service.success')) +
{{ session('self-service.success') }}
+ @endif + @if (session('self-service.error')) + + @endif + +
+

{{ $booking->arrival->translatedFormat('l, d.m.Y') }} bis {{ $booking->departure->translatedFormat('l, d.m.Y') }}, {{ $booking->guests }} Personen

+ + @if ($released && ! session('self-service.success')) +

Dieser Zeitraum wurde freigegeben.

+ @elseif ($canRelease) +

Wenn Sie den vorgemerkten Zeitraum nicht benötigen, geben Sie ihn hier frei – dann können ihn andere Gäste buchen. Es entstehen keine Kosten.

+
+ @csrf + +
+ @elseif (! $released) +

Für diese Anfrage gibt es nichts mehr freizugeben (der Zeitraum ist nicht mehr vorgemerkt oder die Buchung ist bereits verbindlich).

+ @endif +
+ +

Fragen? {{ config('fewo.owner.name') }} · {{ config('fewo.owner.phone') }} · {{ config('fewo.owner.email') }}

+
+@endsection diff --git a/routes/web.php b/routes/web.php index a8aea8f..923f441 100644 --- a/routes/web.php +++ b/routes/web.php @@ -4,6 +4,7 @@ use App\Http\Controllers\MarketingConsentController; use App\Http\Controllers\OfferController; use App\Http\Controllers\PageController; +use App\Http\Controllers\SelfServiceController; use App\Models\Booking; use Illuminate\Foundation\Http\Middleware\PreventRequestForgery; use Illuminate\Support\Facades\Route; @@ -16,6 +17,11 @@ 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'); + // Self service from the guest's mails: release a held request, cancel a booking (paths under /angebot/ keep the requested host) + Route::get('/angebot/{booking}/freigeben', [SelfServiceController::class, 'showRelease'])->name('reservations.release')->middleware('throttle:30,1'); + Route::post('/angebot/{booking}/freigeben/bestaetigen', [SelfServiceController::class, 'release'])->name('reservations.release.confirm')->middleware('throttle:10,1'); + Route::get('/angebot/{booking}/storno', [SelfServiceController::class, 'showCancel'])->name('bookings.cancel')->middleware('throttle:30,1'); + Route::post('/angebot/{booking}/storno/bestaetigen', [SelfServiceController::class, 'cancel'])->name('bookings.cancel.confirm')->middleware('throttle:10,1'); }); Route::get('/kalender/{token}.ics', [ChannelController::class, 'feed'])->name('channels.feed')->middleware('throttle:60,1'); diff --git a/tests/Feature/ContractTemplateTest.php b/tests/Feature/ContractTemplateTest.php new file mode 100644 index 0000000..2855fcf --- /dev/null +++ b/tests/Feature/ContractTemplateTest.php @@ -0,0 +1,138 @@ +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(); + } + + public function test_offer_uses_the_chosen_template_and_freezes_it_with_name_and_version(): void + { + $template = $this->template('Portal XY', ['terms' => '

Bedingungen Portal XY

', 'cancellation' => '

Storno bis 30 Tage

']); + + $offer = $this->offer(['contract_template_id' => $template->id]); + + $this->assertSame('Bedingungen Portal XY', trim(strip_tags($offer->offerText('contract.terms')))); + $this->assertSame(['id' => $template->id, 'name' => 'Portal XY', 'version' => 1], $offer->offer_terms['template']); + $this->assertNotNull($offer->offer_pdf_sha256); + // blank template fields fall back to the website text + $this->assertNotEmpty($offer->offerText('contract.closing')); + } + + public function test_default_order_is_explicit_choice_then_portal_then_property(): void + { + $propertyDefault = $this->template('Direkt', ['terms' => '

DIREKT

']); + $portalDefault = $this->template('Portal', ['terms' => '

PORTAL

']); + $this->property->update(['contract_template_id' => $propertyDefault->id]); + $channel = Channel::factory()->for($this->property)->create(['contract_template_id' => $portalDefault->id]); + + $direct = $this->offer(); + $viaPortal = $this->offer([], ['import_channel_id' => $channel->id, 'arrival' => '2026-12-01', 'departure' => '2026-12-04']); + + $this->assertSame('DIREKT', trim(strip_tags($direct->offerText('contract.terms')))); + $this->assertSame('PORTAL', trim(strip_tags($viaPortal->offerText('contract.terms')))); + } + + public function test_editing_a_template_later_does_not_change_a_sent_offer_or_the_contract(): void + { + $template = $this->template('Direkt', ['terms' => '

VERSION EINS

']); + $offer = $this->offer(['contract_template_id' => $template->id]); + + $template->update(['texts' => ['terms' => '

GEÄNDERT

']]); + app(AcceptOffer::class)->handle($offer->fresh(), 1); + + $this->assertSame('VERSION EINS', trim(strip_tags($offer->fresh()->offerText('contract.terms')))); + } + + public function test_used_versions_are_locked_and_a_new_version_can_be_made(): void + { + $template = $this->template('Direkt', ['terms' => '

A

']); + $this->assertTrue(ContractTemplateResource::canEdit($template)); + + $this->offer(['contract_template_id' => $template->id]); + $this->assertFalse(ContractTemplateResource::canEdit($template->fresh())); + $this->assertFalse(ContractTemplateResource::canDelete($template->fresh())); + + $this->actingAs(User::factory()->create()); + Livewire::test(ListContractTemplates::class)->callAction(TestAction::make('newVersion')->table($template), []); + + $this->assertSame([1, 2], ContractTemplate::query()->where('name', 'Direkt')->orderBy('version')->pluck('version')->all()); + $this->assertTrue(ContractTemplateResource::canEdit(ContractTemplate::query()->where('version', 2)->sole())); + } + + public function test_final_contract_is_a_document_of_record_that_is_never_rewritten(): void + { + $offer = $this->offer(); + app(AcceptOffer::class)->handle($offer->fresh(), 1); + $booking = $offer->fresh(); + $content = Storage::disk('local')->get($booking->contract_path); + + $this->assertSame(hash('sha256', $content), $booking->contract_pdf_sha256); + + $this->travel(3)->days(); + app(ConfirmBooking::class)->resend($booking); + app(RentalContract::class)->generate($booking->fresh()); + + $this->assertSame($content, Storage::disk('local')->get($booking->contract_path)); + $this->assertSame($booking->contract_pdf_sha256, $booking->fresh()->contract_pdf_sha256); + } + + /** + * @param array $texts + */ + private function template(string $name, array $texts): ContractTemplate + { + return ContractTemplate::query()->create(['name' => $name, 'version' => 1, 'texts' => $texts]); + } + + /** + * @param array $changes + * @param array $attributes + */ + private function offer(array $changes = [], array $attributes = []): Booking + { + $booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create([ + 'arrival' => '2026-11-07', 'departure' => '2026-11-10', 'guests' => 2, ...$attributes, + ]); + + return app(SendOffer::class)->handle($booking, $changes); + } +} diff --git a/tests/Feature/DigestTest.php b/tests/Feature/DigestTest.php index bb76a74..f11e62e 100644 --- a/tests/Feature/DigestTest.php +++ b/tests/Feature/DigestTest.php @@ -4,10 +4,13 @@ use App\Actions\SendDigests; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; +use App\Enums\BookingTaskStatus; use App\Enums\DigestSection; use App\Filament\Pages\Operations; use App\Mail\Digest; use App\Models\Booking; +use App\Models\BookingTask; use App\Models\Guest; use App\Models\InboxMessage; use App\Models\Property; @@ -87,7 +90,8 @@ public function test_summary_lists_requests_stays_payments_and_inbox_and_only_th { $this->openRequest(); $this->booking(['arrival' => '2026-11-03', 'departure' => '2026-11-07'], 'Erika Mustermann'); - $this->booking(['arrival' => '2026-12-01', 'departure' => '2026-12-05', 'balance_due_on' => '2026-10-20', 'created_at' => now()->subWeek()], 'Hans Säumig'); + $late = $this->booking(['arrival' => '2026-12-01', 'departure' => '2026-12-05', 'balance_due_on' => '2026-10-20', 'created_at' => now()->subWeek()], 'Hans Säumig'); + BookingTask::query()->create(['booking_id' => $late->id, 'kind' => BookingTaskKind::BalanceReminder, 'status' => BookingTaskStatus::Open, 'due_on' => '2026-10-20']); InboxMessage::factory()->create(['subject' => 'Mögliche Doppelbuchung über FeWo-direkt', 'body' => 'Ostsee']); app(SendDigests::class)->send($this->tenant, weekly: false); @@ -98,7 +102,7 @@ public function test_summary_lists_requests_stays_payments_and_inbox_and_only_th return in_array('Offene Anfragen und Angebote', $titles, true) && in_array('An- und Abreisen heute und morgen', $titles, true) - && in_array('Überfällige Zahlungen', $titles, true) + && in_array('Zahlungsaufgaben und Gästewünsche', $titles, true) && str_contains($html, 'Morgen: Anreise') && str_contains($html, 'Erika Mustermann') && str_contains($html, 'Hans Säumig') diff --git a/tests/Feature/PaymentWorkflowTest.php b/tests/Feature/PaymentWorkflowTest.php index 3c274a3..1b7d28e 100644 --- a/tests/Feature/PaymentWorkflowTest.php +++ b/tests/Feature/PaymentWorkflowTest.php @@ -6,13 +6,17 @@ use App\Actions\CreateReservation; use App\Actions\RecordPayment; use App\Actions\SendBookingReminders; +use App\Actions\SendPaymentReminder; use App\Enums\BookingStatus; +use App\Enums\BookingTaskKind; +use App\Enums\BookingTaskStatus; use App\Filament\Resources\Bookings\Pages\ViewBooking; use App\Filament\Resources\Bookings\RelationManagers\PaymentsRelationManager; use App\Mail\ArrivalInformation; use App\Mail\BookingConfirmed; use App\Mail\PaymentReminder; use App\Models\Booking; +use App\Models\BookingTask; use App\Models\Property; use App\Models\User; use App\Pricing\StayRequest; @@ -85,7 +89,15 @@ public function test_reminders_are_sent_once_at_the_right_time(): void $this->travelTo(CarbonImmutable::parse('2026-10-30 09:00')); $this->assertSame(1, $reminders->handle()['deposit_overdue']); $this->assertSame(0, $reminders->handle()['deposit_overdue']); + Mail::assertNotSent(PaymentReminder::class); + $task = BookingTask::query()->where('kind', BookingTaskKind::DepositReminder)->sole(); + $this->assertSame(BookingTaskStatus::Open, $task->status); + + app(SendPaymentReminder::class)->handle($task, 'Test'); + Mail::assertSent(PaymentReminder::class, 1); Mail::assertSent(PaymentReminder::class, fn (PaymentReminder $mail): bool => $mail->kind === PaymentReminder::DEPOSIT_OVERDUE && $mail->hasBcc(config('fewo.notification_email'))); + $this->assertSame(BookingTaskStatus::Done, $task->fresh()->status); + $this->assertNotNull($booking->fresh()->deposit_reminded_at); (new RecordPayment)->handle($booking, $booking->deposit, today()); @@ -97,7 +109,9 @@ public function test_reminders_are_sent_once_at_the_right_time(): void $this->travelTo(CarbonImmutable::parse('2026-11-04 09:00')); $this->assertSame(1, $reminders->handle()['balance_overdue']); - $this->travelTo(CarbonImmutable::parse('2026-11-24 09:00')); + $this->travelTo(CarbonImmutable::parse('2026-11-27 09:00')); + $this->assertSame(0, $reminders->handle()['arrival_info'], 'default: 3 days before arrival'); + $this->travelTo(CarbonImmutable::parse('2026-11-28 09:00')); $this->assertSame(1, $reminders->handle()['arrival_info']); Mail::assertSent(ArrivalInformation::class); diff --git a/tests/Feature/SelfServiceTest.php b/tests/Feature/SelfServiceTest.php new file mode 100644 index 0000000..d19e9cb --- /dev/null +++ b/tests/Feature/SelfServiceTest.php @@ -0,0 +1,189 @@ +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(); + } + + public function test_release_link_opens_a_page_and_only_the_button_releases_the_dates(): void + { + $booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10']); + $link = SelfServiceLinks::release($booking); + + $this->get($link)->assertOk()->assertSee('Zeitraum freigeben'); + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + + $action = $this->formAction($link, 'freigeben/bestaetigen'); + $this->submit($action)->assertOk()->assertSee('wieder freigegeben'); + $this->submit($action)->assertOk(); + + $this->assertSame(BookingStatus::Declined, $booking->fresh()->status); + $this->assertSame(0, Booking::query()->occupying()->count()); + } + + public function test_release_never_touches_a_binding_booking_and_needs_a_valid_signature(): void + { + $booking = Booking::factory()->for($this->property)->create(['status' => BookingStatus::Confirmed, 'arrival' => '2026-11-07', 'departure' => '2026-11-10']); + + $this->get(SelfServiceLinks::release($booking).'x')->assertForbidden(); + $this->post(SelfServiceLinks::release($booking))->assertStatus(405); + $this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status); + } + + public function test_reservation_mail_contains_the_release_link_only_while_the_dates_are_held(): void + { + $booking = Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(); + $this->assertStringContainsString('/freigeben', (new ReservationReceived($booking))->render()); + + $booking->update(['hold_expires_at' => null]); + $this->assertStringNotContainsString('/freigeben', (new ReservationReceived($booking->fresh()))->render()); + } + + public function test_confirmation_contains_the_cancellation_link(): void + { + $offer = app(SendOffer::class)->handle(Booking::factory()->for($this->property)->reserved(now()->addHours(48))->create(['arrival' => '2026-11-07', 'departure' => '2026-11-10', 'guests' => 2])); + app(AcceptOffer::class)->handle($offer->fresh(), 1); + + Mail::assertSent(BookingConfirmed::class, fn (BookingConfirmed $mail): bool => str_contains($mail->render(), '/storno')); + } + + public function test_request_mode_only_creates_a_task_and_keeps_the_booking(): void + { + $booking = $this->confirmed(); + + $link = SelfServiceLinks::cancel($booking); + $this->get($link)->assertOk()->assertSee('Stornierung anfragen'); + $action = $this->formAction($link, 'storno/bestaetigen'); + $this->submit($action, ['message' => 'Krank'])->assertOk()->assertSee('Stornierungswunsch erhalten'); + $this->submit($action)->assertOk()->assertSee('liegt uns bereits vor'); + + $this->assertSame(BookingStatus::Confirmed, $booking->fresh()->status); + $task = BookingTask::query()->where('kind', BookingTaskKind::CancellationRequest)->sole(); + $this->assertSame('Krank', $task->note); + Mail::assertSent(CancellationRequested::class, 1); + Mail::assertSent(BookingCancelled::class, fn (BookingCancelled $mail): bool => ! $mail->cancelled); + } + + public function test_instant_mode_cancels_at_once_and_still_leaves_a_task_for_the_costs(): void + { + $this->property->update(['cancellation_mode' => CancellationMode::Instant]); + $booking = $this->confirmed(); + + $link = SelfServiceLinks::cancel($booking); + $this->submit($this->formAction($link, 'storno/bestaetigen'))->assertOk()->assertSee('storniert'); + + $this->assertSame(BookingStatus::Cancelled, $booking->fresh()->status); + $this->assertSame(0, Booking::query()->occupying()->count()); + $this->assertStringContainsString('Stornokosten', BookingTask::query()->sole()->note); + Mail::assertSent(BookingCancelled::class, fn (BookingCancelled $mail): bool => $mail->cancelled); + } + + public function test_free_cancellation_window_switches_between_instant_and_request(): void + { + $this->property->update(['cancellation_mode' => CancellationMode::InstantWhenFree, 'free_cancellation_days' => 14]); + $far = $this->confirmed('2026-12-20', '2026-12-24'); + $near = $this->confirmed('2026-11-01', '2026-11-04'); + + $this->post($this->formAction(SelfServiceLinks::cancel($far), 'storno/bestaetigen')); + $this->post($this->formAction(SelfServiceLinks::cancel($near), 'storno/bestaetigen')); + + $this->assertSame(BookingStatus::Cancelled, $far->fresh()->status); + $this->assertSame(BookingStatus::Confirmed, $near->fresh()->status); + } + + public function test_payment_tasks_follow_the_channel_policy(): void + { + $own = $this->confirmed(); + $reservationPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'portal_booking', 'payment_tasks_reservation' => false]); + $inquiryPortal = Channel::factory()->for($this->property)->create(['booking_model' => 'inquiry', 'payment_tasks_inquiry' => true]); + $portalReservation = $this->confirmed('2026-12-10', '2026-12-14', ['import_channel_id' => $reservationPortal->id, 'source' => 'portal']); + $portalInquiry = $this->confirmed('2026-12-16', '2026-12-18', ['import_channel_id' => $inquiryPortal->id, 'source' => 'portal']); + + $this->travelTo(CarbonImmutable::parse('2026-11-30 09:00')); + (new SendBookingReminders)->handle(); + + $withTasks = BookingTask::query()->pluck('booking_id')->unique()->all(); + $this->assertContains($own->id, $withTasks); + $this->assertContains($portalInquiry->id, $withTasks); + $this->assertNotContains($portalReservation->id, $withTasks); + Mail::assertNotSent(PaymentReminder::class); + } + + /** + * @param array $attributes + */ + private function confirmed(string $arrival = '2026-12-01', string $departure = '2026-12-05', array $attributes = []): Booking + { + return Booking::factory()->for($this->property)->create([ + 'status' => BookingStatus::Confirmed, + 'arrival' => $arrival, + 'departure' => $departure, + 'deposit_due_on' => '2026-10-25', + 'balance_due_on' => '2026-11-20', + 'total' => 100000, + 'deposit' => 30000, + ...$attributes, + ]); + } + + /** + * Posts the form and opens the page it redirects to (the redirect carries the result message in the session). + * + * @param array $data + */ + private function submit(string $action, array $data = []): TestResponse + { + return $this->get($this->post($action, $data)->headers->get('Location')); + } + + private function formAction(string $pageUrl, string $action): string + { + preg_match('~action="([^"]*/'.preg_quote($action, '~').'[^"]*)"~', $this->get($pageUrl)->getContent(), $match); + $this->assertNotEmpty($match, "form for {$action} not found"); + + return html_entity_decode($match[1]); + } +}