diff --git a/app/Actions/ProcessPortalMail.php b/app/Actions/ProcessPortalMail.php index f038996..df9dc6a 100644 --- a/app/Actions/ProcessPortalMail.php +++ b/app/Actions/ProcessPortalMail.php @@ -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 $conflicts + * @param array $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]; } diff --git a/app/Actions/ReportChannelConflicts.php b/app/Actions/ReportChannelConflicts.php new file mode 100644 index 0000000..88353e6 --- /dev/null +++ b/app/Actions/ReportChannelConflicts.php @@ -0,0 +1,50 @@ + $conflicts description => first night of the portal occupation + * @return list 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; + } +} diff --git a/app/Actions/SyncChannel.php b/app/Actions/SyncChannel.php index e78effe..2d97a56 100644 --- a/app/Actions/SyncChannel.php +++ b/app/Actions/SyncChannel.php @@ -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(); diff --git a/app/Enums/AdminMode.php b/app/Enums/AdminMode.php index e08a01f..7d42518 100644 --- a/app/Enums/AdminMode.php +++ b/app/Enums/AdminMode.php @@ -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', }; } diff --git a/app/Enums/InboxMessageKind.php b/app/Enums/InboxMessageKind.php new file mode 100644 index 0000000..7a757da --- /dev/null +++ b/app/Enums/InboxMessageKind.php @@ -0,0 +1,28 @@ + 'Mögliche Doppelbuchung', + }; + } + + public function getColor(): string + { + return match ($this) { + self::ChannelConflict => 'danger', + }; + } +} diff --git a/app/Filament/Resources/InboxMessages/InboxMessageResource.php b/app/Filament/Resources/InboxMessages/InboxMessageResource.php new file mode 100644 index 0000000..accf503 --- /dev/null +++ b/app/Filament/Resources/InboxMessages/InboxMessageResource.php @@ -0,0 +1,69 @@ +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('/'), + ]; + } +} diff --git a/app/Filament/Resources/InboxMessages/Pages/ListInboxMessages.php b/app/Filament/Resources/InboxMessages/Pages/ListInboxMessages.php new file mode 100644 index 0000000..ff9137a --- /dev/null +++ b/app/Filament/Resources/InboxMessages/Pages/ListInboxMessages.php @@ -0,0 +1,38 @@ +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()])), + ]; + } +} diff --git a/app/Filament/Resources/InboxMessages/Tables/InboxMessagesTable.php b/app/Filament/Resources/InboxMessages/Tables/InboxMessagesTable.php new file mode 100644 index 0000000..c65994e --- /dev/null +++ b/app/Filament/Resources/InboxMessages/Tables/InboxMessagesTable.php @@ -0,0 +1,82 @@ +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(), + ]), + ]); + } +} diff --git a/app/Models/InboxMessage.php b/app/Models/InboxMessage.php new file mode 100644 index 0000000..e285c79 --- /dev/null +++ b/app/Models/InboxMessage.php @@ -0,0 +1,68 @@ + */ + use BelongsToTenant, HasFactory; + + /** + * Get the attributes that should be cast. + * + * @return array + */ + protected function casts(): array + { + return [ + 'kind' => InboxMessageKind::class, + 'read_at' => 'immutable_datetime', + ]; + } + + /** + * @return BelongsTo + */ + public function property(): BelongsTo + { + return $this->belongsTo(Property::class); + } + + /** + * @return BelongsTo + */ + public function channel(): BelongsTo + { + return $this->belongsTo(Channel::class); + } + + public function isRead(): bool + { + return $this->read_at !== null; + } + + /** + * @param Builder $query + * @return Builder + */ + #[Scope] + protected function unread(Builder $query): Builder + { + return $query->whereNull('read_at'); + } +} diff --git a/app/Policies/InboxMessagePolicy.php b/app/Policies/InboxMessagePolicy.php new file mode 100644 index 0000000..36fd74e --- /dev/null +++ b/app/Policies/InboxMessagePolicy.php @@ -0,0 +1,13 @@ +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; + } + } +} diff --git a/database/factories/InboxMessageFactory.php b/database/factories/InboxMessageFactory.php new file mode 100644 index 0000000..5814f98 --- /dev/null +++ b/database/factories/InboxMessageFactory.php @@ -0,0 +1,33 @@ + + */ +class InboxMessageFactory extends Factory +{ + /** + * Define the model's default state. + * + * @return array + */ + public function definition(): array + { + return [ + 'kind' => InboxMessageKind::ChannelConflict, + 'fingerprint' => fake()->unique()->uuid(), + 'subject' => fake()->sentence(4), + 'body' => fake()->sentence(), + ]; + } + + public function read(): static + { + return $this->state(fn (): array => ['read_at' => now()]); + } +} diff --git a/database/migrations/2026_10_30_094414_create_inbox_messages_table.php b/database/migrations/2026_10_30_094414_create_inbox_messages_table.php new file mode 100644 index 0000000..3d8202f --- /dev/null +++ b/database/migrations/2026_10_30_094414_create_inbox_messages_table.php @@ -0,0 +1,36 @@ +id(); + $table->foreignId('tenant_id')->constrained()->cascadeOnDelete(); + $table->foreignId('property_id')->nullable()->constrained()->cascadeOnDelete(); + $table->foreignId('channel_id')->nullable()->constrained()->nullOnDelete(); + $table->string('kind'); + $table->string('fingerprint', 100); + $table->string('subject'); + $table->text('body'); + $table->string('action_url')->nullable(); + $table->timestamp('read_at')->nullable(); + $table->timestamps(); + $table->unique(['tenant_id', 'fingerprint']); + $table->index(['tenant_id', 'read_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('inbox_messages'); + } +}; diff --git a/docs/STATUS.md b/docs/STATUS.md index b05593a..a69ea46 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,7 @@ # Projektstand +**Doppelbuchungs-Mails nur noch einmal, neues Postfach in der Verwaltung (30.10.2026, Branch `feature/postfach`):** Ursache der Mailflut: `SyncChannel` prüfte bei jedem Abgleich (alle 5 Minuten) alle importierten Belegungen erneut und schickte jede fortbestehende Überschneidung wieder per Mail. Jetzt meldet `ReportChannelConflicts` (Kalenderabgleich und Portal-Mail) jede Überschneidung einmal: Sie landet im neuen **Postfach** (Vermietung › Postfach, `InboxMessage`, Zähler der ungelesenen im Menü, gelesen/ungelesen, „Ansehen“ öffnet den Belegungsplan im betroffenen Monat) und nur neue Meldungen gehen per Mail. Doppelte Meldungen verhindert ein Fingerabdruck je Mandant (`App\Support\Inbox`, eindeutiger Index). Ändern sich Termine, ist es eine neue Meldung. Das Synchronisationsprotokoll zählt offene Konflikte weiter. Nach dem Deployment kommt jede noch bestehende Überschneidung einmal neu (Postfach war leer). Tests: **513 Feature-Tests grün**, Pint. + **Wohnungen, Bilder und Banner neu geordnet (29.10.2026, Branch `feature/wohnungs-kontext`):** - **Wohnungsumschalter** oben im Verwaltungsmenü (`App\Support\CurrentProperty`, je Mandant in der Sitzung). Listen (Fotos, Ausstattung, Bewertungen, Grundrisse, Sperrzeiten, Kanäle, Portal-Aufgaben/-Mails, Importereignisse), neue Einträge, Belegungsplan und Preise & Angebote folgen ihm; die Buchungsliste startet mit dem Filter auf die Wohnung. Ein geöffneter Eintrag einer anderen Wohnung (z. B. aus einer Mail) schaltet um. Website: Galerie und Ersatz-Titelbild zeigen nur Fotos der Wohnung des Bausteins und Fotos ohne Wohnung. - **Grundriss & Pläne:** eigene Fotokategorie, die keine Galerie zeigt; vorhandene Grundriss-Bilder wurden umgestellt. Ausgeblendete Planbilder funktionieren im Grundriss weiterhin. diff --git a/resources/views/mail/channel-conflict.blade.php b/resources/views/mail/channel-conflict.blade.php index d5865f2..972bab5 100644 --- a/resources/views/mail/channel-conflict.blade.php +++ b/resources/views/mail/channel-conflict.blade.php @@ -9,7 +9,9 @@ Bitte prüfen Sie das umgehend im Portal und in der Verwaltung. Falls es sich um eine echte Doppelbuchung handelt, sollte einer der Gäste so früh wie möglich informiert werden. - -Buchungen öffnen +Diese Meldung steht auch im Postfach der Verwaltung. Sie kommt nur einmal, auch wenn die Überschneidung bei weiteren Abgleichen bestehen bleibt. + + +Postfach öffnen diff --git a/tests/Feature/ChannelSyncTest.php b/tests/Feature/ChannelSyncTest.php index a0cb1c1..6f25a18 100644 --- a/tests/Feature/ChannelSyncTest.php +++ b/tests/Feature/ChannelSyncTest.php @@ -10,6 +10,7 @@ use App\Enums\BookingStatus; use App\Enums\ChannelTaskAction; use App\Enums\ChannelTaskStatus; +use App\Enums\InboxMessageKind; use App\Filament\Resources\ChannelTasks\Pages\ListChannelTasks; use App\Filament\Resources\Properties\Pages\EditProperty; use App\Filament\Resources\Properties\RelationManagers\ChannelsRelationManager; @@ -21,6 +22,7 @@ use App\Models\Booking; use App\Models\Channel; use App\Models\ChannelTask; +use App\Models\InboxMessage; use App\Models\Property; use App\Models\User; use Carbon\CarbonImmutable; @@ -118,6 +120,33 @@ public function test_overlap_with_an_existing_booking_is_reported_as_possible_do $this->assertSame(1, $log->conflicts); Mail::assertSent(ChannelConflict::class); + $message = InboxMessage::sole(); + $this->assertSame(InboxMessageKind::ChannelConflict, $message->kind); + $this->assertSame($this->property->id, $message->property_id); + $this->assertStringContainsString('überschneidet sich mit Buchung', $message->body); + $this->assertStringContainsString('monat=2026-11', $message->action_url); + } + + public function test_a_lasting_double_booking_is_reported_once_however_often_the_calendar_is_synced(): void + { + $booking = Booking::factory()->for($this->property)->create(['arrival' => '2026-11-08', 'departure' => '2026-11-12', 'status' => BookingStatus::Confirmed]); + $channel = $this->channel('FeWo-direkt'); + $this->fakeFeed([['x1', '20261107', '20261110']]); + + foreach (range(1, 3) as $run) { + $this->travel(5)->minutes(); + $log = (new SyncChannel)->handle($channel); + $this->assertSame(1, $log->conflicts, 'the sync log keeps counting the open conflict'); + } + + Mail::assertSentCount(1); + $this->assertSame(1, InboxMessage::count()); + + $booking->update(['departure' => '2026-11-13']); + (new SyncChannel)->handle($channel); + + Mail::assertSent(ChannelConflict::class, 2); + $this->assertSame(2, InboxMessage::count()); } public function test_failed_import_is_logged_and_alerted_once_until_it_works_again(): void diff --git a/tests/Feature/InboxTest.php b/tests/Feature/InboxTest.php new file mode 100644 index 0000000..3966530 --- /dev/null +++ b/tests/Feature/InboxTest.php @@ -0,0 +1,89 @@ +actingAs(User::factory()->create()); + $this->channel = Channel::factory()->for(Property::factory())->create(['name' => 'FeWo-direkt']); + } + + public function test_a_finding_is_posted_only_once(): void + { + $inbox = app(Inbox::class); + + $first = $inbox->post(InboxMessageKind::ChannelConflict, 'x', 'Mögliche Doppelbuchung', 'Text', $this->channel); + $again = $inbox->post(InboxMessageKind::ChannelConflict, 'x', 'Mögliche Doppelbuchung', 'Text', $this->channel); + + $this->assertNotNull($first); + $this->assertNull($again); + $this->assertSame($this->channel->property_id, $first->property_id); + $this->assertSame(1, InboxMessage::count()); + } + + public function test_menu_shows_the_number_of_unread_messages(): void + { + InboxMessage::factory()->for($this->channel)->count(2)->create(); + InboxMessage::factory()->for($this->channel)->read()->create(); + + $this->assertSame('2', InboxMessageResource::getNavigationBadge()); + $this->get(InboxMessageResource::getUrl('index'))->assertOk()->assertSee('Postfach'); + } + + public function test_messages_can_be_marked_as_read_and_opened(): void + { + $message = InboxMessage::factory()->for($this->channel)->create(['subject' => 'Mögliche Doppelbuchung über FeWo-direkt', 'action_url' => 'http://localhost/admin/belegung']); + $other = InboxMessage::factory()->for($this->channel)->create(); + + Livewire::test(ListInboxMessages::class) + ->assertCanSeeTableRecords([$message, $other]) + ->assertSee('Mögliche Doppelbuchung über FeWo-direkt') + ->callAction(TestAction::make('toggleRead')->table($other)) + ->callAction(TestAction::make('open')->table($message)) + ->assertRedirect('http://localhost/admin/belegung'); + + $this->assertTrue($message->fresh()->isRead()); + $this->assertTrue($other->fresh()->isRead()); + $this->assertNull(InboxMessageResource::getNavigationBadge()); + } + + public function test_read_all_marks_only_the_chosen_apartments_messages(): void + { + $otherChannel = Channel::factory()->for(Property::factory())->create(); + $own = InboxMessage::factory()->for($this->channel)->create(['property_id' => $this->channel->property_id]); + $general = InboxMessage::factory()->create(['tenant_id' => $this->channel->tenant_id]); + $foreign = InboxMessage::factory()->for($otherChannel)->create(['property_id' => $otherChannel->property_id]); + app(CurrentProperty::class)->select($this->channel->property); + + Livewire::test(ListInboxMessages::class) + ->assertCanSeeTableRecords([$own, $general]) + ->assertCanNotSeeTableRecords([$foreign]) + ->callAction('readAll'); + + $this->assertTrue($own->fresh()->isRead()); + $this->assertTrue($general->fresh()->isRead()); + $this->assertFalse($foreign->fresh()->isRead()); + } +}