Zentralen Belegungsplan und plattformuebergreifende Buchungs- und Gaesteverwaltung integrieren
Deploy FeWo mit PipelineManager / deploy (push) Successful in 2m41s

This commit is contained in:
Lars committed 2026-10-27 21:51:56 +01:00
1 parent c74199e978
commit f369018a68
41 files changed
+1343 -157

No files matched your search

+2
View File
@@ -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();
+1 -1
View File
@@ -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'];
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Actions;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
class AssignOccupationGuest
{
/** @param array{first_name?: string, last_name?: ?string, email?: ?string, phone?: ?string} $details */
public function handle(Booking|BlockedPeriod $occupation, ?int $guestId, array $details = []): Guest
{
Gate::authorize('update', $occupation);
return DB::transaction(function () use ($occupation, $guestId, $details): Guest {
$record = $occupation->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;
});
}
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Actions;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\ValidationException;
class ClassifyPortalOccupation
{
public function handle(BlockedPeriod $occupation, OccupationKind $kind, ?int $originId = null): void
{
Gate::authorize('update', $occupation);
DB::transaction(function () use ($occupation, $kind, $originId): void {
$record = BlockedPeriod::query()->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();
});
}
}
+4
View File
@@ -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');
}
+4
View File
@@ -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');
}
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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();
}
+4
View File
@@ -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');
}
+102
View File
@@ -0,0 +1,102 @@
<?php
namespace App\Availability;
use App\Enums\BookingStatus;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\Guests\GuestResource;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Property;
use Carbon\CarbonImmutable;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Gate;
class OccupancyOverview
{
/**
* One read model over local booking workflows and their external calendar counterparts.
* Source records retain their identities; linked representations never become a second stay.
*
* @return Collection<int|string, array<string, mixed>>
*/
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];
}
}
+4
View File
@@ -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];
}
+1 -1
View File
@@ -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));
}
+4
View File
@@ -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<class-string>
*/
public const SIMPLE_NAVIGATION = [
OccupancyCalendar::class,
BookingResource::class,
PortalOccupationResource::class,
BlockedPeriodResource::class,
PricesAndOffers::class,
GuestResource::class,
+31
View File
@@ -0,0 +1,31 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
enum OccupationKind: string implements HasColor, HasLabel
{
case Reservation = 'reservation';
case Block = 'block';
case Unknown = 'unknown';
public function getLabel(): string
{
return match ($this) {
self::Reservation => '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',
};
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Filament\Actions;
use App\Actions\AssignOccupationGuest;
use App\Enums\OccupationKind;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Guest;
use Filament\Actions\Action;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Notifications\Notification;
use Filament\Schemas\Components\Utilities\Get;
class AssignGuestAction
{
public static function make(): Action
{
return Action::make('assignGuest')->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();
});
}
}
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace App\Filament\Pages;
use App\Availability\OccupancyOverview;
use App\Filament\Concerns\FollowsAdminMode;
use App\Models\Booking;
use App\Models\Property;
use BackedEnum;
use Carbon\CarbonImmutable;
use Filament\Pages\Page;
use Filament\Support\Icons\Heroicon;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Facades\Validator;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use UnitEnum;
class OccupancyCalendar extends Page
{
use FollowsAdminMode;
protected string $view = 'filament.pages.occupancy-calendar';
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedCalendarDays;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $title = 'Belegungsplan';
protected static ?string $navigationLabel = 'Belegungsplan';
protected static ?string $slug = 'belegungsplan';
protected static ?int $navigationSort = 0;
#[Url(as: 'monat')]
public string $month = '';
#[Url(as: 'wohnung')]
public ?int $propertyId = null;
public static function canAccess(): bool
{
return Gate::allows('viewAny', Booking::class);
}
public function mount(): void
{
$this->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);
}
}
+1 -1
View File
@@ -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;
@@ -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 [
@@ -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(),
];
}
@@ -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)
@@ -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')
@@ -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'])]);
}
}
@@ -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
{
@@ -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);
}
}
@@ -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),
@@ -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(),
@@ -0,0 +1,27 @@
<?php
namespace App\Filament\Resources\PortalOccupations\Pages;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use Filament\Resources\Pages\ManageRecords;
use Filament\Schemas\Components\Tabs\Tab;
use Illuminate\Database\Eloquent\Builder;
class ManagePortalOccupations extends ManageRecords
{
protected static string $resource = PortalOccupationResource::class;
public function getTabs(): array
{
return [
'unclear' => 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 [];
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Filament\Resources\PortalOccupations\Pages;
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
use Filament\Resources\Pages\ViewRecord;
class ViewPortalOccupation extends ViewRecord
{
protected static string $resource = PortalOccupationResource::class;
public function getTitle(): string
{
return $this->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();
}
}
@@ -0,0 +1,133 @@
<?php
namespace App\Filament\Resources\PortalOccupations;
use App\Actions\ClassifyPortalOccupation;
use App\Enums\OccupationKind;
use App\Filament\Actions\AssignGuestAction;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\BlockedPeriods\BlockedPeriodResource;
use App\Filament\Resources\Bookings\BookingResource;
use App\Filament\Resources\PortalOccupations\Pages\ManagePortalOccupations;
use App\Filament\Resources\PortalOccupations\Pages\ViewPortalOccupation;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use BackedEnum;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Actions\ViewAction;
use Filament\Forms\Components\Select;
use Filament\Infolists\Components\TextEntry;
use Filament\Notifications\Notification;
use Filament\Resources\Resource;
use Filament\Schemas\Components\Section;
use Filament\Schemas\Schema;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Builder;
use UnitEnum;
class PortalOccupationResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = BlockedPeriod::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedQuestionMarkCircle;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $navigationLabel = 'Ungeklärte Belegungen';
protected static ?string $modelLabel = 'Portalbelegung';
protected static ?string $pluralModelLabel = 'Portalbelegungen & Klärung';
protected static ?int $navigationSort = 2;
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->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}')];
}
}
@@ -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'),
+71 -1
View File
@@ -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<BlockedPeriodFactory> */
@@ -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<Guest, $this> */
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<BlockedPeriod, $this> */
public function channelRepresentations(): HasMany
{
return $this->hasMany(self::class, 'canonical_block_id');
}
/** @param Builder<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
*/
#[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<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
*/
#[Scope]
protected function explicitBlocks(Builder $query): Builder
{
return $query->where(fn (Builder $query) => $query->where('source', 'manual')->orWhere('occupation_kind', OccupationKind::Block));
}
/** @param Builder<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
*/
#[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<BlockedPeriod> $query
* @return Builder<BlockedPeriod>
*/
+30
View File
@@ -157,6 +157,36 @@ public function guest(): BelongsTo
return $this->belongsTo(Guest::class);
}
/** @return BelongsTo<Channel, $this> */
public function originChannel(): BelongsTo
{
return $this->belongsTo(Channel::class, 'origin_channel_id');
}
/** @return BelongsTo<Channel, $this> */
public function importChannel(): BelongsTo
{
return $this->belongsTo(Channel::class, 'import_channel_id');
}
/** @return HasMany<BlockedPeriod, $this> */
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.
*
+7 -1
View File
@@ -42,12 +42,18 @@ public function bookings(): HasMany
return $this->hasMany(Booking::class)->latest('arrival');
}
/** @return HasMany<BlockedPeriod, $this> */
public function portalStays(): HasMany
{
return $this->hasMany(BlockedPeriod::class)->reservations()->occupying()->latest('starts_on');
}
/**
* @return Attribute<string, never>
*/
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}"));
}
/**