Doppelbuchungen nur einmal melden und im Postfach der Verwaltung zeigen

Der Kalenderabgleich alle 5 Minuten hat jede fortbestehende Ueberschneidung
erneut gemailt. ReportChannelConflicts legt jede Ueberschneidung einmal im
neuen Postfach (InboxMessage, Fingerabdruck je Mandant) ab und mailt nur neue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
LarsandClaude Opus 5.5 committed 2026-10-30 09:52:35 +01:00
1 parent 876a0a20f3
commit b9225f5fb8
17 files changed
+593 -15

No files matched your search

+4 -4
View File
@@ -9,13 +9,13 @@
use App\Enums\PortalEmailStatus;
use App\Enums\PortalEmailType;
use App\Enums\TenantServiceKey;
use App\Mail\ChannelConflict;
use App\Mail\PortalMailNotification;
use App\Models\BlockedPeriod;
use App\Models\Channel;
use App\Models\PortalEmail;
use App\Support\Settings;
use App\Tenancy\TenantFeatures;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
@@ -80,7 +80,7 @@ public function handle(PortalMail $mail): ?PortalEmail
}
if ($conflicts !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $conflicts)));
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
}
return $record;
@@ -126,7 +126,7 @@ public function senders(Channel $channel): array
}
/**
* @param list<string> $conflicts
* @param array<string, CarbonInterface> $conflicts description => first night
* @return array{PortalEmailStatus, ?BlockedPeriod, ?string}
*/
private function block(Channel $channel, ParsedPortalMail $parsed, array &$conflicts): array
@@ -158,7 +158,7 @@ private function block(Channel $channel, ParsedPortalMail $parsed, array &$confl
$block->forceFill(['needs_review' => true, 'review_note' => 'Überlappende Portalrepräsentationen ohne gemeinsame Kennung persönlich prüfen.'])->saveQuietly();
}
$conflicts = $this->conflictDetector->conflictsFor($block);
$conflicts = array_fill_keys($this->conflictDetector->conflictsFor($block), $block->starts_on);
return [PortalEmailStatus::Blocked, $block, null];
}
+50
View File
@@ -0,0 +1,50 @@
<?php
namespace App\Actions;
use App\Enums\InboxMessageKind;
use App\Filament\Pages\OccupancyCalendar;
use App\Mail\ChannelConflict;
use App\Models\Channel;
use App\Support\Inbox;
use App\Support\Settings;
use Carbon\CarbonInterface;
use Illuminate\Support\Facades\Mail;
/**
* Reports possible double bookings found while importing portal occupations (calendar sync or portal
* e-mail). Every conflict lands in the admin inbox once; only conflicts not reported before are e-mailed,
* so a lasting overlap does not trigger a mail on every sync.
*/
class ReportChannelConflicts
{
public function __construct(private Inbox $inbox) {}
/**
* @param array<string, CarbonInterface> $conflicts description => first night of the portal occupation
* @return list<string> the conflicts reported for the first time
*/
public function handle(Channel $channel, array $conflicts): array
{
$new = [];
foreach ($conflicts as $description => $startsOn) {
$message = $this->inbox->post(
InboxMessageKind::ChannelConflict,
$channel->id.':'.sha1($description),
'Mögliche Doppelbuchung über '.$channel->name,
$description,
$channel,
OccupancyCalendar::getUrl(['monat' => $startsOn->format('Y-m'), 'wohnung' => $channel->property_id]),
);
if ($message) {
$new[] = $description;
}
}
if ($new !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new)));
}
return $new;
}
}
+5 -8
View File
@@ -6,17 +6,14 @@
use App\Channels\ConflictDetector;
use App\Channels\ExternalPeriod;
use App\Enums\ChannelEchoBehavior;
use App\Mail\ChannelConflict;
use App\Models\BlockedPeriod;
use App\Models\Booking;
use App\Models\Channel;
use App\Models\ChannelSyncLog;
use App\Models\Property;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Mail;
/** Imports one complete channel snapshot without guessing that overlapping events are identical. */
class SyncChannel
@@ -129,18 +126,18 @@ public function handle(Channel $channel): ChannelSyncLog
}
$warnings[] = $note;
}
array_push($conflicts, ...$foundConflicts);
foreach ($foundConflicts as $conflict) {
$conflicts[$conflict] ??= $block->starts_on;
}
}
$warnings = array_values(array_unique($warnings));
$locked->forceFill(['last_synced_at' => now(), 'last_success_at' => now(), 'last_error' => null,
'alerted_at' => null, 'last_import_events' => count($periods), 'sync_warnings' => $warnings])->save();
});
if ($conflicts !== []) {
rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, array_values(array_unique($conflicts)))));
}
app(ReportChannelConflicts::class)->handle($channel, $conflicts);
return $channel->syncLogs()->create(['successful' => true, 'events' => count($periods), ...$counts,
'conflicts' => count(array_unique($conflicts)), 'warnings' => $warnings,
'conflicts' => count($conflicts), 'warnings' => $warnings,
'duration_ms' => (int) round((microtime(true) - $startedAt) * 1000)]);
} catch (ChannelSyncException $exception) {
$channel->forceFill(['last_synced_at' => now(), 'last_error_at' => now(), 'last_error' => $exception->getMessage()])->save();
+2 -1
View File
@@ -30,6 +30,7 @@ enum AdminMode: string implements HasDescription, HasLabel
*/
public const SIMPLE_NAVIGATION = [
OccupancyCalendar::class,
InboxMessageResource::class,
BookingResource::class,
PortalOccupationResource::class,
BlockedPeriodResource::class,
@@ -52,7 +53,7 @@ public function getLabel(): string
public function getDescription(): string
{
return match ($this) {
self::Simple => 'Das Tägliche: Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
self::Simple => 'Das Tägliche: Postfach, Anfragen, Buchungen und Verträge, Sperrzeiten, Preise & Angebote, Gäste, Kalenderabgleich (iCal), Portal-Aufgaben, Bewertungen, Fotos',
self::Expert => 'Alle Einstellungen: Preise, Angebote, Kalenderabgleich (iCal), Webseite, System',
};
}
+28
View File
@@ -0,0 +1,28 @@
<?php
namespace App\Enums;
use Filament\Support\Contracts\HasColor;
use Filament\Support\Contracts\HasLabel;
/**
* What an inbox message is about.
*/
enum InboxMessageKind: string implements HasColor, HasLabel
{
case ChannelConflict = 'channel_conflict';
public function getLabel(): string
{
return match ($this) {
self::ChannelConflict => 'Mögliche Doppelbuchung',
};
}
public function getColor(): string
{
return match ($this) {
self::ChannelConflict => 'danger',
};
}
}
@@ -0,0 +1,69 @@
<?php
namespace App\Filament\Resources\InboxMessages;
use App\Filament\Concerns\FollowsAdminMode;
use App\Filament\Resources\InboxMessages\Pages\ListInboxMessages;
use App\Filament\Resources\InboxMessages\Tables\InboxMessagesTable;
use App\Models\InboxMessage;
use BackedEnum;
use Filament\Resources\Resource;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Table;
use UnitEnum;
/**
* The admin inbox ("Postfach"): findings the landlord has to look at, each posted once (App\Support\Inbox).
*/
class InboxMessageResource extends Resource
{
use FollowsAdminMode;
protected static ?string $model = InboxMessage::class;
protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedInbox;
protected static string|UnitEnum|null $navigationGroup = 'Vermietung';
protected static ?string $navigationLabel = 'Postfach';
protected static ?string $modelLabel = 'Meldung';
protected static ?string $pluralModelLabel = 'Postfach';
protected static ?int $navigationSort = 0;
public static function table(Table $table): Table
{
return InboxMessagesTable::configure($table);
}
public static function canCreate(): bool
{
return false;
}
public static function getNavigationBadge(): ?string
{
$unread = InboxMessage::query()->unread()->count();
return $unread > 0 ? (string) $unread : null;
}
public static function getNavigationBadgeColor(): string
{
return 'danger';
}
public static function getNavigationBadgeTooltip(): ?string
{
return 'Ungelesen';
}
public static function getPages(): array
{
return [
'index' => ListInboxMessages::route('/'),
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Filament\Resources\InboxMessages\Pages;
use App\Filament\Concerns\ListsCurrentProperty;
use App\Filament\Resources\InboxMessages\InboxMessageResource;
use App\Models\Property;
use Filament\Actions\Action;
use Filament\Resources\Pages\ListRecords;
use Filament\Support\Icons\Heroicon;
use Illuminate\Database\Eloquent\Builder;
class ListInboxMessages extends ListRecords
{
use ListsCurrentProperty;
protected static string $resource = InboxMessageResource::class;
/**
* Messages of the chosen apartment and those that concern no apartment in particular.
*/
protected function scopeToProperty(Builder $query, Property $property): Builder
{
return $query->where(fn (Builder $query) => $query->where('property_id', $property->id)->orWhereNull('property_id'));
}
protected function getHeaderActions(): array
{
return [
Action::make('readAll')
->label('Alle als gelesen markieren')
->icon(Heroicon::OutlinedCheck)
->color('gray')
->visible(fn (): bool => $this->getTableQuery()->unread()->exists())
->action(fn () => $this->getTableQuery()->unread()->update(['read_at' => now()])),
];
}
}
@@ -0,0 +1,82 @@
<?php
namespace App\Filament\Resources\InboxMessages\Tables;
use App\Enums\InboxMessageKind;
use App\Models\InboxMessage;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Support\Enums\FontWeight;
use Filament\Support\Icons\Heroicon;
use Filament\Tables\Columns\IconColumn;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Filters\TernaryFilter;
use Filament\Tables\Table;
use Illuminate\Database\Eloquent\Collection;
class InboxMessagesTable
{
public static function configure(Table $table): Table
{
return $table
->defaultSort('created_at', 'desc')
->description('Hinweise, um die Sie sich kümmern sollten. Jede Meldung kommt nur einmal – auch wenn sie bei jedem Kalenderabgleich wieder auffällt.')
->emptyStateHeading('Keine Meldungen')
->columns([
IconColumn::make('read_at')
->label('')
->state(fn (InboxMessage $record): bool => ! $record->isRead())
->boolean()
->trueIcon(Heroicon::Envelope)
->falseIcon(Heroicon::OutlinedEnvelopeOpen)
->trueColor('danger')
->falseColor('gray')
->tooltip(fn (InboxMessage $record): string => $record->isRead() ? 'Gelesen' : 'Ungelesen'),
TextColumn::make('created_at')->label('Eingang')->dateTime('d.m. H:i')->sortable(),
TextColumn::make('kind')->label('Art')->badge(),
TextColumn::make('subject')
->label('Meldung')
->weight(fn (InboxMessage $record): ?FontWeight => $record->isRead() ? null : FontWeight::Bold)
->description(fn (InboxMessage $record): string => $record->body)
->wrap(),
])
->filters([
TernaryFilter::make('read_at')
->label('Gelesen')
->nullable()
->trueLabel('Nur gelesene')
->falseLabel('Nur ungelesene'),
SelectFilter::make('kind')->label('Art')->options(InboxMessageKind::class),
])
->recordUrl(null)
->recordActions([
Action::make('open')
->label('Ansehen')
->icon(Heroicon::OutlinedArrowTopRightOnSquare)
->visible(fn (InboxMessage $record): bool => filled($record->action_url))
->action(function (InboxMessage $record) {
$record->update(['read_at' => $record->read_at ?? now()]);
return redirect($record->action_url);
}),
Action::make('toggleRead')
->label(fn (InboxMessage $record): string => $record->isRead() ? 'Als ungelesen markieren' : 'Als gelesen markieren')
->icon(fn (InboxMessage $record): Heroicon => $record->isRead() ? Heroicon::OutlinedEnvelope : Heroicon::OutlinedCheck)
->color('gray')
->action(fn (InboxMessage $record) => $record->update(['read_at' => $record->isRead() ? null : now()])),
])
->toolbarActions([
BulkActionGroup::make([
BulkAction::make('markRead')
->label('Als gelesen markieren')
->icon(Heroicon::OutlinedCheck)
->action(fn (Collection $records) => InboxMessage::query()->whereKey($records->modelKeys())->update(['read_at' => now()]))
->deselectRecordsAfterCompletion(),
DeleteBulkAction::make(),
]),
]);
}
}
+68
View File
@@ -0,0 +1,68 @@
<?php
namespace App\Models;
use App\Enums\InboxMessageKind;
use App\Models\Concerns\BelongsToTenant;
use Database\Factories\InboxMessageFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Scope;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/**
* A message in the admin inbox ("Postfach"). The fingerprint identifies the finding, so the same
* finding is posted – and e-mailed – only once per landlord (App\Support\Inbox).
*/
#[Fillable(['property_id', 'channel_id', 'kind', 'fingerprint', 'subject', 'body', 'action_url', 'read_at'])]
class InboxMessage extends Model
{
/** @use HasFactory<InboxMessageFactory> */
use BelongsToTenant, HasFactory;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'kind' => InboxMessageKind::class,
'read_at' => 'immutable_datetime',
];
}
/**
* @return BelongsTo<Property, $this>
*/
public function property(): BelongsTo
{
return $this->belongsTo(Property::class);
}
/**
* @return BelongsTo<Channel, $this>
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
public function isRead(): bool
{
return $this->read_at !== null;
}
/**
* @param Builder<InboxMessage> $query
* @return Builder<InboxMessage>
*/
#[Scope]
protected function unread(Builder $query): Builder
{
return $query->whereNull('read_at');
}
}
+13
View File
@@ -0,0 +1,13 @@
<?php
namespace App\Policies;
use App\Enums\Permission;
class InboxMessagePolicy extends RolePolicy
{
protected function permission(): Permission
{
return Permission::Bookings;
}
}
+41
View File
@@ -0,0 +1,41 @@
<?php
namespace App\Support;
use App\Enums\InboxMessageKind;
use App\Models\Channel;
use App\Models\InboxMessage;
use Illuminate\Database\UniqueConstraintViolationException;
/**
* Posts findings to the admin inbox ("Postfach"). Each finding has a fingerprint and arrives only once
* per landlord, so a check that runs every few minutes reports a lasting problem a single time.
*/
class Inbox
{
/**
* @return InboxMessage|null the new message, or null when this finding was posted before
*/
public function post(InboxMessageKind $kind, string $fingerprint, string $subject, string $body, ?Channel $channel = null, ?string $actionUrl = null): ?InboxMessage
{
$fingerprint = $kind->value.':'.$fingerprint;
if (InboxMessage::query()->where('fingerprint', $fingerprint)->exists()) {
return null;
}
try {
return InboxMessage::create([
'kind' => $kind,
'fingerprint' => $fingerprint,
'subject' => mb_substr($subject, 0, 255),
'body' => $body,
'channel_id' => $channel?->id,
'property_id' => $channel?->property_id,
'action_url' => $actionUrl,
]);
} catch (UniqueConstraintViolationException) {
return null;
}
}
}