diff --git a/app/Actions/AnonymizeGuests.php b/app/Actions/AnonymizeGuests.php index 85a6b69..8d7e767 100644 --- a/app/Actions/AnonymizeGuests.php +++ b/app/Actions/AnonymizeGuests.php @@ -22,12 +22,14 @@ public function handle(): int ->whereNull('anonymized_at') ->whereDate('created_at', '<', $cutoff) ->whereDoesntHave('bookings', fn ($query) => $query->whereDate('departure', '>=', $cutoff)) + ->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed()->whereDate('ends_on', '>=', $cutoff)) ->get(); $inquiryCutoff = now()->subMonths(config('fewo.retention.inquiry_months')); $inquiriesOnly = Guest::query() ->whereNull('anonymized_at') ->whereDoesntHave('bookings', fn ($query) => $query->whereNotNull('confirmed_at')) + ->whereDoesntHave('portalStays', fn ($query) => $query->withTrashed()) ->whereDoesntHave('bookings', fn ($query) => $query->where('updated_at', '>=', $inquiryCutoff)) ->where('updated_at', '<', $inquiryCutoff) ->get(); diff --git a/app/Actions/ApplyChannelRules.php b/app/Actions/ApplyChannelRules.php index 5444f91..b691187 100644 --- a/app/Actions/ApplyChannelRules.php +++ b/app/Actions/ApplyChannelRules.php @@ -17,7 +17,7 @@ public function attributes(Channel $channel, ?BlockedPeriod $block, array $prope $attributes = ['ical_interpretation' => $result, 'ical_event_type' => $result['event_type'], 'leading_priority' => $result['representation'] === 'leading_candidate' ? max(1, 10001 - $result['priority']) : 0]; $previousOrigin = $block?->ical_interpretation['origin_channel_id'] ?? null; - if ($block === null || ($block->reviewed_at === null && ($block->origin_channel_id === null || $block->origin_channel_id === $previousOrigin))) { + if ($block === null || ($block->occupation_kind === null && $block->reviewed_at === null && ($block->origin_channel_id === null || $block->origin_channel_id === $previousOrigin))) { $attributes['origin_channel_id'] = $result['origin_channel_id']; } diff --git a/app/Actions/AssignOccupationGuest.php b/app/Actions/AssignOccupationGuest.php new file mode 100644 index 0000000..dea3baf --- /dev/null +++ b/app/Actions/AssignOccupationGuest.php @@ -0,0 +1,45 @@ +newQuery()->whereKey($occupation->id)->lockForUpdate()->firstOrFail(); + if ($record instanceof BlockedPeriod && ($record->occupationKind() !== OccupationKind::Reservation || $record->is_representation)) { + throw ValidationException::withMessages(['guest_id' => 'Zuerst als eigenständige Portalreservierung einordnen. Darstellungen werden an der führenden Buchung gepflegt.']); + } + if ($guestId !== null) { + $guest = Guest::query()->where('tenant_id', $record->tenant_id)->whereNull('anonymized_at')->findOrFail($guestId); + Gate::authorize('view', $guest); + } else { + Gate::authorize('create', Guest::class); + $data = Validator::make($details, [ + 'first_name' => ['required', 'string', 'max:255'], + 'last_name' => ['nullable', 'string', 'max:255'], + 'email' => ['nullable', 'email', 'max:255'], + 'phone' => ['nullable', 'string', 'max:50'], + ])->validate(); + $guest = new Guest([...$data, 'last_name' => $data['last_name'] ?? '', 'email' => filled($data['email'] ?? null) ? mb_strtolower(trim($data['email'])) : null]); + $guest->forceFill(['tenant_id' => $record->tenant_id])->save(); + } + $record->forceFill(['guest_id' => $guest->id])->save(); + + return $guest; + }); + } +} diff --git a/app/Actions/ClassifyPortalOccupation.php b/app/Actions/ClassifyPortalOccupation.php new file mode 100644 index 0000000..eb5e151 --- /dev/null +++ b/app/Actions/ClassifyPortalOccupation.php @@ -0,0 +1,28 @@ +whereKey($occupation->id)->lockForUpdate()->firstOrFail(); + if (! in_array($record->source, ['channel', 'email'], true) || $record->is_representation) { + throw ValidationException::withMessages(['occupation_kind' => 'Nur eigenständige Portalereignisse können hier eingeordnet werden.']); + } + if ($originId !== null && ! Channel::query()->where('property_id', $record->property_id)->whereKey($originId)->exists()) { + throw ValidationException::withMessages(['origin_channel_id' => 'Der Ursprungskanal muss zur selben Wohnung gehören.']); + } + $record->forceFill(['occupation_kind' => $kind, 'origin_channel_id' => $originId])->save(); + }); + } +} diff --git a/app/Actions/ConfirmBooking.php b/app/Actions/ConfirmBooking.php index e7eb6f2..53c5338 100644 --- a/app/Actions/ConfirmBooking.php +++ b/app/Actions/ConfirmBooking.php @@ -28,6 +28,10 @@ public function __construct( */ public function handle(Booking $booking, bool $notifyGuest = true): void { + if ($notifyGuest && blank($booking->guest?->email)) { + throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.'); + } + 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/DeclineBooking.php b/app/Actions/DeclineBooking.php index 80870eb..b1bd9e7 100644 --- a/app/Actions/DeclineBooking.php +++ b/app/Actions/DeclineBooking.php @@ -15,6 +15,10 @@ class DeclineBooking */ public function handle(Booking $booking, bool $notifyGuest = true): void { + if ($notifyGuest && blank($booking->guest?->email)) { + throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.'); + } + if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) { throw ReservationException::invalidTransition($booking->status->getLabel(), 'abgelehnt'); } diff --git a/app/Actions/RequestReviews.php b/app/Actions/RequestReviews.php index da72b4b..70a1cd5 100644 --- a/app/Actions/RequestReviews.php +++ b/app/Actions/RequestReviews.php @@ -23,7 +23,7 @@ public function handle(): int ->whereDate('departure', '<=', $latestDeparture) ->whereDate('departure', '>', $latestDeparture->copy()->subDays(30)) ->whereDoesntHave('review') - ->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')) + ->whereHas('guest', fn ($query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', '')) ->with('guest') ->get(); diff --git a/app/Actions/SendBookingReminders.php b/app/Actions/SendBookingReminders.php index 9f81be4..f5ea022 100644 --- a/app/Actions/SendBookingReminders.php +++ b/app/Actions/SendBookingReminders.php @@ -82,7 +82,7 @@ public function handle(): array private function bookings(callable $constraints): Collection { return $constraints(Booking::query()->with(['guest', 'property', 'payments'])) - ->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')) + ->whereHas('guest', fn (Builder $query) => $query->whereNull('anonymized_at')->whereNotNull('email')->where('email', '!=', '')) ->get() ->toBase(); } diff --git a/app/Actions/SendOffer.php b/app/Actions/SendOffer.php index 0af8de8..aadaca3 100644 --- a/app/Actions/SendOffer.php +++ b/app/Actions/SendOffer.php @@ -42,6 +42,10 @@ public function __construct( */ public function handle(Booking $booking, array $changes = [], bool $sendMail = true): Booking { + if ($sendMail && blank($booking->guest?->email)) { + throw new ReservationException('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.'); + } + if (! in_array($booking->status, [BookingStatus::Reserved, BookingStatus::OfferSent, BookingStatus::Expired], true)) { throw ReservationException::invalidTransition($booking->status->getLabel(), 'als Angebot versendet'); } diff --git a/app/Availability/OccupancyOverview.php b/app/Availability/OccupancyOverview.php new file mode 100644 index 0000000..61a8b11 --- /dev/null +++ b/app/Availability/OccupancyOverview.php @@ -0,0 +1,102 @@ +> + */ + public function records(?int $propertyId = null, ?int $guestId = null, bool $includeBlocks = false, ?CarbonImmutable $from = null, ?CarbonImmutable $until = null): Collection + { + Gate::authorize('viewAny', Booking::class); + $bookings = Booking::query()->with(['guest', 'property', 'originChannel', 'importChannel'])->withCount('channelRepresentations') + ->when($propertyId, fn ($query) => $query->where('property_id', $propertyId)) + ->when($guestId, fn ($query) => $query->where('guest_id', $guestId)) + ->when($from, fn ($query) => $query->whereDate('departure', '>=', $from)) + ->when($until, fn ($query) => $query->whereDate('arrival', '<', $until)) + ->get(); + $records = collect(); + foreach ($bookings as $booking) { + $records->put($booking->id, [ + 'record_type' => 'booking', 'record_id' => $booking->id, 'reference' => $booking->reference, + 'kind' => 'booking', 'kind_label' => 'Anfrage / Buchung', + 'property_id' => $booking->property_id, 'property' => $booking->property->name, + 'arrival' => $booking->arrival->toDateString(), 'departure' => $booking->departure->toDateString(), + 'nights' => $booking->nights(), 'persons' => $booking->guests, 'total' => $booking->total, + 'guest_id' => $booking->guest_id, 'guest' => $booking->guest?->full_name ?? 'Gastzuordnung offen', + 'guest_email' => $booking->guest?->email, 'guest_assigned' => $booking->guest_id !== null, + 'source' => $booking->bookingChannelLabel(), 'status' => $booking->status->getLabel(), + 'status_key' => $booking->status->value, 'color' => $booking->status->getColor(), + 'occupies' => in_array($booking->status, BookingStatus::occupying(), true) || $booking->isHoldActive(), + 'needs_review' => false, 'review_note' => null, 'archived' => false, + 'representations' => $booking->channel_representations_count, + 'url' => BookingResource::getUrl('view', ['record' => $booking->id]), + 'guest_url' => $booking->guest_id ? GuestResource::getUrl('edit', ['record' => $booking->guest_id]) : null, + ]); + } + $blocks = BlockedPeriod::query()->select(['id', 'tenant_id', 'property_id', 'guest_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'occupation_kind', 'ical_event_type', 'ical_interpretation', 'is_representation', 'needs_review', 'review_note', 'deleted_at'])->withTrashed()->occupying()->with(['guest', 'property', 'channel', 'originChannel'])->withCount('channelRepresentations') + ->when(! $includeBlocks, fn ($query) => $query->reservations()) + ->when($propertyId, fn ($query) => $query->where('property_id', $propertyId)) + ->when($guestId, fn ($query) => $query->where('guest_id', $guestId)->reservations()) + ->when($from, fn ($query) => $query->whereDate('ends_on', '>=', $from)) + ->when($until, fn ($query) => $query->whereDate('starts_on', '<', $until)) + ->get(); + foreach ($blocks as $block) { + $kind = $block->occupationKind(); + $records->put('portal-'.$block->id, [ + 'record_type' => 'portal', 'record_id' => $block->id, + 'reference' => $block->ical_interpretation['fields']['booking_reference'] ?? 'Kalender-'.$block->id, + 'kind' => $kind->value, 'kind_label' => $kind->getLabel(), + 'property_id' => $block->property_id, 'property' => $block->property->name, + 'arrival' => $block->starts_on->toDateString(), 'departure' => $block->ends_on->toDateString(), + 'nights' => (int) $block->starts_on->diffInDays($block->ends_on), 'persons' => null, 'total' => null, + 'guest_id' => $block->guest_id, 'guest' => $block->guestName() ?? 'Gastzuordnung offen', + 'guest_email' => $block->guest?->email, 'guest_assigned' => $block->guest_id !== null, + 'source' => $block->originChannel?->name ?? $block->channel?->name ?? ($block->source === 'manual' ? 'Eigene Sperre' : 'Ursprung unbekannt'), + 'status' => $block->trashed() ? 'Nicht mehr im Kalenderfeed' : ($block->needs_review ? 'Klärung erforderlich' : 'Im Kalender geführt'), + 'status_key' => $block->trashed() ? 'archived' : 'imported', 'color' => $block->needs_review ? 'warning' : $kind->getColor(), + 'occupies' => ! $block->trashed(), 'needs_review' => $block->needs_review, 'review_note' => $block->review_note, + 'archived' => $block->trashed(), 'representations' => $block->channel_representations_count, + 'url' => $block->source === 'manual' ? BlockedPeriodResource::getUrl() : PortalOccupationResource::getUrl('view', ['record' => $block->id]), + 'guest_url' => $block->guest_id ? GuestResource::getUrl('edit', ['record' => $block->guest_id]) : null, + ]); + } + + return $records; + } + + /** @return array{month: CarbonImmutable, days: array, rows: Collection, free: int, occupied: int} */ + public function calendar(Property $property, CarbonImmutable $month): array + { + $month = $month->startOfMonth(); + $until = $month->addMonth(); + $records = $this->records($property->id, includeBlocks: true, from: $month, until: $until); + $occupying = $records->where('occupies', true); + $days = []; + for ($date = $month; $date->lessThan($until); $date = $date->addDay()) { + $day = $date->toDateString(); + $nights = $occupying->filter(fn (array $record): bool => $record['arrival'] <= $day && $day < $record['departure']); + $departures = $occupying->where('departure', $day); + $days[] = ['date' => $date, 'free' => $nights->isEmpty(), 'occupations' => $nights->values()->all(), 'departures' => $departures->values()->all(), 'overlap' => $nights->count() > 1]; + } + $free = collect($days)->where('free', true)->count(); + + return ['month' => $month, 'days' => $days, 'rows' => $records->sortBy('arrival'), 'free' => $free, 'occupied' => count($days) - $free]; + } +} diff --git a/app/Channels/ICal/ICalExportFields.php b/app/Channels/ICal/ICalExportFields.php index a1ec268..800452e 100644 --- a/app/Channels/ICal/ICalExportFields.php +++ b/app/Channels/ICal/ICalExportFields.php @@ -52,6 +52,10 @@ public function context(Booking|BlockedPeriod $occupation): array return [...$context, 'guest_first_name' => $occupation->guest?->first_name, 'guest_full_name' => $occupation->guest?->full_name, 'booking_reference' => $occupation->reference]; } $fields = array_intersect_key($occupation->ical_interpretation['fields'] ?? [], self::FIELDS); + if ($occupation->guest !== null) { + $fields['guest_first_name'] = $occupation->guest->anonymized_at === null ? $occupation->guest->first_name : null; + $fields['guest_full_name'] = $occupation->guest->anonymized_at === null && filled($occupation->guest->last_name) ? $occupation->guest->full_name : null; + } return [...$context, ...$fields]; } diff --git a/app/Channels/ICal/ICalFeed.php b/app/Channels/ICal/ICalFeed.php index 695a2ec..7127dd4 100644 --- a/app/Channels/ICal/ICalFeed.php +++ b/app/Channels/ICal/ICalFeed.php @@ -45,7 +45,7 @@ public function build(Channel $channel): string $blocks->whereNull('channel_id')->whereNull('origin_channel_id')->where('source', 'manual'); } - foreach ($blocks->with(['property', 'channel', 'originChannel'])->orderBy('id')->get() as $block) { + foreach ($blocks->with(['property', 'channel', 'originChannel', 'guest'])->orderBy('id')->get() as $block) { $events[] = $this->event("block-{$block->id}{$suffix}", $block->starts_on, $block->ends_on, $block->updated_at, (new ICalExportFields)->properties($channel, $block)); } diff --git a/app/Enums/AdminMode.php b/app/Enums/AdminMode.php index 2e33be3..e08a01f 100644 --- a/app/Enums/AdminMode.php +++ b/app/Enums/AdminMode.php @@ -2,6 +2,7 @@ namespace App\Enums; +use App\Filament\Pages\OccupancyCalendar; use App\Filament\Pages\PricesAndOffers; use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource; use App\Filament\Resources\Bookings\BookingResource; @@ -9,6 +10,7 @@ use App\Filament\Resources\ChannelTasks\ChannelTaskResource; use App\Filament\Resources\Guests\GuestResource; use App\Filament\Resources\Photos\PhotoResource; +use App\Filament\Resources\PortalOccupations\PortalOccupationResource; use App\Filament\Resources\Reviews\ReviewResource; use Filament\Support\Contracts\HasDescription; use Filament\Support\Contracts\HasLabel; @@ -27,7 +29,9 @@ enum AdminMode: string implements HasDescription, HasLabel * @var list */ public const SIMPLE_NAVIGATION = [ + OccupancyCalendar::class, BookingResource::class, + PortalOccupationResource::class, BlockedPeriodResource::class, PricesAndOffers::class, GuestResource::class, diff --git a/app/Enums/OccupationKind.php b/app/Enums/OccupationKind.php new file mode 100644 index 0000000..96f6ac4 --- /dev/null +++ b/app/Enums/OccupationKind.php @@ -0,0 +1,31 @@ + 'Portalreservierung', + self::Block => 'Sperrzeit', + self::Unknown => 'Ungeklärte Belegung', + }; + } + + public function getColor(): string + { + return match ($this) { + self::Reservation => 'info', + self::Block => 'gray', + self::Unknown => 'warning', + }; + } +} diff --git a/app/Filament/Actions/AssignGuestAction.php b/app/Filament/Actions/AssignGuestAction.php new file mode 100644 index 0000000..e903262 --- /dev/null +++ b/app/Filament/Actions/AssignGuestAction.php @@ -0,0 +1,49 @@ +label('Gast zuordnen') + ->visible(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record) + && ($record instanceof Booking || (! $record->trashed() && ! $record->is_representation && $record->occupationKind() === OccupationKind::Reservation))) + ->authorize(fn (Booking|BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) + ->modalDescription('Einen vorhandenen Gast persönlich auswählen oder einen neuen Gast anlegen. Ein Namensfragment ist kein Identitätsnachweis. Die Zuordnung versendet keine Nachricht und ändert keine Belegungszeiträume.') + ->fillForm(fn (Booking|BlockedPeriod $record): array => [ + 'mode' => 'existing', 'guest_id' => $record->guest_id, + 'first_name' => $record instanceof BlockedPeriod ? ($record->ical_interpretation['fields']['guest_first_name'] ?? '') : '', + ]) + ->schema([ + Select::make('mode')->label('Zuordnung')->options(['existing' => 'Vorhandenen Gast auswählen', 'new' => 'Neuen Gast anlegen'])->required()->live(), + Select::make('guest_id')->label('Gast')->searchable() + ->getSearchResultsUsing(fn (string $search): array => Guest::query()->whereNull('anonymized_at') + ->where(fn ($query) => $query->where('first_name', 'like', '%'.$search.'%')->orWhere('last_name', 'like', '%'.$search.'%')->orWhere('email', 'like', '%'.$search.'%')) + ->orderBy('last_name')->orderBy('id')->limit(50)->get()->mapWithKeys(fn (Guest $guest): array => [$guest->id => $guest->full_name.($guest->email ? ' · '.$guest->email : ' · E-Mail unbekannt')])->all()) + ->getOptionLabelUsing(fn ($value): ?string => Guest::find($value)?->full_name) + ->visible(fn (Get $get): bool => $get('mode') === 'existing')->required(fn (Get $get): bool => $get('mode') === 'existing'), + TextInput::make('first_name')->label('Vorname / verfügbarer Namensbestandteil')->maxLength(255) + ->visible(fn (Get $get): bool => $get('mode') === 'new')->required(fn (Get $get): bool => $get('mode') === 'new'), + TextInput::make('last_name')->label('Nachname, sofern bekannt')->maxLength(255)->visible(fn (Get $get): bool => $get('mode') === 'new'), + TextInput::make('email')->label('E-Mail, sofern bekannt')->email()->maxLength(255)->visible(fn (Get $get): bool => $get('mode') === 'new'), + TextInput::make('phone')->label('Telefon, sofern bekannt')->maxLength(50)->visible(fn (Get $get): bool => $get('mode') === 'new'), + ]) + ->action(function (Booking|BlockedPeriod $record, array $data, AssignOccupationGuest $assign): void { + $assign->handle($record, $data['mode'] === 'existing' ? (int) $data['guest_id'] : null, $data); + $record->refresh()->load('guest'); + Notification::make()->title('Gast zugeordnet')->success()->send(); + }); + } +} diff --git a/app/Filament/Pages/OccupancyCalendar.php b/app/Filament/Pages/OccupancyCalendar.php new file mode 100644 index 0000000..a637f71 --- /dev/null +++ b/app/Filament/Pages/OccupancyCalendar.php @@ -0,0 +1,71 @@ +month = $this->month ?: now()->format('Y-m'); + $this->propertyId ??= Property::query()->where('is_active', true)->value('id') ?? Property::query()->value('id'); + } + + #[Computed] + public function calendar(): ?array + { + Validator::make(['month' => $this->month], ['month' => ['required', 'date_format:Y-m']])->validate(); + if ($this->propertyId === null) { + return null; + } + + return app(OccupancyOverview::class)->calendar(Property::findOrFail($this->propertyId), CarbonImmutable::createFromFormat('!Y-m', $this->month)); + } + + public function moveMonth(int $direction): void + { + Validator::make(['month' => $this->month, 'direction' => $direction], ['month' => ['required', 'date_format:Y-m'], 'direction' => ['in:-1,1']])->validate(); + $this->month = CarbonImmutable::createFromFormat('!Y-m', $this->month)->addMonths($direction)->format('Y-m'); + unset($this->calendar); + } +} diff --git a/app/Filament/Pages/PricesAndOffers.php b/app/Filament/Pages/PricesAndOffers.php index 0f16041..d937234 100644 --- a/app/Filament/Pages/PricesAndOffers.php +++ b/app/Filament/Pages/PricesAndOffers.php @@ -39,7 +39,7 @@ class PricesAndOffers extends Page protected static ?string $slug = 'preise-und-angebote'; - protected static ?int $navigationSort = 3; + protected static ?int $navigationSort = 5; #[Url(as: 'wohnung')] public ?int $propertyId = null; diff --git a/app/Filament/Resources/BlockedPeriods/BlockedPeriodResource.php b/app/Filament/Resources/BlockedPeriods/BlockedPeriodResource.php index d1ba374..dc18294 100644 --- a/app/Filament/Resources/BlockedPeriods/BlockedPeriodResource.php +++ b/app/Filament/Resources/BlockedPeriods/BlockedPeriodResource.php @@ -6,6 +6,7 @@ use App\Channels\ICal\ICalRuleEngine; use App\Filament\Concerns\FollowsAdminMode; use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods; +use App\Filament\Resources\PortalOccupations\PortalOccupationResource; use App\Models\BlockedPeriod; use App\Models\Booking; use App\Models\Channel; @@ -30,7 +31,7 @@ use UnitEnum; /** - * All blocked periods of all apartments in one place (own use, renovation, portal occupations). + * Explicit blocks of all apartments. Imported reservations and unresolved periods have their own views. * Portal and e-mail blocks are maintained by the sync and can only be viewed here. */ class BlockedPeriodResource extends Resource @@ -47,7 +48,7 @@ class BlockedPeriodResource extends Resource protected static ?string $pluralModelLabel = 'Sperrzeiten'; - protected static ?int $navigationSort = 2; + protected static ?int $navigationSort = 3; public static function form(Schema $schema): Schema { @@ -72,82 +73,73 @@ public static function form(Schema $schema): Schema ]); } + public static function getEloquentQuery(): Builder + { + return parent::getEloquentQuery()->explicitBlocks()->occupying(); + } + public static function table(Table $table): Table { return $table - ->description('Zeiträume, in denen die Wohnung nicht vermietet wird. Belegungen aus Portalen erscheinen hier automatisch.') + ->description('Eigennutzung, Wartung und ausdrücklich als Sperrzeit bestätigte Zeiträume. Portalreservierungen stehen unter Anfragen & Buchungen; unbekannte Zeiten unter Ungeklärte Belegungen.') ->defaultSort('starts_on') ->columns([ TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y')->sortable(), - TextColumn::make('ends_on')->label('Bis')->date('D, d.m.Y'), + TextColumn::make('ends_on')->label('Bis / erster freier Tag')->date('D, d.m.Y'), TextColumn::make('reason')->label('Grund')->placeholder('–'), - TextColumn::make('property.name')->label('Wohnung')->visible(fn (): bool => Property::query()->count() > 1), - TextColumn::make('source') - ->label('Quelle') - ->formatStateUsing(fn (string $state): string => match ($state) { - 'manual' => 'von Hand', - 'channel' => 'Portal-Kalender', - 'email' => 'Portal-E-Mail', - default => $state, - }) - ->badge(), - TextColumn::make('channel.name')->label('Importkanal')->placeholder('Eigene Sperre'), - TextColumn::make('originChannel.name')->label('Ursprungskanal')->placeholder('Unbekannt')->toggleable(), - TextColumn::make('id')->label('Interne Sperr-ID')->toggleable(isToggledHiddenByDefault: true), - TextColumn::make('external_uid')->label('Externe UID')->limit(30)->toggleable(), - TextColumn::make('ical_event_type')->label('Erkannt als')->formatStateUsing(fn (?string $state): string => ICalRuleEngine::TYPES[$state] ?? 'Nicht erkannt')->badge(), - TextColumn::make('guest_fragment')->label('Verfügbare Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->ical_interpretation['fields']['guest_full_name'] ?? $record->ical_interpretation['fields']['guest_first_name'] ?? null)->placeholder('Unbekannt')->toggleable(), - TextColumn::make('occupation_state')->label('Belegungsführung')->state(fn (BlockedPeriod $record): string => $record->is_representation - ? ($record->linked_booking_id ? 'Darstellung von Buchung #'.$record->linked_booking_id : 'Darstellung von Sperre #'.$record->canonical_block_id) - : ($record->export_approved ? 'Führende Belegung' : 'Intern gesperrt – Export erst klären'))->badge(), - TextColumn::make('needs_review')->label('Prüfung')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->badge() - ->description(fn (BlockedPeriod $record): ?string => $record->review_note), + TextColumn::make('property.name')->label('Wohnung'), + TextColumn::make('channel.name')->label('Kalenderquelle')->placeholder('Eigene Sperre'), ]) ->filters([ - Filter::make('needs_review')->label('Nur Prüffälle')->query(fn (Builder $query): Builder => $query->where('needs_review', true)), - Filter::make('upcoming') - ->label('Nur kommende') - ->default() + Filter::make('upcoming')->label('Nur kommende')->default() ->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())), ]) ->recordActions([ - Action::make('icalOriginal')->label('iCal-Original & Erkennung')->visible(fn (BlockedPeriod $record): bool => $record->ical_raw !== null) - ->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->schema([ - TextEntry::make('recognized_rule')->label('Treffende Regel')->state(fn (BlockedPeriod $record): string => $record->ical_interpretation['rule'] ?? 'Keine'), - TextEntry::make('recognized_representation')->label('Fachliche Einordnung')->state(fn (BlockedPeriod $record): string => ICalRuleEngine::REPRESENTATIONS[$record->ical_interpretation['representation'] ?? 'unspecified']), - TextEntry::make('original')->label('Originalereignis (entfaltet)')->state(fn (BlockedPeriod $record): string => $record->ical_raw)->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']), - ]), - Action::make('resolve')->label('Belegung zuordnen / klären') - ->visible(fn (BlockedPeriod $record): bool => in_array($record->source, ['channel', 'email'], true)) - ->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) - ->modalDescription('Nur nach persönlicher Prüfung zuordnen. Eine Darstellung steuert keine eigene Belegung mehr; die führende Buchung oder Sperre übernimmt Änderungen und Stornierungen. Kalenderereignisse und UIDs bleiben nachvollziehbar erhalten.') - ->schema([ - Select::make('resolution')->label('Fachliche Klärung')->options(['independent' => 'Eigenständige Belegung bestätigen', 'block' => 'Weitere Darstellung einer vorhandenen Sperre', 'booking' => 'Weitere Darstellung einer vorhandenen Buchung'])->default('independent')->required()->live(), - Select::make('target_id')->label('Führende Belegung mit demselben Zeitraum') - ->visible(fn (Get $get): bool => $get('resolution') !== 'independent') - ->required(fn (Get $get): bool => $get('resolution') !== 'independent') - ->options(function (BlockedPeriod $record, Get $get): array { - if ($get('resolution') === 'booking') { - return Booking::query()->where('property_id', $record->property_id)->occupying()->whereDate('arrival', $record->starts_on)->whereDate('departure', $record->ends_on)->get() - ->mapWithKeys(fn (Booking $booking): array => [$booking->id => 'Buchung '.$booking->reference])->all(); - } - - return BlockedPeriod::query()->where('property_id', $record->property_id)->occupying()->whereKeyNot($record->id)->whereDate('starts_on', $record->starts_on)->whereDate('ends_on', $record->ends_on)->orderByDesc('leading_priority')->orderBy('id')->get() - ->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.($block->reason ?? 'Sperre').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all(); - }), - Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt') - ->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all()) - ->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'), - ]) - ->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void { - $resolve->handle($record, $data['resolution'], filled($data['target_id'] ?? null) ? (int) $data['target_id'] : null, filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null); - Notification::make()->title('Belegungszuordnung gespeichert')->success()->send(); - }), + Action::make('viewPortal')->label('Details')->visible(fn (BlockedPeriod $record): bool => $record->source !== 'manual') + ->url(fn (BlockedPeriod $record): string => PortalOccupationResource::getUrl('view', ['record' => $record->id])), EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'), DeleteAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'), ]); } + public static function portalActions(): array + { + return [ + Action::make('icalOriginal')->label('iCal-Original & Erkennung')->visible(fn (BlockedPeriod $record): bool => $record->ical_raw !== null) + ->modalSubmitAction(false)->modalCancelActionLabel('Schließen')->schema([ + TextEntry::make('recognized_rule')->label('Treffende Regel')->state(fn (BlockedPeriod $record): string => $record->ical_interpretation['rule'] ?? 'Keine'), + TextEntry::make('recognized_representation')->label('Fachliche Einordnung')->state(fn (BlockedPeriod $record): string => ICalRuleEngine::REPRESENTATIONS[$record->ical_interpretation['representation'] ?? 'unspecified']), + TextEntry::make('original')->label('Originalereignis (entfaltet)')->state(fn (BlockedPeriod $record): string => $record->ical_raw)->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']), + ]), + Action::make('resolve')->label('Belegung zuordnen / klären') + ->visible(fn (BlockedPeriod $record): bool => ! $record->trashed() && in_array($record->source, ['channel', 'email'], true)) + ->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) + ->modalDescription('Nur nach persönlicher Prüfung zuordnen. Eine Darstellung steuert keine eigene Belegung mehr; die führende Buchung oder Sperre übernimmt Änderungen und Stornierungen. Kalenderereignisse und UIDs bleiben nachvollziehbar erhalten.') + ->schema([ + Select::make('resolution')->label('Fachliche Klärung')->options(['independent' => 'Eigenständige Belegung bestätigen', 'block' => 'Weitere Darstellung einer vorhandenen Sperre', 'booking' => 'Weitere Darstellung einer vorhandenen Buchung'])->default('independent')->required()->live(), + Select::make('target_id')->label('Führende Belegung mit demselben Zeitraum') + ->visible(fn (Get $get): bool => $get('resolution') !== 'independent') + ->required(fn (Get $get): bool => $get('resolution') !== 'independent') + ->options(function (BlockedPeriod $record, Get $get): array { + if ($get('resolution') === 'booking') { + return Booking::query()->where('property_id', $record->property_id)->occupying()->whereDate('arrival', $record->starts_on)->whereDate('departure', $record->ends_on)->get() + ->mapWithKeys(fn (Booking $booking): array => [$booking->id => 'Buchung '.$booking->reference])->all(); + } + + return BlockedPeriod::query()->where('property_id', $record->property_id)->occupying()->whereKeyNot($record->id)->whereDate('starts_on', $record->starts_on)->whereDate('ends_on', $record->ends_on)->orderByDesc('leading_priority')->orderBy('id')->get() + ->mapWithKeys(fn (BlockedPeriod $block): array => [$block->id => '#'.$block->id.' · '.($block->reason ?? 'Sperre').($block->leading_priority ? ' · bevorzugter Führungskandidat' : '')])->all(); + }), + Select::make('origin_channel_id')->label('Ursprünglicher Buchungskanal, sofern persönlich bekannt') + ->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all()) + ->default(fn (BlockedPeriod $record): ?int => $record->origin_channel_id)->placeholder('Unbekannt / eigene Vermietung'), + ]) + ->action(function (BlockedPeriod $record, array $data, ResolveChannelOccupation $resolve): void { + $resolve->handle($record, $data['resolution'], filled($data['target_id'] ?? null) ? (int) $data['target_id'] : null, filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null); + Notification::make()->title('Belegungszuordnung gespeichert')->success()->send(); + }), + ]; + } + public static function getPages(): array { return [ diff --git a/app/Filament/Resources/Bookings/Pages/ListBookings.php b/app/Filament/Resources/Bookings/Pages/ListBookings.php index 95ca200..7d5b1c6 100644 --- a/app/Filament/Resources/Bookings/Pages/ListBookings.php +++ b/app/Filament/Resources/Bookings/Pages/ListBookings.php @@ -2,7 +2,9 @@ namespace App\Filament\Resources\Bookings\Pages; +use App\Filament\Pages\OccupancyCalendar; use App\Filament\Resources\Bookings\BookingResource; +use Filament\Actions\Action; use Filament\Actions\CreateAction; use Filament\Resources\Pages\ListRecords; @@ -13,6 +15,7 @@ class ListBookings extends ListRecords protected function getHeaderActions(): array { return [ + Action::make('calendar')->label('Belegungsplan')->url(OccupancyCalendar::getUrl()), CreateAction::make(), ]; } diff --git a/app/Filament/Resources/Bookings/Pages/ViewBooking.php b/app/Filament/Resources/Bookings/Pages/ViewBooking.php index deed588..b6390d0 100644 --- a/app/Filament/Resources/Bookings/Pages/ViewBooking.php +++ b/app/Filament/Resources/Bookings/Pages/ViewBooking.php @@ -8,6 +8,7 @@ use App\Documents\RentalContract; use App\Enums\BookingStatus; use App\Exceptions\ReservationException; +use App\Filament\Actions\AssignGuestAction; use App\Filament\Resources\Bookings\BookingResource; use App\Models\Booking; use App\Pricing\PriceCalculator; @@ -45,6 +46,7 @@ public function getTitle(): string protected function getHeaderActions(): array { return [ + AssignGuestAction::make(), Action::make('sendOffer') ->label(fn (): string => $this->record->status === BookingStatus::OfferSent ? 'Angebot ändern & neu senden' : 'Angebot senden') ->icon(Heroicon::OutlinedPaperAirplane) diff --git a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php index 10ad312..bd1ebdb 100644 --- a/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php +++ b/app/Filament/Resources/Bookings/Schemas/BookingInfolist.php @@ -68,7 +68,7 @@ public static function configure(Schema $schema): Schema TextEntry::make('hold_expires_at')->label('Vorgemerkt bis')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->hold_expires_at !== null), TextEntry::make('confirmed_at')->label('Bestätigt am')->dateTime('d.m.Y, H:i')->visible(fn (Booking $record): bool => $record->confirmed_at !== null), TextEntry::make('created_at')->label('Eingegangen')->dateTime('d.m.Y, H:i'), - TextEntry::make('source')->label('Quelle'), + TextEntry::make('source')->label('Buchungskanal / Quelle')->state(fn (Booking $record): string => $record->bookingChannelLabel()), TextEntry::make('referral_source')->label('Aufmerksam geworden durch')->placeholder('–'), TextEntry::make('utm') ->label('Kampagne (UTM)') @@ -78,7 +78,7 @@ public static function configure(Schema $schema): Schema Section::make('Gast') ->schema([ TextEntry::make('guest.full_name')->label('Name'), - TextEntry::make('guest.email')->label('E-Mail')->copyable(), + TextEntry::make('guest.email')->label('E-Mail')->placeholder('Unbekannt')->copyable(), TextEntry::make('guest.phone')->label('Telefon')->placeholder('–'), TextEntry::make('guest_address') ->label('Adresse') diff --git a/app/Filament/Resources/Bookings/Tables/BookingsTable.php b/app/Filament/Resources/Bookings/Tables/BookingsTable.php index 02b5b82..c63fdc1 100644 --- a/app/Filament/Resources/Bookings/Tables/BookingsTable.php +++ b/app/Filament/Resources/Bookings/Tables/BookingsTable.php @@ -2,72 +2,73 @@ namespace App\Filament\Resources\Bookings\Tables; +use App\Availability\OccupancyOverview; use App\Enums\BookingStatus; -use App\Models\Booking; -use App\Support\Money; -use Filament\Actions\ViewAction; +use App\Models\Property; +use Filament\Actions\Action; use Filament\Tables\Columns\TextColumn; use Filament\Tables\Filters\Filter; use Filament\Tables\Filters\SelectFilter; use Filament\Tables\Table; -use Illuminate\Database\Eloquent\Builder; +use Illuminate\Pagination\LengthAwarePaginator; class BookingsTable { - public static function configure(Table $table): Table + public static function configure(Table $table, ?int $guestId = null): Table { return $table - ->modifyQueryUsing(fn (Builder $query): Builder => $query->with(['guest', 'property', 'payments'])) - ->defaultSort('created_at', 'desc') + ->description('Eigene Anfragen und Buchungen sowie erkannte Portalreservierungen in einer Liste. Fehlende Gastzuordnungen lassen sich in den Details ergänzen; unbekannte Belegungen haben einen eigenen Klärungsbereich.') + ->records(function (?string $search, ?string $sortColumn, ?string $sortDirection, array $filters, int $page, int|string $recordsPerPage) use ($guestId, $table): LengthAwarePaginator { + $propertyId = filled($filters['property']['value'] ?? null) ? (int) $filters['property']['value'] : null; + $records = app(OccupancyOverview::class)->records($propertyId, $guestId); + if (filled($search)) { + $term = mb_strtolower($search); + $records = $records->filter(fn (array $record): bool => str_contains(mb_strtolower(implode(' ', [$record['reference'], $record['guest'], $record['guest_email'], $record['source'], $record['property']])), $term)); + } + if ($filters['upcoming']['isActive'] ?? false) { + $records = $records->filter(fn (array $record): bool => $record['departure'] >= today()->toDateString()); + } + if ($filters['without_guest']['isActive'] ?? false) { + $records = $records->where('guest_assigned', false); + } + if (filled($filters['kind']['value'] ?? null)) { + $records = $records->where('record_type', $filters['kind']['value']); + } + if (filled($filters['status']['values'] ?? [])) { + $records = $records->whereIn('status_key', $filters['status']['values']); + } + $column = in_array($sortColumn, ['arrival', 'departure', 'reference', 'guest', 'source', 'total'], true) ? $sortColumn : 'arrival'; + $records = $records->sortBy($column, SORT_REGULAR, $sortDirection === 'desc'); + $perPage = $recordsPerPage === 'all' ? max(1, $records->count()) : $recordsPerPage; + + return new LengthAwarePaginator($records->forPage($page, $perPage), $records->count(), $perPage, $page, ['pageName' => $table->getLivewire()->getTablePaginationPageName()]); + }) + ->defaultSort('arrival')->searchable()->recordAction(null) ->columns([ - TextColumn::make('reference') - ->label('Nr.') - ->searchable(), - TextColumn::make('status') - ->label('Status') - ->badge() - ->description(fn (Booking $record): ?string => $record->isHoldActive() ? 'bis '.$record->hold_expires_at->format('d.m. H:i') : null), - TextColumn::make('guest.last_name') - ->label('Gast') - ->formatStateUsing(fn (Booking $record): string => $record->guest->full_name) - ->description(fn (Booking $record): string => $record->guest->email) - ->searchable(['first_name', 'last_name', 'email']), - TextColumn::make('property.name') - ->label('Wohnung') - ->toggleable(isToggledHiddenByDefault: true), - TextColumn::make('arrival') - ->label('Anreise') - ->date('D, d.m.Y') - ->sortable(), - TextColumn::make('departure') - ->label('Abreise') - ->date('D, d.m.Y') - ->description(fn (Booking $record): string => $record->nights().' Nächte'), - TextColumn::make('guests') - ->label('Pers.'), - TextColumn::make('total') - ->label('Gesamt') - ->money('EUR', divideBy: 100, locale: 'de') - ->description(fn (Booking $record): ?string => in_array($record->status, BookingStatus::occupying(), true) && $record->openAmount() > 0 ? 'offen '.Money::format($record->openAmount()) : null), - TextColumn::make('source') - ->label('Quelle') - ->toggleable(isToggledHiddenByDefault: true), - TextColumn::make('created_at') - ->label('Eingang') - ->since() - ->sortable(), + TextColumn::make('reference')->label('Nr. / Referenz')->sortable(), + TextColumn::make('kind_label')->label('Art')->badge(), + TextColumn::make('status')->label('Status')->badge()->color(fn (array $record): string => $record['color']), + TextColumn::make('guest')->label('Gast / Namensinformation')->sortable() + ->description(fn (array $record): string => $record['guest_assigned'] ? ($record['guest_email'] ?? 'E-Mail unbekannt') : 'Gastzuordnung offen'), + TextColumn::make('source')->label('Buchungskanal / Quelle')->sortable(), + TextColumn::make('arrival')->label('Anreise')->date('d.m.Y')->sortable(), + TextColumn::make('departure')->label('Abreise')->date('d.m.Y')->sortable() + ->description(fn (array $record): string => $record['nights'].' Nächte'), + TextColumn::make('persons')->label('Personen')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true), + TextColumn::make('total')->label('Bekannter Gesamtpreis')->money('EUR', divideBy: 100, locale: 'de')->placeholder('Unbekannt')->toggleable(isToggledHiddenByDefault: true), + TextColumn::make('property')->label('Wohnung')->toggleable(isToggledHiddenByDefault: true), ]) ->filters([ - SelectFilter::make('status') - ->label('Status') - ->options(BookingStatus::class) - ->multiple(), - Filter::make('upcoming') - ->label('Nur kommende Aufenthalte') - ->query(fn (Builder $query): Builder => $query->whereDate('departure', '>=', today())), + SelectFilter::make('property')->label('Wohnung')->options(fn (): array => Property::query()->orderBy('name')->pluck('name', 'id')->all()), + SelectFilter::make('kind')->label('Buchungsweg')->options(['booking' => 'Eigene Anfragen & Buchungen', 'portal' => 'Portalreservierungen']), + SelectFilter::make('status')->label('Status')->multiple()->options([ + ...collect(BookingStatus::cases())->mapWithKeys(fn (BookingStatus $status): array => [$status->value => $status->getLabel()])->all(), + 'imported' => 'Im Portalkalender geführt', 'archived' => 'Nicht mehr im Kalenderfeed', + ]), + Filter::make('upcoming')->label('Nur kommende Aufenthalte'), + Filter::make('without_guest')->label('Gastzuordnung offen'), ]) - ->recordActions([ - ViewAction::make(), - ]); + ->recordUrl(fn (array $record): string => $record['url']) + ->recordActions([Action::make('view')->label('Details')->url(fn (array $record): string => $record['url'])]); } } diff --git a/app/Filament/Resources/Guests/GuestResource.php b/app/Filament/Resources/Guests/GuestResource.php index cf52f88..e79a2eb 100644 --- a/app/Filament/Resources/Guests/GuestResource.php +++ b/app/Filament/Resources/Guests/GuestResource.php @@ -33,7 +33,7 @@ class GuestResource extends Resource protected static ?string $recordTitleAttribute = 'last_name'; - protected static ?int $navigationSort = 2; + protected static ?int $navigationSort = 4; public static function form(Schema $schema): Schema { diff --git a/app/Filament/Resources/Guests/RelationManagers/BookingsRelationManager.php b/app/Filament/Resources/Guests/RelationManagers/BookingsRelationManager.php index e2d5381..7fc75db 100644 --- a/app/Filament/Resources/Guests/RelationManagers/BookingsRelationManager.php +++ b/app/Filament/Resources/Guests/RelationManagers/BookingsRelationManager.php @@ -2,11 +2,8 @@ namespace App\Filament\Resources\Guests\RelationManagers; -use App\Filament\Resources\Bookings\BookingResource; -use App\Models\Booking; -use Filament\Actions\ViewAction; +use App\Filament\Resources\Bookings\Tables\BookingsTable; use Filament\Resources\RelationManagers\RelationManager; -use Filament\Tables\Columns\TextColumn; use Filament\Tables\Table; class BookingsRelationManager extends RelationManager @@ -22,18 +19,6 @@ public function isReadOnly(): bool public function table(Table $table): Table { - return $table - ->recordTitleAttribute('reference') - ->columns([ - TextColumn::make('reference')->label('Nr.'), - TextColumn::make('arrival')->label('Anreise')->date('d.m.Y'), - TextColumn::make('departure')->label('Abreise')->date('d.m.Y'), - TextColumn::make('guests')->label('Pers.'), - TextColumn::make('status')->label('Status')->badge(), - TextColumn::make('total')->label('Gesamt')->money('EUR', divideBy: 100, locale: 'de'), - ]) - ->recordActions([ - ViewAction::make()->url(fn (Booking $record): string => BookingResource::getUrl('view', ['record' => $record])), - ]); + return BookingsTable::configure($table, $this->getOwnerRecord()->id); } } diff --git a/app/Filament/Resources/Guests/Schemas/GuestForm.php b/app/Filament/Resources/Guests/Schemas/GuestForm.php index a590df2..0590d5e 100644 --- a/app/Filament/Resources/Guests/Schemas/GuestForm.php +++ b/app/Filament/Resources/Guests/Schemas/GuestForm.php @@ -23,8 +23,8 @@ public static function configure(Schema $schema): Schema ->columns(2) ->schema([ TextInput::make('first_name')->label('Vorname')->required()->maxLength(255), - TextInput::make('last_name')->label('Nachname')->required()->maxLength(255), - TextInput::make('email')->label('E-Mail')->email()->required()->maxLength(255), + TextInput::make('last_name')->label('Nachname')->maxLength(255)->dehydrateStateUsing(fn (?string $state): string => $state ?? ''), + TextInput::make('email')->label('E-Mail')->email()->maxLength(255)->dehydrateStateUsing(fn (?string $state): ?string => filled($state) ? $state : null)->helperText('Bei Portalgästen gegebenenfalls noch unbekannt. Keine Ersatzadresse eintragen.'), TextInput::make('phone')->label('Telefon')->tel()->maxLength(50), TextInput::make('street')->label('Straße')->maxLength(255), TextInput::make('postal_code')->label('PLZ')->maxLength(20), diff --git a/app/Filament/Resources/Guests/Tables/GuestsTable.php b/app/Filament/Resources/Guests/Tables/GuestsTable.php index 60429cc..f242118 100644 --- a/app/Filament/Resources/Guests/Tables/GuestsTable.php +++ b/app/Filament/Resources/Guests/Tables/GuestsTable.php @@ -20,25 +20,26 @@ public static function configure(Table $table): Table $countedBookings = ['bookings' => fn (Builder $query): Builder => $query->whereIn('status', BookingStatus::occupying())]; return $table + ->modifyQueryUsing(fn (Builder $query): Builder => $query->withCount('portalStays')) ->defaultSort('last_name') ->columns([ TextColumn::make('last_name') ->label('Name') - ->formatStateUsing(fn (Guest $record): string => "{$record->last_name}, {$record->first_name}") - ->description(fn (Guest $record): string => $record->email) + ->formatStateUsing(fn (Guest $record): string => $record->full_name) + ->description(fn (Guest $record): string => $record->email ?? 'E-Mail unbekannt') ->searchable(['first_name', 'last_name', 'email']) ->sortable(), TextColumn::make('phone')->label('Telefon')->placeholder('–'), TextColumn::make('city')->label('Ort')->placeholder('–')->toggleable(), TextColumn::make('tags')->label('Markierungen')->badge(), - TextColumn::make('bookings_count')->label('Aufenthalte')->counts($countedBookings)->sortable(), - TextColumn::make('bookings_sum_total')->label('Umsatz')->sum($countedBookings, 'total')->money('EUR', divideBy: 100, locale: 'de')->sortable(), + TextColumn::make('bookings_count')->label('Aufenthalte')->counts($countedBookings)->formatStateUsing(fn (Guest $record, int $state): int => $state + $record->portal_stays_count)->description('Eigene und zugeordnete Portalaufenthalte'), + TextColumn::make('bookings_sum_total')->label('Umsatz eigener Buchungen')->sum($countedBookings, 'total')->money('EUR', divideBy: 100, locale: 'de')->sortable(), IconColumn::make('marketing_consent_at')->label('Angebote')->boolean()->getStateUsing(fn (Guest $record): bool => $record->marketing_consent_at !== null), ]) ->filters([ Filter::make('returning') ->label('Stammgäste (ab 2 Aufenthalten)') - ->query(fn (Builder $query): Builder => $query->has('bookings', '>=', 2)), + ->query(fn (Builder $query): Builder => $query->where(fn (Builder $query) => $query->whereHas('bookings', fn (Builder $query) => $query->whereIn('status', BookingStatus::occupying()), '>=', 2)->orWhereHas('portalStays', null, '>=', 2)->orWhere(fn (Builder $query) => $query->whereHas('bookings', fn (Builder $query) => $query->whereIn('status', BookingStatus::occupying()))->whereHas('portalStays')))), TernaryFilter::make('marketing_consent_at') ->label('Einwilligung Angebote') ->nullable(), diff --git a/app/Filament/Resources/PortalOccupations/Pages/ManagePortalOccupations.php b/app/Filament/Resources/PortalOccupations/Pages/ManagePortalOccupations.php new file mode 100644 index 0000000..9c72830 --- /dev/null +++ b/app/Filament/Resources/PortalOccupations/Pages/ManagePortalOccupations.php @@ -0,0 +1,27 @@ + Tab::make('Ungeklärt')->modifyQueryUsing(fn (Builder $query) => $query->whereNull('deleted_at')->unclear()), + 'all' => Tab::make('Alle Importereignisse')->modifyQueryUsing(fn (Builder $query) => $query->whereNull('deleted_at')), + 'archive' => Tab::make('Nicht mehr im Feed')->modifyQueryUsing(fn (Builder $query) => $query->onlyTrashed()), + ]; + } + + protected function getHeaderActions(): array + { + return []; + } +} diff --git a/app/Filament/Resources/PortalOccupations/Pages/ViewPortalOccupation.php b/app/Filament/Resources/PortalOccupations/Pages/ViewPortalOccupation.php new file mode 100644 index 0000000..1cc1f81 --- /dev/null +++ b/app/Filament/Resources/PortalOccupations/Pages/ViewPortalOccupation.php @@ -0,0 +1,21 @@ +record->occupationKind()->getLabel().' · '.$this->record->starts_on->format('d.m.Y').'–'.$this->record->ends_on->format('d.m.Y'); + } + + protected function getHeaderActions(): array + { + return PortalOccupationResource::occupationActions(); + } +} diff --git a/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php new file mode 100644 index 0000000..33e8c1d --- /dev/null +++ b/app/Filament/Resources/PortalOccupations/PortalOccupationResource.php @@ -0,0 +1,133 @@ +withTrashed()->whereIn('source', ['channel', 'email'])->with(['guest', 'channel', 'originChannel', 'property', 'linkedBooking.guest', 'canonicalBlock.guest']); + } + + public static function getNavigationBadge(): ?string + { + $count = BlockedPeriod::query()->unclear()->count(); + + return $count ? (string) $count : null; + } + + public static function getNavigationBadgeColor(): string + { + return 'warning'; + } + + public static function table(Table $table): Table + { + return $table->description('Unbekannte Belegungen und mögliche Mehrfachdarstellungen persönlich klären. Auch ungeklärte führende Einträge halten ihre Nächte belegt.') + ->defaultSort('starts_on')->columns([ + TextColumn::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y')->sortable(), + TextColumn::make('ends_on')->label('Abreise / Ende')->date('d.m.Y'), + TextColumn::make('business_kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->occupationKind()->getLabel())->badge(), + TextColumn::make('guest_name')->label('Gast / Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->guestName())->placeholder('Zuordnung offen') + ->description(fn (BlockedPeriod $record): string => $record->guest_id ? 'Gast zugeordnet' : 'Keine bestätigte Gastzuordnung'), + TextColumn::make('channel.name')->label('Importkanal'), + TextColumn::make('property.name')->label('Wohnung')->toggleable(), + TextColumn::make('needs_review')->label('Prüffall')->formatStateUsing(fn (bool $state): string => $state ? 'Bitte prüfen' : '–')->description(fn (BlockedPeriod $record): ?string => $record->review_note), + ])->recordActions([ViewAction::make(), ActionGroup::make(static::occupationActions())->label('Weitere Aktionen')]); + } + + public static function occupationActions(): array + { + return [ + AssignGuestAction::make(), + Action::make('classify')->label('Belegungsart festlegen') + ->visible(fn (BlockedPeriod $record): bool => ! $record->is_representation && ! $record->trashed()) + ->authorize(fn (BlockedPeriod $record): bool => auth()->user()?->can('update', $record) ?? false) + ->modalDescription('Nur bekannte Sachverhalte bestätigen. Die Einordnung ändert keine Termine, hebt keine Sperre auf und führt keine Ereignisse automatisch zusammen. Überschneidungen bleiben gesonderte Prüffälle.') + ->fillForm(fn (BlockedPeriod $record): array => ['occupation_kind' => $record->occupationKind()->value, 'origin_channel_id' => $record->origin_channel_id]) + ->schema([ + Select::make('occupation_kind')->label('Fachliche Einordnung')->options(OccupationKind::class)->required(), + Select::make('origin_channel_id')->label('Buchungskanal, sofern persönlich bekannt')->placeholder('Unbekannt') + ->options(fn (BlockedPeriod $record): array => Channel::query()->where('property_id', $record->property_id)->pluck('name', 'id')->all()), + ])->action(function (BlockedPeriod $record, array $data, ClassifyPortalOccupation $classify): void { + $classify->handle($record, $data['occupation_kind'] instanceof OccupationKind ? $data['occupation_kind'] : OccupationKind::from($data['occupation_kind']), filled($data['origin_channel_id'] ?? null) ? (int) $data['origin_channel_id'] : null); + $record->refresh(); + Notification::make()->title('Belegungsart gespeichert')->success()->send(); + }), + ...BlockedPeriodResource::portalActions(), + ]; + } + + public static function infolist(Schema $schema): Schema + { + return $schema->components([ + Section::make('Portalbelegung')->columns(3)->schema([ + TextEntry::make('property.name')->label('Wohnung'), + TextEntry::make('starts_on')->label('Anreise / Beginn')->date('d.m.Y'), + TextEntry::make('ends_on')->label('Abreise / erster freier Tag')->date('d.m.Y'), + TextEntry::make('kind')->label('Einordnung')->state(fn (BlockedPeriod $record): string => $record->occupationKind()->getLabel()), + TextEntry::make('originChannel.name')->label('Bestätigter Buchungskanal')->placeholder('Unbekannt'), + TextEntry::make('channel.name')->label('Importiert über'), + TextEntry::make('guest_name')->label('Gast / Namensinformation')->state(fn (BlockedPeriod $record): ?string => $record->guestName())->placeholder('Unbekannt'), + TextEntry::make('guest_email')->label('E-Mail')->state(fn (BlockedPeriod $record): ?string => $record->assignedGuest()?->email)->placeholder('Unbekannt'), + TextEntry::make('assignment')->label('Gastzuordnung')->state(fn (BlockedPeriod $record): string => $record->is_representation ? 'Wird an der führenden Belegung gepflegt' : ($record->guest_id ? 'Persönlich zugeordnet' : 'Noch offen; Namensfragment allein ist kein Identitätsnachweis')), + TextEntry::make('calendar_state')->label('Kalenderstatus')->state(fn (BlockedPeriod $record): string => $record->trashed() ? 'Nicht mehr im Feed – keine Aussage über den Stornogrund' : ($record->is_representation ? 'Weitere Darstellung einer führenden Belegung' : 'Belegt den Zeitraum')), + TextEntry::make('leading_record')->label('Führende Belegung')->state(fn (BlockedPeriod $record): string => $record->linkedBooking ? 'Buchung '.$record->linkedBooking->reference : ($record->canonical_block_id ? 'Kalenderbelegung #'.$record->canonical_block_id : 'Dieser Eintrag')) + ->url(fn (BlockedPeriod $record): ?string => $record->linked_booking_id ? BookingResource::getUrl('view', ['record' => $record->linked_booking_id]) : null), + TextEntry::make('review_note')->label('Prüfhinweis')->placeholder('Kein zusätzlicher Prüfhinweis')->columnSpanFull(), + ]), + Section::make('Kalenderquelle')->schema([ + TextEntry::make('external_uid')->label('Externe Ereignis-ID'), + TextEntry::make('import_note')->hiddenLabel()->state('Kalenderdaten liefern Belegungszeiträume. Preis, Personenanzahl, Zahlungsstand und Vertragsstatus sind daraus nicht gesichert bekannt.'), + TextEntry::make('ical_raw')->label('Originalereignis')->placeholder('Keine iCal-Originaldaten vorhanden')->wrap()->extraAttributes(['style' => 'white-space:pre-wrap;overflow-wrap:anywhere']), + ]), + ]); + } + + public static function getPages(): array + { + return ['index' => ManagePortalOccupations::route('/'), 'view' => ViewPortalOccupation::route('/{record}')]; + } +} diff --git a/app/Filament/Resources/Properties/RelationManagers/BlockedPeriodsRelationManager.php b/app/Filament/Resources/Properties/RelationManagers/BlockedPeriodsRelationManager.php index c3d98c7..d7b02b9 100644 --- a/app/Filament/Resources/Properties/RelationManagers/BlockedPeriodsRelationManager.php +++ b/app/Filament/Resources/Properties/RelationManagers/BlockedPeriodsRelationManager.php @@ -48,8 +48,9 @@ public function form(Schema $schema): Schema public function table(Table $table): Table { return $table + ->modifyQueryUsing(fn (Builder $query): Builder => $query->explicitBlocks()->occupying()) ->recordTitleAttribute('reason') - ->description('Manuelle Sperren (z. B. Eigennutzung). Belegungen aus Portalen erscheinen hier später automatisch.') + ->description('Ausdrückliche Sperrzeiten. Alle Belegungen stehen im Belegungsplan; Portalreservierungen unter Anfragen & Buchungen.') ->defaultSort('starts_on') ->columns([ TextColumn::make('starts_on')->label('Von')->date('D, d.m.Y'), @@ -64,7 +65,7 @@ public function table(Table $table): Table ->query(fn (Builder $query): Builder => $query->whereDate('ends_on', '>=', today())), ]) ->headerActions([ - CreateAction::make(), + CreateAction::make()->mutateDataUsing(fn (array $data): array => [...$data, 'source' => 'manual']), ]) ->recordActions([ EditAction::make()->visible(fn (BlockedPeriod $record): bool => $record->source === 'manual'), diff --git a/app/Models/BlockedPeriod.php b/app/Models/BlockedPeriod.php index b7934a1..28868df 100644 --- a/app/Models/BlockedPeriod.php +++ b/app/Models/BlockedPeriod.php @@ -2,6 +2,7 @@ namespace App\Models; +use App\Enums\OccupationKind; use App\Models\Concerns\BelongsToTenant; use App\Models\Concerns\HasChannelProvenance; use App\Observers\BlockedPeriodObserver; @@ -15,6 +16,7 @@ use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; +use Illuminate\Database\Eloquent\Relations\HasMany; use Illuminate\Database\Eloquent\SoftDeletes; /** @@ -23,7 +25,7 @@ */ #[ObservedBy(BlockedPeriodObserver::class)] #[Hidden(['ical_properties', 'ical_raw', 'ical_interpretation'])] -#[Fillable(['property_id', 'channel_id', 'origin_channel_id', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid', 'needs_review', 'review_note', 'missing_imports', 'is_representation', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'reviewed_at'])] +#[Fillable(['property_id', 'channel_id', 'origin_channel_id', 'guest_id', 'occupation_kind', 'starts_on', 'ends_on', 'reason', 'source', 'external_uid', 'needs_review', 'review_note', 'missing_imports', 'is_representation', 'canonical_block_id', 'linked_booking_id', 'export_approved', 'reviewed_at'])] class BlockedPeriod extends Model { /** @use HasFactory */ @@ -39,6 +41,7 @@ class BlockedPeriod extends Model protected function casts(): array { return [ + 'occupation_kind' => OccupationKind::class, 'starts_on' => 'immutable_date', 'ends_on' => 'immutable_date', 'needs_review' => 'boolean', @@ -87,6 +90,73 @@ public function linkedBooking(): BelongsTo return $this->belongsTo(Booking::class, 'linked_booking_id'); } + /** @return BelongsTo */ + public function guest(): BelongsTo + { + return $this->belongsTo(Guest::class); + } + + public function occupationKind(): OccupationKind + { + if ($this->source === 'manual') { + return OccupationKind::Block; + } + + return $this->occupation_kind ?? ($this->ical_event_type === 'portal_reservation' ? OccupationKind::Reservation : OccupationKind::Unknown); + } + + public function guestName(): ?string + { + if ($this->is_representation) { + return $this->linkedBooking?->guest?->full_name ?? $this->canonicalBlock?->guestName(); + } + + return $this->guest?->full_name ?? ($this->ical_interpretation['fields']['guest_full_name'] ?? $this->ical_interpretation['fields']['guest_first_name'] ?? null); + } + + public function assignedGuest(): ?Guest + { + return $this->is_representation ? ($this->linkedBooking?->guest ?? $this->canonicalBlock?->assignedGuest()) : $this->guest; + } + + /** @return HasMany */ + public function channelRepresentations(): HasMany + { + return $this->hasMany(self::class, 'canonical_block_id'); + } + + /** @param Builder $query + * @return Builder + */ + #[Scope] + protected function reservations(Builder $query): Builder + { + return $query->whereIn('source', ['channel', 'email'])->where(fn (Builder $query) => $query + ->where('occupation_kind', OccupationKind::Reservation) + ->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where('ical_event_type', 'portal_reservation'))); + } + + /** @param Builder $query + * @return Builder + */ + #[Scope] + protected function explicitBlocks(Builder $query): Builder + { + return $query->where(fn (Builder $query) => $query->where('source', 'manual')->orWhere('occupation_kind', OccupationKind::Block)); + } + + /** @param Builder $query + * @return Builder + */ + #[Scope] + protected function unclear(Builder $query): Builder + { + return $query->whereIn('source', ['channel', 'email'])->where(fn (Builder $query) => $query + ->where('needs_review', true) + ->orWhere('occupation_kind', OccupationKind::Unknown) + ->orWhere(fn (Builder $query) => $query->whereNull('occupation_kind')->where(fn (Builder $query) => $query->whereNull('ical_event_type')->orWhere('ical_event_type', '!=', 'portal_reservation')))); + } + /** @param Builder $query * @return Builder */ diff --git a/app/Models/Booking.php b/app/Models/Booking.php index 80c3dec..7655dcd 100644 --- a/app/Models/Booking.php +++ b/app/Models/Booking.php @@ -157,6 +157,36 @@ public function guest(): BelongsTo return $this->belongsTo(Guest::class); } + /** @return BelongsTo */ + public function originChannel(): BelongsTo + { + return $this->belongsTo(Channel::class, 'origin_channel_id'); + } + + /** @return BelongsTo */ + public function importChannel(): BelongsTo + { + return $this->belongsTo(Channel::class, 'import_channel_id'); + } + + /** @return HasMany */ + public function channelRepresentations(): HasMany + { + return $this->hasMany(BlockedPeriod::class, 'linked_booking_id'); + } + + public function bookingChannelLabel(): string + { + return $this->originChannel?->name ?? $this->importChannel?->name ?? match ($this->source) { + 'website' => 'Eigene Webseite', + 'manual' => 'Manuell / direkt', + 'phone' => 'Telefon', + 'email' => 'E-Mail', + 'direct' => 'Direkt', + default => $this->source, + }; + } + /** * Bookings that currently occupy their dates: confirmed ones and requests/offers whose hold has not expired. * diff --git a/app/Models/Guest.php b/app/Models/Guest.php index d386385..3cd7859 100644 --- a/app/Models/Guest.php +++ b/app/Models/Guest.php @@ -42,12 +42,18 @@ public function bookings(): HasMany return $this->hasMany(Booking::class)->latest('arrival'); } + /** @return HasMany */ + public function portalStays(): HasMany + { + return $this->hasMany(BlockedPeriod::class)->reservations()->occupying()->latest('starts_on'); + } + /** * @return Attribute */ protected function fullName(): Attribute { - return Attribute::get(fn (): string => "{$this->first_name} {$this->last_name}"); + return Attribute::get(fn (): string => trim("{$this->first_name} {$this->last_name}")); } /** diff --git a/database/migrations/2026_10_27_212523_add_guest_assignment_for_portal_occupations.php b/database/migrations/2026_10_27_212523_add_guest_assignment_for_portal_occupations.php new file mode 100644 index 0000000..bae50ab --- /dev/null +++ b/database/migrations/2026_10_27_212523_add_guest_assignment_for_portal_occupations.php @@ -0,0 +1,40 @@ +foreignId('guest_id')->nullable()->constrained()->nullOnDelete(); + $table->string('occupation_kind', 30)->nullable(); + }); + Schema::table('guests', function (Blueprint $table) { + $table->string('email')->nullable()->change(); + }); + } + + /** + * Reverse the migrations. + */ + public function down(): void + { + if (DB::table('guests')->whereNull('email')->exists()) { + throw new RuntimeException('Gäste ohne E-Mail zuerst vervollständigen; das vorherige Schema erlaubt keine fehlenden E-Mail-Adressen.'); + } + Schema::table('guests', function (Blueprint $table) { + $table->string('email')->nullable(false)->change(); + }); + Schema::table('blocked_periods', function (Blueprint $table) { + $table->dropConstrainedForeignId('guest_id'); + $table->dropColumn('occupation_kind'); + }); + } +}; diff --git a/docs/STATUS.md b/docs/STATUS.md index b04c28b..2dc1760 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -4,6 +4,8 @@ # Projektstand > Dieses Dokument ist der Einstieg für jede neue Arbeitssitzung. Bitte bei größeren Änderungen fortschreiben (Abschnitte „Fertig“, „Offen“, „Nächste Schritte“). +**Zentrale Belegungsverwaltung lokal umgesetzt (27.10.2026):** Belegungsplan je Wohnung mit Monats-/Mobilansicht, freien Nächten, Wechseln, Kanal, Gast und Status; gemeinsame Liste eigener Anfragen/Buchungen und erkannter Portalreservierungen; plattformübergreifende Gästezuordnung und gemeinsame Aufenthaltshistorie. Sperrzeiten auf ausdrückliche Sperren begrenzt, eigener Klärungsbereich mit Originaldaten und persönlicher Einordnung. **Entscheidung Lars: Gastzuordnung bei Portalreservierungen zunächst offen lassen**, keine automatische Anlage anhand eines Namensfragments. Fehlende Kontaktdaten sind erlaubt, Mailabläufe entsprechend abgesichert; Portalaufenthalte werden bei Anonymisierung und Stammgast-Auswahl berücksichtigt. Importidentitäten, Datumslogik und Herkunftsschutz weiterverwendet, keine automatische Datumszusammenführung oder erfundene Preis-/Vertragsdaten. Additive Zuordnungsfelder und nullable Gast-E-Mail in Migration `2026_10_27_212523_add_guest_assignment_for_portal_occupations`; noch nicht ausgeliefert. [Fachliche Bedienung und Grenzen](architecture/ical-kanalkonfiguration.md#zentrale-belegungsverwaltung). **433 Feature-Tests / 2062 Assertions lokal erfolgreich, darunter 24 neue Prüffälle; Pint und Vite-Build erfolgreich.** Bestehende Herkunfts-/Synchronisations- und Buchungsworkflow-Tests grün. Bereitstellungsnachweis folgt nach der vorhandenen Pipeline. + **n8n-Oberfläche wieder zugänglich (27.10.2026):** n8n läuft durchgehend; Port 5678 bietet intern HTTP, keinen direkten HTTPS-Zugang. Die zuvor aus der Konfiguration übernommene öffentliche HTTPS-Adresse war als Zugangslink nicht funktionsfähig. Temporären SSH-Tunnel ausschließlich an `127.0.0.1:15678` eingerichtet; http://localhost:15678 und Workflowroute mit HTTP 200 geprüft. **Lars bestätigt die erfolgreiche Anmeldung.** Serverkonfiguration, Zertifikate, n8n-Konten und Secure-Cookie-Einstellung unverändert. Der Tunnel gilt nur auf diesem Arbeitsplatz und solange er läuft; dauerhafter öffentlicher HTTPS-Zugang bleibt ungeklärt. Lokale Workflowlinks unten setzen diesen Tunnel voraus. Wiederherstellung und Diagnose: [BETRIEB.md](BETRIEB.md#zugang-zur-n8n-oberfläche-27102026). **Externer Scheduler aktiv (27.10.2026):** Lars hat den [n8n-Workflow „FewoPortal Scheduler (stommer.info)“](http://localhost:15678/workflow/23581e4b70324812) veröffentlicht. Veröffentlichte Version und aktiver Zeitplan lesend bestätigt. n8n auf dem Pi ruft den Scheduler auf stommer.info minütlich auf; Kalenderimporte sind alle fünf Minuten fällig. **Zwei aufeinanderfolgende automatische Importe am 27.10. um 20:55:03 und 21:00:03 Uhr MEZ nachgewiesen**, exakt 300 Sekunden Abstand; jeweils 11 Ereignisse, erfolgreich, keine neuen, geänderten oder entfernten Belegungen und keine Konflikte. Prüfung ausschließlich lesend, kein zusätzlicher manueller Abgleich. Letzter Erfolg am Kanal und Fehlerfreiheit bestätigt. Verschlüsselte Header-Auth-Zugangsdaten eingerichtet, tokenfreie [Workflowvorlage](../scripts/n8n-fewo-scheduler.json) im Repository. Der erfolgreiche einmalige Verbindungstest von 20:42:47 Uhr bleibt vom Nachweis automatischer Importe getrennt. Browser und lokaler SSH-Tunnel sind für den automatischen Betrieb nicht erforderlich; Pi und n8n müssen laufen und stommer.info erreichen können. Details in [BETRIEB.md §6](BETRIEB.md#6-erledigt--offen-im-testbetrieb); tokenfreier lokaler Nachweis Git-ignoriert unter `storage/app/private/n8n-scheduler/setup-result.json`. diff --git a/docs/architecture/ical-kanalkonfiguration.md b/docs/architecture/ical-kanalkonfiguration.md index e954ce8..e9ba22c 100644 --- a/docs/architecture/ical-kanalkonfiguration.md +++ b/docs/architecture/ical-kanalkonfiguration.md @@ -149,6 +149,30 @@ ## 8. Konsolidierte Portal-Aufgaben ## 9. Überwachung und Abrufzeiten +### Zentrale Belegungsverwaltung + +Die Verwaltungsansichten werden mit dem Folgeauftrag vom 27.10.2026 fachlich zusammengeführt: + +| Bereich | Inhalt und Zweck | +|---|---| +| **Belegungsplan** (`/admin/belegungsplan`) | Monatsplan je Wohnung mit freien und belegten Nächten, An-/Abreisen, Gast beziehungsweise Namensinformation, Buchungskanal, Status und Prüfhinweisen. Auf kleinen Bildschirmen werden die Tage untereinander dargestellt. Darunter stehen alle Vorgänge des Zeitraums mit Links zu den Details. | +| **Anfragen & Buchungen** (`/admin/bookings`) | Gemeinsame, durchsuchbare Liste eigener Vorgänge und erkannter Portalreservierungen. Filter nach Wohnung, Buchungsweg, Status, kommenden Aufenthalten und offener Gastzuordnung. Vorhandene Buchungsabläufe bleiben erreichbar. | +| **Gäste** (`/admin/guests`) | Gemeinsame Kartei für alle Plattformen. Zugeordnete Portalreservierungen erscheinen zusammen mit eigenen Buchungen in der Aufenthaltshistorie. Die Stammgast-Auswahl berücksichtigt beide Quellen; Umsätze beziehen sich weiterhin auf bekannte Preise eigener Buchungen. | +| **Sperrzeiten** (`/admin/blocked-periods`) | Eigene ausdrückliche Sperren und persönlich als Sperrzeit bestätigte importierte Zeiträume. Allgemeine, nicht näher bekannte iCal-Sperren werden nicht automatisch als eigene Sperrzeiten ausgegeben. | +| **Ungeklärte Belegungen** (`/admin/portal-occupations`) | Unbekannte Importzeiten und Prüffälle. Zusätzliche Register erlauben die Sicht auf alle Importereignisse sowie auf Einträge, die nicht mehr im Feed stehen. Details zeigen Herkunft, Originalereignis, führende Zuordnung und bekannte Gastinformationen. | + +**Gastzuordnung bleibt bei Portalreservierungen zunächst offen**, entsprechend der Entscheidung von Lars. Ein Namensfragment erzeugt keinen Gast automatisch und führt keine Gäste automatisch zusammen. Über **Details → Gast zuordnen** wird ein vorhandener Gast persönlich gewählt oder ein neuer mit den bekannten Angaben angelegt. Nachname und E-Mail dürfen dabei fehlen; es werden keine Ersatzdaten erfunden. Die Zuordnung ist auch an eigenen Buchungen möglich. Sie sendet keine Nachricht, ersetzt keine Vertragsdatei und ändert keine Termine. Ein späterer Kalenderimport erhält die Gastzuordnung anhand derselben Ereignisidentität. Auch archivierte und wiederkehrende Ereignisse behalten diese Zuordnung. + +**Belegungsart festlegen** bestätigt eine Portalreservierung, eine ausdrückliche Sperrzeit oder einen weiterhin unbekannten Sachverhalt. Diese persönliche Einordnung bleibt gegenüber späteren iCal-Regelauswertungen erhalten. Sie schließt Überschneidungen und mögliche Mehrfachdarstellungen nicht automatisch ab; dafür bleibt **Belegung zuordnen / klären** zuständig. Die führende Buchung oder Belegung erscheint einmal im Plan und in der gemeinsamen Liste. Zugeordnete Kalenderdarstellungen bleiben in den Quelldetails nachvollziehbar. + +Ein erkannter Portalaufenthalt aus iCal besitzt dadurch keine erfundenen Preise, Personenzahlen, Zahlungsstände oder Vertragsbestätigungen. Fehlende Angaben werden als unbekannt angezeigt. Ein verschwundenes Feedereignis heißt **„Nicht mehr im Kalenderfeed“**; daraus wird kein gesicherter Stornogrund abgeleitet. Ohne belegenden führenden Datensatz zählt ein zugeordneter Kalendereintrag nicht als zweite Belegung. + +Die zusätzliche Gastverknüpfung und persönliche Belegungsart erweitern die vorhandenen Importdaten. Bestehende IDs, UIDs, Zeiträume, Zuordnungen und Herkunftsausschlüsse werden nicht durch Löschen und Neuimport ersetzt. Unbekannte führende Importzeiten halten ihre Nächte weiterhin belegt. E-Mail-Aktionen verlangen eine vorhandene Gastadresse; Erinnerungs- und Bewertungsmails überspringen Datensätze ohne E-Mail. Die Anonymisierung berücksichtigt zugeordnete Portalaufenthalte, damit ein Gast mit aktuellem Portalaufenthalt nicht fälschlich als veralteter bloßer Interessent behandelt wird. Eine Weitergabe zugeordneter Gastnamen bleibt an die ausdrückliche Freigabe des jeweiligen Zielkanals gebunden. + +Technischer Einstieg: `OccupancyOverview`, `OccupancyCalendar`, `PortalOccupationResource`, `AssignOccupationGuest`, `ClassifyPortalOccupation` und `OccupationKind`; Tests in `OccupancyManagementTest`. Die Migration ergänzt `blocked_periods.guest_id` und die optionale persönliche Belegungsart und erlaubt fehlende Gast-E-Mail-Adressen. Ein Schema-Rollback verlangt vorab die Vervollständigung solcher E-Mail-Adressen; keine Ersatzadressen werden für einen Rollback erzeugt. Den aktuellen Bereitstellungs- und Nachweisstand hält [STATUS.md](../STATUS.md) fest. + +### Synchronisationsstatus + Die Kanalliste zeigt Importzustand, letzten erfolgreichen Import, letzte Fehlerzeit, Anzahl zuletzt übernommener Ereignisse, Warnungen, Prüffallzahl, Exportmodus und Exportzustand. Die letzten 30 Protokolle sind einsehbar. Ein manueller Lauf bleibt für eingeschaltete eingerichtete Importe verfügbar. Unser Aufgabenplan sieht `channels:sync` alle fünf Minuten vor. Der erwartete externe Abrufabstand ist dagegen nur eine Vermutung zum Portal und steuert diesen Plan nicht. Ohne eingerichteten Scheduler erfolgt kein regelmäßiger Abgleich. Stand 27.10.2026: Strato erlaubt laut Nutzer minimal stündliche Cron-Ausführung. Der minütliche externe n8n-Auslöser mit verschlüsselten Zugangsdaten ist durch Lars veröffentlicht und aktiv. Zwei aufeinanderfolgende automatische Importe am 27.10. um 20:55:03 und 21:00:03 Uhr MEZ, jeweils 11 Ereignisse ohne Änderungen oder Konflikte, sind im Sync-Protokoll nachgewiesen. Kein manueller Abgleich während dieser Beobachtung. Der automatische Betrieb erfolgt auf dem Pi und benötigt weder Browser noch lokalen SSH-Tunnel; die externe Infrastruktur muss verfügbar sein. Einrichtung und Betriebsnachweis: [BETRIEB.md §6](../BETRIEB.md#6-erledigt--offen-im-testbetrieb). diff --git a/docs/architecture/ical-regelengine.md b/docs/architecture/ical-regelengine.md index 3eb472a..8dfc123 100644 --- a/docs/architecture/ical-regelengine.md +++ b/docs/architecture/ical-regelengine.md @@ -37,9 +37,9 @@ ## Führende Repräsentation und Zuordnung Eine erkannte Portalreservierung kann als führender Kandidat mit Vorrang gegenüber einer allgemeinen Sperre gekennzeichnet werden. Bei identischen Terminen zeigt die Vorschau mögliche Zusammenhänge mit vorhandenen Sperren und die Begründung **„exakt derselbe Zeitraum“**. -Dieser Hinweis ist kein Identitätsnachweis. Eine Regel erzeugt keine automatische Zusammenführung und hebt keine zusätzliche Sperre ungeprüft auf. Unter **Sperrzeiten → Belegung zuordnen / klären** wird die Identität persönlich bestätigt. Führende Kandidaten stehen dort bei den gleich terminierten Zielen zuerst. Bestätigte Verknüpfungen und persönlich bekannte Herkunft werden durch die Regelauswertung erhalten. +Dieser Hinweis ist kein Identitätsnachweis. Eine Regel erzeugt keine automatische Zusammenführung und hebt keine zusätzliche Sperre ungeprüft auf. Unter **Ungeklärte Belegungen → Details → Belegung zuordnen / klären** wird die Identität persönlich bestätigt. Führende Kandidaten stehen dort bei den gleich terminierten Zielen zuerst. Bestätigte Verknüpfungen und persönlich bekannte Herkunft werden durch die Regelauswertung erhalten. -Die Sperrzeitenübersicht zeigt den erkannten Ereignistyp und verfügbare Namensinformationen. **iCal-Original & Erkennung** öffnet das Original und die treffende Regel. +Erkannte Portalreservierungen stehen zusammen mit eigenen Vorgängen unter **Anfragen & Buchungen**. Unbekannte Zeiten und Prüffälle stehen unter **Ungeklärte Belegungen**; **Sperrzeiten** enthält ausdrückliche Sperren. Die Portal-Detailansicht zeigt Einordnung und Namensinformationen. **iCal-Original & Erkennung** öffnet das Original und die treffende Regel. Gastzuordnungen bleiben bis zur persönlichen Auswahl beziehungsweise Anlage eines Gastes offen. Persönlich bestätigte Belegungsarten werden durch neue Regelinterpretationen nicht überschrieben; Identitätsprüffälle bleiben davon getrennt. Der [zentrale Belegungsplan und die gemeinsame Gästekartei](ical-kanalkonfiguration.md#zentrale-belegungsverwaltung) ergänzen die Kalenderverwaltung. ## Exportinformationen je Zielkanal diff --git a/resources/views/filament/pages/occupancy-calendar.blade.php b/resources/views/filament/pages/occupancy-calendar.blade.php new file mode 100644 index 0000000..fd7b7ff --- /dev/null +++ b/resources/views/filament/pages/occupancy-calendar.blade.php @@ -0,0 +1,105 @@ + + + @php($calendar = $this->calendar) +
+
+ + + ← Zurück + Weiter → + Alle Anfragen & Buchungen + Ungeklärte Belegungen +
+ @if ($calendar) +

{{ $calendar['month']->locale('de')->translatedFormat('F Y') }}

+

+ {{ $calendar['free'] }} freie Nächte · {{ $calendar['occupied'] }} belegte Nächte. + Eine Belegung umfasst die Nächte ab Anreise bis vor Abreise. Ein Wechsel am selben Tag ist möglich. + Ungeklärte führende Belegungen sperren ebenfalls. Namensinformationen aus iCal ersetzen keine bestätigte Gastzuordnung. +

+
+ @foreach (['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'] as $weekday) +
{{ $weekday }}
+ @endforeach + @for ($offset = 1; $offset < $calendar['month']->isoWeekday(); $offset++) + + @endfor + @foreach ($calendar['days'] as $day) +
+

{{ $day['date']->locale('de')->translatedFormat('D, d.m.') }}

+ @if ($day['free'])Frei@endif + @if ($day['overlap'])

Mehrere führende Einträge – prüfen

@endif + @foreach ($day['occupations'] as $event) + + {{ $event['kind'] === 'booking' || $event['kind'] === 'reservation' ? $event['guest'] : $event['kind_label'] }} + {{ $event['source'] }} · {{ $event['status'] }} + @if (!$event['guest_assigned'] && $event['kind'] === 'reservation')Gastzuordnung offen@endif + @if ($event['needs_review'])Klärung erforderlich@endif + + @endforeach + @foreach ($day['departures'] as $event) +

Abreise / Ende: {{ $event['guest_assigned'] ? $event['guest'] : $event['source'] }}

+ @endforeach +
+ @endforeach +
+
+

Alle Vorgänge dieses Zeitraums

+ + + + @forelse ($calendar['rows'] as $event) + + + + + + + + @empty + + @endforelse + +
ZeitraumArt / StatusGastKanal / QuelleHinweise
{{ \Carbon\CarbonImmutable::parse($event['arrival'])->format('d.m.Y') }}–{{ \Carbon\CarbonImmutable::parse($event['departure'])->format('d.m.Y') }}{{ $event['kind_label'] }}
{{ $event['status'] }}
+ {{ $event['guest'] }} + @if (!$event['guest_assigned'] && $event['kind'] === 'reservation') +
Zuordnung offen + @endif +
{{ $event['source'] }}{{ $event['review_note'] }}@if ($event['representations'])
{{ $event['representations'] }} zugeordnete Kalenderdarstellung(en)@endif
Keine Vorgänge in diesem Zeitraum.
+
+ @else +

Es ist noch keine Wohnung angelegt.

+ @endif +
+
diff --git a/tests/Feature/ChannelOccupationResolutionTest.php b/tests/Feature/ChannelOccupationResolutionTest.php index 39a000f..5b4c792 100644 --- a/tests/Feature/ChannelOccupationResolutionTest.php +++ b/tests/Feature/ChannelOccupationResolutionTest.php @@ -9,7 +9,7 @@ use App\Enums\BookingStatus; use App\Enums\ChannelEchoBehavior; use App\Enums\UserRole; -use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods; +use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations; use App\Filament\Resources\Properties\Pages\EditProperty; use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager; use App\Models\BlockedPeriod; @@ -218,7 +218,7 @@ public function test_landlord_can_resolve_a_duplicate_through_the_existing_admin $copy = $this->block($property, $channel, 'copy'); $this->actingAs(User::factory()->create()); - Livewire::test(ManageBlockedPeriods::class)->callTableAction('resolve', $copy, ['resolution' => 'block', 'target_id' => $primary->id])->assertHasNoActionErrors(); + Livewire::test(ManagePortalOccupations::class)->callTableAction('resolve', $copy, ['resolution' => 'block', 'target_id' => $primary->id])->assertHasNoActionErrors(); $this->assertSame($primary->id, $copy->fresh()->canonical_block_id); $this->assertTrue($copy->fresh()->is_representation); @@ -229,7 +229,7 @@ public function test_content_role_cannot_open_the_occupation_resolution_screen() $this->property(); $this->actingAs(User::factory()->role(UserRole::Content)->create()); - Livewire::test(ManageBlockedPeriods::class)->assertForbidden(); + Livewire::test(ManagePortalOccupations::class)->assertForbidden(); } public function test_any_portal_created_in_the_ui_automatically_gets_its_own_stable_export_link(): void diff --git a/tests/Feature/GenericChannelIntegrationTest.php b/tests/Feature/GenericChannelIntegrationTest.php index f422c5c..a73c830 100644 --- a/tests/Feature/GenericChannelIntegrationTest.php +++ b/tests/Feature/GenericChannelIntegrationTest.php @@ -14,7 +14,7 @@ use App\Enums\ChannelExportMode; use App\Enums\ChannelStatus; use App\Enums\ChannelTaskAction; -use App\Filament\Resources\BlockedPeriods\Pages\ManageBlockedPeriods; +use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations; use App\Filament\Resources\Properties\Pages\EditProperty; use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager; use App\Models\BlockedPeriod; @@ -559,7 +559,7 @@ public function test_admin_can_view_import_provenance_and_unresolved_block_revie $block = BlockedPeriod::factory()->for($property)->create(['channel_id' => $channel->id, 'origin_channel_id' => $channel->id, 'source' => 'channel', 'external_uid' => 'synthetic-uid', 'needs_review' => true, 'review_note' => 'Bestand persönlich prüfen', 'starts_on' => '2026-11-07', 'ends_on' => '2026-11-10']); $this->actingAs(User::factory()->create()); - Livewire::test(ManageBlockedPeriods::class) + Livewire::test(ManagePortalOccupations::class) ->assertCanSeeTableRecords([$block]) ->assertSee('Synthetisches Portal') ->assertSee('Bitte prüfen') diff --git a/tests/Feature/OccupancyManagementTest.php b/tests/Feature/OccupancyManagementTest.php new file mode 100644 index 0000000..764e7c9 --- /dev/null +++ b/tests/Feature/OccupancyManagementTest.php @@ -0,0 +1,395 @@ +travelTo(CarbonImmutable::parse('2026-10-27 12:00')); + } + + public function test_bookings_list_combines_own_requests_and_portal_reservations_without_creating_guests(): void + { + $property = $this->property(); + $own = Booking::factory()->for($property)->reserved()->create(['arrival' => '2026-11-02', 'departure' => '2026-11-05']); + $portal = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $unknown = $this->import($property, ['ical_event_type' => 'block']); + $guestCount = Guest::count(); + + Livewire::test(ListBookings::class) + ->assertCanSeeTableRecords([$own, 'portal-'.$portal->id]) + ->assertCanNotSeeTableRecords(['portal-'.$unknown->id]) + ->assertSee('Portalreservierung')->assertSee('Gastzuordnung offen'); + + $this->assertSame($guestCount, Guest::count()); + $this->assertNull($portal->fresh()->guest_id); + } + + public function test_calendar_uses_nights_all_occupation_types_and_ignores_expired_holds_and_representations(): void + { + $property = $this->property(); + $booking = Booking::factory()->for($property)->create(['arrival' => '2026-11-02', 'departure' => '2026-11-05']); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'starts_on' => '2026-11-05', 'ends_on' => '2026-11-07']); + BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-07', 'ends_on' => '2026-11-08']); + $this->import($property, ['starts_on' => '2026-11-10', 'ends_on' => '2026-11-11']); + $this->import($property, ['starts_on' => '2026-11-02', 'ends_on' => '2026-11-05', 'is_representation' => true, 'linked_booking_id' => $booking->id]); + Booking::factory()->for($property)->reserved(now()->subMinute())->create(['arrival' => '2026-11-08', 'departure' => '2026-11-09']); + Booking::factory()->for($property)->create(['status' => BookingStatus::Cancelled, 'arrival' => '2026-11-09', 'departure' => '2026-11-10']); + + $calendar = app(OccupancyOverview::class)->calendar($property, CarbonImmutable::parse('2026-11-01')); + + $this->assertSame([23, 7], [$calendar['free'], $calendar['occupied']]); + $this->assertCount(1, $calendar['days'][4]['occupations']); + $this->assertCount(1, $calendar['days'][4]['departures']); + $this->assertFalse($calendar['days'][4]['overlap']); + $this->assertTrue($calendar['days'][7]['free']); + $this->assertTrue($calendar['days'][8]['free']); + $this->assertFalse($calendar['days'][9]['free']); + $this->assertFalse(app(AvailabilityChecker::class)->isAvailable($property, CarbonImmutable::parse('2026-11-10'), CarbonImmutable::parse('2026-11-11'))); + Livewire::test(OccupancyCalendar::class, ['month' => '2026-11', 'propertyId' => $property->id])->assertSee('23 freie Nächte')->assertSee('Ungeklärte Belegung'); + } + + public function test_only_explicit_blocks_remain_in_blocked_periods_and_unknown_imports_have_a_separate_queue(): void + { + $property = $this->property(); + $manual = BlockedPeriod::factory()->for($property)->create(['starts_on' => '2026-11-01', 'ends_on' => '2026-11-02']); + $unknown = $this->import($property, ['ical_event_type' => 'block']); + $reservation = $this->import($property, ['ical_event_type' => 'portal_reservation']); + + Livewire::test(ManageBlockedPeriods::class)->assertCanSeeTableRecords([$manual])->assertCanNotSeeTableRecords([$unknown, $reservation]); + Livewire::test(ManagePortalOccupations::class)->assertCanSeeTableRecords([$unknown])->assertCanNotSeeTableRecords([$manual, $reservation]); + $this->assertSame('1', PortalOccupationResource::getNavigationBadge()); + } + + public function test_manual_classification_preserves_calendar_identity_and_survives_rule_updates(): void + { + $property = $this->property(); + $block = $this->import($property, ['needs_review' => true, 'export_approved' => false]); + $before = $block->only(['id', 'external_uid', 'starts_on', 'ends_on', 'is_representation', 'export_approved']); + + Livewire::test(ViewPortalOccupation::class, ['record' => $block->id])->callAction('classify', ['occupation_kind' => 'block', 'origin_channel_id' => null])->assertHasNoActionErrors(); + app(ApplyChannelRules::class)->store($block->fresh(), ['ical_event_type' => 'portal_reservation']); + + $this->assertSame(OccupationKind::Block, $block->fresh()->occupationKind()); + $this->assertEquals($before, $block->fresh()->only(array_keys($before))); + $this->assertTrue($block->fresh()->needs_review); + Livewire::test(ManageBlockedPeriods::class)->assertCanSeeTableRecords([$block]); + } + + public function test_a_guest_with_only_known_information_can_be_created_and_assigned_from_portal_details(): void + { + $property = $this->property(); + $block = $this->import($property, ['ical_event_type' => 'portal_reservation']); + Mail::fake(); + $uid = $block->external_uid; + + Livewire::test(ViewPortalOccupation::class, ['record' => $block->id]) + ->callAction('assignGuest', ['mode' => 'new', 'first_name' => 'Maren', 'last_name' => null, 'email' => null, 'phone' => null]) + ->assertHasNoActionErrors()->assertNotified('Gast zugeordnet'); + + $guest = Guest::sole(); + $this->assertSame(['Maren', '', null, $guest->id, $uid], [$guest->first_name, $guest->last_name, $guest->email, $block->fresh()->guest_id, $block->fresh()->external_uid]); + $this->get(GuestResource::getUrl('edit', ['record' => $guest]))->assertOk()->assertSee('Maren'); + Mail::assertNothingSent(); + } + + public function test_guest_history_combines_direct_and_assigned_portal_stays_in_one_table(): void + { + $property = $this->property(); + $own = Booking::factory()->for($property)->create(); + $portal = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $unassigned = $this->import($property, ['ical_event_type' => 'portal_reservation']); + app(AssignOccupationGuest::class)->handle($portal, $own->guest_id); + + Livewire::test(BookingsRelationManager::class, ['ownerRecord' => $own->guest, 'pageClass' => EditGuest::class]) + ->assertCanSeeTableRecords([$own, 'portal-'.$portal->id])->assertCanNotSeeTableRecords(['portal-'.$unassigned->id]); + $this->assertSame(1, $own->guest->portalStays()->count()); + } + + public function test_guest_can_be_entered_directly_without_fabricating_unknown_contact_details(): void + { + $this->property(); + + Livewire::test(CreateGuest::class)->fillForm(['first_name' => 'Tanja', 'country' => 'DE'])->call('create')->assertHasNoFormErrors(); + + $this->assertSame(['Tanja', '', null], [Guest::sole()->first_name, Guest::sole()->last_name, Guest::sole()->email]); + } + + public function test_guest_assignment_survives_import_changes_archiving_and_return_with_same_uid(): void + { + $property = $this->property(); + $block = $this->import($property, ['ical_event_type' => 'portal_reservation', 'external_uid' => 'stay-17', 'occupation_kind' => OccupationKind::Reservation]); + $guest = Guest::factory()->create(['tenant_id' => $property->tenant_id]); + app(AssignOccupationGuest::class)->handle($block, $guest->id); + Http::preventStrayRequests(); + Http::fake(['https://portal.example/calendar.ics' => Http::sequence()->push($this->feed('stay-17', '20261120', '20261125'))->push($this->feed())->push($this->feed())->push($this->feed('stay-17', '20261121', '20261126'))]); + Mail::fake(); + + $first = app(SyncChannel::class)->handle($block->channel); + $this->assertTrue($first->successful, $first->message ?? 'First import failed'); + $second = app(SyncChannel::class)->handle($block->channel); + $this->assertTrue($second->successful, $second->message ?? 'First missing snapshot failed'); + $third = app(SyncChannel::class)->handle($block->channel); + $this->assertTrue($third->successful, $third->message ?? 'Second missing snapshot failed'); + $this->assertTrue($block->fresh()->trashed()); + $history = app(OccupancyOverview::class)->records(guestId: $guest->id); + $this->assertSame('Nicht mehr im Kalenderfeed', $history['portal-'.$block->id]['status']); + app(SyncChannel::class)->handle($block->channel); + + $restored = BlockedPeriod::withTrashed()->findOrFail($block->id); + $this->assertSame([$guest->id, 'stay-17', '2026-11-21', false], [$restored->guest_id, $restored->external_uid, $restored->starts_on->toDateString(), $restored->trashed()]); + $this->assertSame(1, BlockedPeriod::withTrashed()->where('external_uid', 'stay-17')->count()); + Http::assertSentCount(4); + } + + public function test_third_party_guests_are_not_prematurely_anonymized_as_inquiries_without_local_bookings(): void + { + $property = $this->property(); + $guest = Guest::factory()->create(['tenant_id' => $property->tenant_id, 'created_at' => '2010-01-01', 'updated_at' => '2010-01-01']); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'guest_id' => $guest->id]); + + $this->assertSame(0, app(AnonymizeGuests::class)->handle()); + $this->assertNull($guest->fresh()->anonymized_at); + } + + public function test_archived_portal_stays_remain_readable_without_mutation_actions(): void + { + $property = $this->property(); + $block = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $block->delete(); + + $this->get(PortalOccupationResource::getUrl('view', ['record' => $block->id]))->assertOk()->assertSee('Nicht mehr im Feed'); + Livewire::test(ViewPortalOccupation::class, ['record' => $block->id])->assertActionHidden('assignGuest')->assertActionHidden('classify')->assertActionHidden('resolve'); + } + + public function test_returning_guest_filter_counts_portal_only_and_mixed_stays(): void + { + $property = $this->property(); + $portalGuest = Guest::factory()->create(['tenant_id' => $property->tenant_id]); + $mixed = Booking::factory()->for($property)->create(); + $single = Guest::factory()->create(['tenant_id' => $property->tenant_id]); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'guest_id' => $portalGuest->id]); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'guest_id' => $portalGuest->id]); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'guest_id' => $mixed->guest_id]); + $this->import($property, ['ical_event_type' => 'portal_reservation', 'guest_id' => $single->id]); + + Livewire::test(ListGuests::class)->filterTable('returning')->assertCanSeeTableRecords([$portalGuest, $mixed->guest])->assertCanNotSeeTableRecords([$single]); + } + + public function test_central_booking_search_and_filters_apply_to_both_sources(): void + { + $property = $this->property(); + $own = Booking::factory()->for($property)->create(); + $portal = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $portal->forceFill(['ical_interpretation' => ['fields' => ['guest_first_name' => 'Elisa']]])->saveQuietly(); + + Livewire::test(ListBookings::class)->filterTable('kind', 'portal')->assertCanSeeTableRecords(['portal-'.$portal->id])->assertCanNotSeeTableRecords([$own]); + Livewire::test(ListBookings::class)->filterTable('without_guest')->assertCanSeeTableRecords(['portal-'.$portal->id])->assertCanNotSeeTableRecords([$own]); + Livewire::test(ListBookings::class)->searchTable('Elisa')->assertCanSeeTableRecords(['portal-'.$portal->id])->assertCanNotSeeTableRecords([$own]); + } + + public function test_confirming_only_a_business_type_does_not_clear_identity_review_or_allow_rule_origin_override(): void + { + $property = $this->property(); + $block = $this->import($property, ['needs_review' => true, 'review_note' => 'Mehrere Darstellungen prüfen']); + $block->channel->forceFill(['ical_active_rules' => [[ + 'name' => 'Reservation', 'enabled' => true, 'priority' => 1, 'match' => 'all', + 'conditions' => [['field' => 'SUMMARY', 'operator' => 'equals', 'value' => 'Reserved']], + 'event_type' => 'portal_reservation', 'origin' => 'current', 'representation' => 'leading_candidate', 'extractions' => [], + ]]])->save(); + + app(ClassifyPortalOccupation::class)->handle($block, OccupationKind::Unknown); + $block->refresh(); + $attributes = app(ApplyChannelRules::class)->attributes($block->channel, $block, ['SUMMARY' => [['value' => 'Reserved', 'params' => []]]]); + + $this->assertArrayNotHasKey('origin_channel_id', $attributes); + $this->assertNull($block->reviewed_at); + $this->assertTrue($block->needs_review); + $this->assertSame(OccupationKind::Unknown, $block->occupationKind()); + } + + public function test_guest_identity_of_a_representation_is_shown_from_the_leading_booking(): void + { + $property = $this->property(); + $booking = Booking::factory()->for($property)->create(); + $copy = $this->import($property, ['is_representation' => true, 'linked_booking_id' => $booking->id]); + + $this->assertSame($booking->guest->full_name, $copy->guestName()); + Livewire::test(ViewPortalOccupation::class, ['record' => $copy->id])->assertActionHidden('assignGuest')->assertSee($booking->reference)->assertSee($booking->guest->email); + } + + public function test_invalid_calendar_month_change_is_rejected_without_changing_the_current_month(): void + { + $property = $this->property(); + + Livewire::test(OccupancyCalendar::class, ['month' => '2026-11', 'propertyId' => $property->id]) + ->call('moveMonth', 4)->assertHasErrors(['direction'])->assertSet('month', '2026-11'); + } + + public function test_confirmed_guest_names_obey_the_existing_per_target_export_permission(): void + { + $property = $this->property(); + $portal = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $guest = Guest::factory()->create(['tenant_id' => $property->tenant_id, 'first_name' => 'Ida', 'last_name' => 'Beispiel']); + app(AssignOccupationGuest::class)->handle($portal, $guest->id); + $target = Channel::factory()->for($property)->create(['name' => 'Anderes Portal']); + $target->forceFill(['ical_export_names' => true, 'ical_export_mapping' => [['field' => 'SUMMARY', 'items' => ['guest_full_name']]]])->save(); + + $this->assertStringContainsString('SUMMARY:Ida Beispiel', app(ICalFeed::class)->build($target)); + $this->assertStringNotContainsString('Ida Beispiel', app(ICalFeed::class)->build($portal->channel)); + $target->forceFill(['ical_export_names' => false])->save(); + $this->assertStringNotContainsString('Ida Beispiel', app(ICalFeed::class)->build($target)); + } + + public function test_foreign_guest_is_rejected_by_the_scoped_selection_and_does_not_change_the_portal_stay(): void + { + $property = $this->property(); + $block = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $foreign = Guest::factory()->create(['tenant_id' => Tenant::factory()->create()->id]); + + Livewire::test(ViewPortalOccupation::class, ['record' => $block->id])->callAction('assignGuest', ['mode' => 'existing', 'guest_id' => $foreign->id])->assertHasActionErrors(['guest_id']); + $this->assertNull($block->fresh()->guest_id); + } + + public function test_calendar_and_import_details_reject_foreign_properties_and_records(): void + { + $property = $this->property(); + $foreignTenant = Tenant::factory()->create(); + $foreignProperty = Property::factory()->create(['tenant_id' => $foreignTenant->id]); + $foreignBlock = BlockedPeriod::factory()->for($foreignProperty)->create(['source' => 'channel']); + + $this->get(OccupancyCalendar::getUrl(['wohnung' => $foreignProperty->id]))->assertNotFound(); + $this->get(PortalOccupationResource::getUrl('view', ['record' => $foreignBlock]))->assertNotFound(); + } + + public function test_content_role_cannot_access_central_occupancy_data(): void + { + $this->property(); + $this->actingAs(User::factory()->role(UserRole::Content)->create()); + + Livewire::test(OccupancyCalendar::class)->assertForbidden(); + Livewire::test(ManagePortalOccupations::class)->assertForbidden(); + } + + public function test_rendered_calendar_escapes_imported_names(): void + { + $property = $this->property(); + $block = $this->import($property, ['ical_event_type' => 'portal_reservation']); + $block->forceFill(['ical_interpretation' => ['fields' => ['guest_first_name' => '']]])->saveQuietly(); + + $response = $this->get(OccupancyCalendar::getUrl(['monat' => '2026-11', 'wohnung' => $property->id])); + + $response->assertOk()->assertSee('<script>alert(1)</script>', escape: false)->assertDontSee('', escape: false); + } + + public function test_guest_assignment_to_an_unclassified_block_is_rejected_without_creating_a_guest(): void + { + $property = $this->property(); + $block = $this->import($property); + try { + app(AssignOccupationGuest::class)->handle($block, null, ['first_name' => 'Maren']); + $this->fail('An unclassified occupation must first be classified.'); + } catch (ValidationException $exception) { + $this->assertStringContainsString('Zuerst als eigenständige Portalreservierung', $exception->getMessage()); + } + $this->assertSame(0, Guest::count()); + } + + #[DataProvider('mailActions')] + public function test_local_mail_workflows_require_a_real_guest_email(string $action): void + { + $property = $this->property(); + $booking = Booking::factory()->for($property)->reserved()->create(); + $booking->guest->update(['email' => null]); + Mail::fake(); + try { + app($action)->handle($booking); + $this->fail('Missing guest email must prevent mail workflows.'); + } catch (ReservationException $exception) { + $this->assertSame('Vor dem E-Mail-Versand bitte die E-Mail-Adresse des zugeordneten Gastes ergänzen.', $exception->getMessage()); + } + $this->assertSame(BookingStatus::Reserved, $booking->fresh()->status); + Mail::assertNothingSent(); + } + + public static function mailActions(): array + { + return ['offer' => [SendOffer::class], 'confirmation' => [ConfirmBooking::class], 'decline' => [DeclineBooking::class]]; + } + + private function property(): Property + { + $this->seed(PropertySeeder::class); + $property = Property::sole(); + app(TenantContext::class)->set($property->tenant); + $this->actingAs(User::factory()->create()); + + return $property; + } + + private function import(Property $property, array $attributes = []): BlockedPeriod + { + $channel = Channel::factory()->for($property)->create(['name' => 'Beispielportal', 'settings' => ['import_url' => 'https://portal.example/calendar.ics']]); + $block = BlockedPeriod::factory()->for($property)->create([ + 'source' => 'channel', 'channel_id' => $channel->id, 'external_uid' => 'entry-'.$channel->id, + 'starts_on' => '2026-11-12', 'ends_on' => '2026-11-15', ...$attributes, + ]); + + return $block; + } + + private function feed(?string $uid = null, string $start = '20261112', string $end = '20261115'): string + { + $event = $uid === null ? '' : "BEGIN:VEVENT\r\nUID:{$uid}\r\nDTSTAMP:20261027T110000Z\r\nDTSTART;VALUE=DATE:{$start}\r\nDTEND;VALUE=DATE:{$end}\r\nSUMMARY:Reserved\r\nEND:VEVENT\r\n"; + + return "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Synthetic Occupancy Test//DE\r\n{$event}END:VCALENDAR\r\n"; + } +}