From 1c757f7429e7dd99ad37bcdb6e2a38b9e8e3c696 Mon Sep 17 00:00:00 2001 From: Lars Date: Fri, 30 Oct 2026 10:11:15 +0100 Subject: [PATCH] Erinnerungsabstand und taegliche/woechentliche Zusammenfassung einstellbar System > Betrieb > Benachrichtigungen: offene Meldungen (Doppelbuchungen im Postfach, Portal-Aufgaben) nur einmal oder alle 1/2/3/7 Tage erneut senden; Tages- und/oder Wochenuebersicht mit waehlbarer Uhrzeit, Wochentag und Inhalt (Postfach, Anfragen, Neues, An-/Abreisen, Zahlungen, Portale, Bewertungen). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- app/Actions/RemindChannelTasks.php | 10 +- app/Actions/ReportChannelConflicts.php | 16 +- app/Actions/SendDigests.php | 67 ++++++ app/Enums/DigestSection.php | 55 +++++ app/Filament/Pages/Operations.php | 85 ++++++- app/Mail/ChannelConflict.php | 12 +- app/Mail/Digest.php | 40 ++++ app/Models/InboxMessage.php | 4 +- app/Models/Tenant.php | 21 ++ app/Support/DigestReport.php | 218 ++++++++++++++++++ app/Support/Inbox.php | 28 ++- app/Support/Settings.php | 8 + ...10_30_100136_add_reminders_and_digests.php | 47 ++++ docs/STATUS.md | 2 + .../views/mail/channel-conflict.blade.php | 20 +- resources/views/mail/digest.blade.php | 23 ++ routes/console.php | 7 + tests/Feature/ChannelSyncTest.php | 43 ++++ tests/Feature/DigestTest.php | 156 +++++++++++++ 20 files changed, 842 insertions(+), 22 deletions(-) create mode 100644 app/Actions/SendDigests.php create mode 100644 app/Enums/DigestSection.php create mode 100644 app/Mail/Digest.php create mode 100644 app/Support/DigestReport.php create mode 100644 database/migrations/2026_10_30_100136_add_reminders_and_digests.php create mode 100644 resources/views/mail/digest.blade.php create mode 100644 tests/Feature/DigestTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 286de4c..a898391 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -17,7 +17,7 @@ # Ferienwohnung Stommer - Website = theme system (`docs/THEMES.md`): themes live in `resources/themes/` (theme.json, theme.css, theme.js, views); views resolve via the `theme::` namespace (theme → parent → base `ostsee-licht`). Pages are lists of sections (`app/Themes/Sections`, catalogue in `config/themes.php`); seasonal `Appearance`s override tokens/texts/hero photo/photos per section (stable `data.id` per placed section) and sections can be limited to appearances. Theme views use only token colour classes (`bg-accent`, `text-muted`, …). New designs are **additional** themes: `php artisan themes:make `, `themes:check`, `themes:preview` – never edit `ostsee-licht` for a new design; authoring rules in `docs/THEME-ERSTELLUNG.md`. Resolve `Theme` lazily (`app(Theme::class)`), never in constructors – middleware `ResolveTheme` replaces it per request. - Operations (environments, Strato access, server .env, admin accounts, 2FA, known pitfalls): `docs/BETRIEB.md` – read it before touching a server. Admin accounts: `php artisan users:create`; 2FA (Filament app authentication) is mandatory for every account. Admin modes (`App\Enums\AdminMode`: simple/expert per user, user menu switch) only shape the menu via the `FollowsAdminMode` trait on every resource/page (simple menu = `AdminMode::SIMPLE_NAVIGATION`); permissions stay with roles/policies. New admin resources must use `FollowsAdminMode`. - Deployment: `scripts/deploy.sh setup|deploy [ref]|rollback|releases|artisan` (atomic releases on Strato, docs/DEPLOYMENT.md; the server keeps only the active release because of Strato's file quota – history = Git tags `deploy//`); CI `.gitea/workflows/deploy.yml`. Production has no dev packages (no factories/Faker) – production seeding via `ProductionSeeder`. -- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0. +- Strato specifics: `public/index.php` strips the internal `/releases//public` prefix from `REQUEST_URI` (signed URLs); `URL::forceRootUrl(APP_URL)` outside local/testing; mail routing: `App\Support\Settings` (admin page System › Betrieb, stored on the tenant) – test mode (default) sends every mail to the test recipient only, live delivers normally; `FEWO_MAIL_REDIRECT_TO` is a hard override. Landlord data, bank, addresses and periods are columns of `tenants`: `App\Tenancy\TenantConfig` lays them over `config('fewo.*')` and `mail.from` whenever the tenant context changes, so views and mails keep reading the config keys. Send notifications to `Settings::notificationRecipients()` (never `config('fewo.notification_email')` directly). Findings detected repeatedly (e.g. by the 5-minute sync) go through `AppSupportInbox` (admin Postfach, fingerprint per tenant, repeated only per the tenant's `reminder_interval_days`), never straight to mail; daily/weekly summaries: `SendDigests` + `DigestReport` (sections `DigestSection`). Retention periods and bot-protection counters can only be tightened against the `.env` baseline. The booking form is protected against bots (`config('fewo.spam')`: honeypot, time trap, rate limits, max open holds per e-mail) – tests that submit it instantly set `fewo.spam.min_seconds` to 0. - Vite fonts plugin is removed on purpose (corporate proxy breaks remote font downloads, and fonts must be self-hosted for GDPR). - PHP/Composer on this machine: winget package dir `%LOCALAPPDATA%\Microsoft\WinGet\Packages\PHP.PHP.8.4_*` (Composer as `composer\composer.phar` there). - Git remote: Gitea `https://gitea.stommer.de/Lars/fewo-stommer.git`, branch `main`. diff --git a/app/Actions/RemindChannelTasks.php b/app/Actions/RemindChannelTasks.php index b560820..62a3eed 100644 --- a/app/Actions/RemindChannelTasks.php +++ b/app/Actions/RemindChannelTasks.php @@ -5,18 +5,24 @@ use App\Mail\ChannelTasksNotification; use App\Models\ChannelTask; use App\Support\Settings; +use Illuminate\Database\Eloquent\Builder; use Illuminate\Support\Facades\Mail; /** - * Reminds the landlord once about blocking tasks that are still open after the reminder time. + * Reminds the landlord about blocking tasks that are still open after the reminder time, and again after + * the landlord's reminder interval while they stay open (Settings::reminderIntervalDays(), 0 = only once). */ class RemindChannelTasks { public function handle(): int { + $interval = Settings::reminderIntervalDays(); + $tasks = ChannelTask::query() ->open() - ->whereNull('reminded_at') + ->where(fn (Builder $query) => $query + ->whereNull('reminded_at') + ->when($interval > 0, fn (Builder $query) => $query->orWhere('reminded_at', '<=', now()->subDays($interval)))) ->where('created_at', '<=', now()->subMinutes(config('fewo.channels.task_reminder_after_minutes'))) ->with('channel') ->get(); diff --git a/app/Actions/ReportChannelConflicts.php b/app/Actions/ReportChannelConflicts.php index 88353e6..b6cf2ae 100644 --- a/app/Actions/ReportChannelConflicts.php +++ b/app/Actions/ReportChannelConflicts.php @@ -14,7 +14,8 @@ /** * 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. + * so a lasting overlap does not trigger a mail on every sync. Unread ones are repeated after the landlord's + * reminder interval while the overlap persists (App\Support\Inbox). */ class ReportChannelConflicts { @@ -22,11 +23,12 @@ public function __construct(private Inbox $inbox) {} /** * @param array $conflicts description => first night of the portal occupation - * @return list the conflicts reported for the first time + * @return list the conflicts e-mailed now (new ones and due reminders) */ public function handle(Channel $channel, array $conflicts): array { $new = []; + $reminders = []; foreach ($conflicts as $description => $startsOn) { $message = $this->inbox->post( InboxMessageKind::ChannelConflict, @@ -36,15 +38,17 @@ public function handle(Channel $channel, array $conflicts): array $channel, OccupancyCalendar::getUrl(['monat' => $startsOn->format('Y-m'), 'wohnung' => $channel->property_id]), ); - if ($message) { + if ($message?->wasRecentlyCreated) { $new[] = $description; + } elseif ($message) { + $reminders[] = $description; } } - if ($new !== []) { - rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new))); + if ($new !== [] || $reminders !== []) { + rescue(fn () => Mail::to(Settings::notificationRecipients())->send(new ChannelConflict($channel, $new, $reminders))); } - return $new; + return [...$new, ...$reminders]; } } diff --git a/app/Actions/SendDigests.php b/app/Actions/SendDigests.php new file mode 100644 index 0000000..daa1fe1 --- /dev/null +++ b/app/Actions/SendDigests.php @@ -0,0 +1,67 @@ +startOfDay(); + if ($now->hour < $tenant->digest_hour) { + return null; + } + + $weekly = $tenant->digest_weekly && $today->isoWeekday() === $tenant->digest_weekday && ! $tenant->digest_weekly_sent_on?->isSameDay($today); + $daily = $tenant->digest_daily && ! $tenant->digest_daily_sent_on?->isSameDay($today); + if (! $weekly && ! $daily) { + return null; + } + + $this->send($tenant, $weekly); + $tenant->forceFill([ + 'digest_daily_sent_on' => $today->toDateString(), + ...($weekly ? ['digest_weekly_sent_on' => $today->toDateString()] : []), + ])->save(); + + return $weekly ? 'weekly' : 'daily'; + } + + /** + * Builds and mails one summary. Without anything to report it is skipped unless the landlord wants it + * anyway or $force is set (button „Zusammenfassung jetzt senden“). + * + * @return bool whether a mail was sent + */ + public function send(Tenant $tenant, bool $weekly, bool $force = false): bool + { + $since = CarbonImmutable::now()->sub($weekly ? '7 days' : '1 day'); + $sections = $this->report->build(DigestSection::chosen($tenant->digest_sections), $weekly, $since); + + if ($sections === [] && ! $tenant->digest_when_empty && ! $force) { + return false; + } + + Mail::to(Settings::notificationRecipients())->send(new Digest($weekly, $sections)); + + return true; + } +} diff --git a/app/Enums/DigestSection.php b/app/Enums/DigestSection.php new file mode 100644 index 0000000..06e460c --- /dev/null +++ b/app/Enums/DigestSection.php @@ -0,0 +1,55 @@ + 'Postfach', + self::Requests => 'Offene Anfragen und Angebote', + self::News => 'Neu seit der letzten Übersicht', + self::Stays => 'An- und Abreisen', + self::Payments => 'Überfällige Zahlungen', + self::Portals => 'Portale: Aufgaben und Klärungsfälle', + self::Reviews => 'Bewertungen zur Freigabe', + }; + } + + public function getDescription(): string + { + return match ($this) { + self::Inbox => 'Ungelesene Meldungen, z. B. mögliche Doppelbuchungen', + self::Requests => 'Anfragen und Angebote, die auf Sie oder den Gast warten, mit Frist', + self::News => 'Neue Anfragen, Buchungen, Stornierungen und Portalbuchungen', + self::Stays => 'Heute und morgen, in der Wochenübersicht die nächsten 7 Tage', + self::Payments => 'Anzahlungen und Restzahlungen nach Fälligkeit', + self::Portals => 'Offene Portal-Aufgaben, zu prüfende Portal-Mails und Kalendereinträge, Abgleichsfehler', + self::Reviews => 'Neue Bewertungen, die noch nicht freigegeben sind', + }; + } + + /** + * @param list|null $values stored choice; null = everything + * @return list + */ + public static function chosen(?array $values): array + { + return $values === null ? self::cases() : array_values(array_filter(self::cases(), fn (self $section): bool => in_array($section->value, $values, true))); + } +} diff --git a/app/Filament/Pages/Operations.php b/app/Filament/Pages/Operations.php index a69ca5d..501fa99 100644 --- a/app/Filament/Pages/Operations.php +++ b/app/Filament/Pages/Operations.php @@ -2,6 +2,8 @@ namespace App\Filament\Pages; +use App\Actions\SendDigests; +use App\Enums\DigestSection; use App\Enums\TenantServiceKey; use App\Enums\UserRole; use App\Filament\Concerns\FollowsAdminMode; @@ -11,10 +13,12 @@ use App\Tenancy\TenantFeatures; use BackedEnum; use Filament\Actions\Action; +use Filament\Forms\Components\CheckboxList; use Filament\Forms\Components\Radio; use Filament\Forms\Components\Select; use Filament\Forms\Components\TagsInput; use Filament\Forms\Components\TextInput; +use Filament\Forms\Components\Toggle; use Filament\Notifications\Notification; use Filament\Pages\Page; use Filament\Schemas\Components\Actions; @@ -30,7 +34,7 @@ /** * Operating data of the landlord: operating mode (test mode sends every e-mail to one test recipient only; * live delivers to the real recipients), the addresses of the internal communication, the landlord's own - * address and bank details, and the periods. Administrators only. + * address and bank details, reminders and summaries, and the periods. Administrators only. */ class Operations extends Page { @@ -53,6 +57,11 @@ class Operations extends Page 'channel_task_reminder_after_minutes' => 'Erinnerung an Portal-Aufgaben nach (Minuten)', ]; + /** Choices for repeating open findings (days => label). */ + public const REMINDER_INTERVALS = [0 => 'Nur einmal', 1 => 'Täglich', 2 => 'Alle 2 Tage', 3 => 'Alle 3 Tage', 7 => 'Wöchentlich']; + + public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag']; + protected static string|BackedEnum|null $navigationIcon = Heroicon::OutlinedPower; protected static string|UnitEnum|null $navigationGroup = 'System'; @@ -99,6 +108,13 @@ public function mount(): void 'mailbox_password' => $tenant->mailbox_password, 'mailbox_encryption' => $tenant->mailbox_encryption, 'mailbox_folder' => $tenant->mailbox_folder, + 'reminder_interval_days' => $tenant->reminder_interval_days, + 'digest_daily' => $tenant->digest_daily, + 'digest_weekly' => $tenant->digest_weekly, + 'digest_weekday' => $tenant->digest_weekday, + 'digest_hour' => $tenant->digest_hour, + 'digest_sections' => array_map(fn (DigestSection $section): string => $section->value, DigestSection::chosen($tenant->digest_sections)), + 'digest_when_empty' => $tenant->digest_when_empty, ...$this->periodValues($tenant), ]); } @@ -181,6 +197,43 @@ public function form(Schema $schema): Schema ->maxLength(255) ->columnSpanFull(), ]), + Section::make('Benachrichtigungen') + ->description('Wie oft offene Meldungen wiederholt werden und welche Zusammenfassungen Sie per E-Mail erhalten. Empfänger sind die Adressen unter „Benachrichtigungen an“.') + ->columns(2) + ->schema([ + Select::make('reminder_interval_days') + ->label('Offene Meldungen erneut senden') + ->helperText('Gilt für mögliche Doppelbuchungen (solange sie im Postfach ungelesen sind und weiter bestehen) und offene Portal-Aufgaben.') + ->options(self::REMINDER_INTERVALS) + ->selectablePlaceholder(false) + ->required() + ->columnSpanFull(), + Toggle::make('digest_daily')->label('Tägliche Zusammenfassung'), + Toggle::make('digest_weekly')->label('Wöchentliche Zusammenfassung')->live(), + Select::make('digest_hour') + ->label('Versand ab') + ->options(collect(range(5, 21))->mapWithKeys(fn (int $hour): array => [$hour => sprintf('%02d:00 Uhr', $hour)])->all()) + ->selectablePlaceholder(false) + ->required(), + Select::make('digest_weekday') + ->label('Wochentag der Wochenübersicht') + ->helperText('An diesem Tag kommt nur die Wochenübersicht, nicht zusätzlich die tägliche.') + ->options(self::WEEKDAYS) + ->selectablePlaceholder(false) + ->visible(fn (Get $get): bool => (bool) $get('digest_weekly')) + ->required(), + CheckboxList::make('digest_sections') + ->label('Inhalt der Zusammenfassung') + ->options(DigestSection::class) + ->descriptions(collect(DigestSection::cases())->mapWithKeys(fn (DigestSection $section): array => [$section->value => $section->getDescription()])->all()) + ->columns(2) + ->required() + ->columnSpanFull(), + Toggle::make('digest_when_empty') + ->label('Auch senden, wenn nichts ansteht') + ->helperText('Sonst entfällt die Zusammenfassung an Tagen ohne offene Punkte.') + ->columnSpanFull(), + ]), Section::make('Portal-Postfach') ->description('Aus diesem Postfach werden die Buchungsmails der Portale gelesen, damit ein Termin sofort gesperrt wird. Leerer Server = ausgeschaltet. Das Passwort liegt verschlüsselt in der Datenbank.') ->columns(2) @@ -215,6 +268,29 @@ public function content(Schema $schema): Schema ]); } + protected function getHeaderActions(): array + { + return [ + Action::make('sendDigest') + ->label('Zusammenfassung jetzt senden') + ->icon(Heroicon::OutlinedPaperAirplane) + ->color('gray') + ->modalDescription('Schickt die Zusammenfassung mit den gespeicherten Einstellungen sofort an die Benachrichtigungsadressen – auch wenn nichts ansteht. Der reguläre Versand bleibt unverändert.') + ->schema([ + Radio::make('weekly') + ->label('Welche?') + ->options([0 => 'Tagesübersicht', 1 => 'Wochenübersicht']) + ->default(0) + ->required(), + ]) + ->action(function (array $data): void { + app(SendDigests::class)->send($this->tenant(), (bool) $data['weekly'], force: true); + + Notification::make()->title('Zusammenfassung gesendet')->body(Settings::isLive() ? null : 'Testbetrieb: Sie geht an die Testadresse.')->success()->send(); + }), + ]; + } + public function save(): void { $data = $this->form->getState(); @@ -243,6 +319,13 @@ public function save(): void 'mailbox_password' => $data['mailbox_password'] ?? null, 'mailbox_encryption' => $data['mailbox_encryption'] ?? null, 'mailbox_folder' => $data['mailbox_folder'] ?? null, + 'reminder_interval_days' => (int) $data['reminder_interval_days'], + 'digest_daily' => (bool) $data['digest_daily'], + 'digest_weekly' => (bool) $data['digest_weekly'], + 'digest_weekday' => (int) ($data['digest_weekday'] ?? $tenant->digest_weekday), + 'digest_hour' => (int) $data['digest_hour'], + 'digest_sections' => count($data['digest_sections']) === count(DigestSection::cases()) ? null : array_values($data['digest_sections']), + 'digest_when_empty' => (bool) $data['digest_when_empty'], ...array_map(fn (mixed $value): ?int => filled($value) ? (int) $value : null, $this->periodInput($data)), ]); diff --git a/app/Mail/ChannelConflict.php b/app/Mail/ChannelConflict.php index 29b3da4..ea6e1fe 100644 --- a/app/Mail/ChannelConflict.php +++ b/app/Mail/ChannelConflict.php @@ -10,19 +10,23 @@ use Illuminate\Queue\SerializesModels; /** - * Reports overlaps between a newly imported portal occupation and occupations from elsewhere. + * Reports overlaps between an imported portal occupation and occupations from elsewhere: new ones and + * reminders about ones that are still open. */ class ChannelConflict extends Mailable { use Queueable, SerializesModels; - /** @param list $conflicts */ - public function __construct(public Channel $channel, public array $conflicts) {} + /** + * @param list $conflicts reported for the first time + * @param list $reminders reported before, still unread and still detected + */ + public function __construct(public Channel $channel, public array $conflicts, public array $reminders = []) {} public function envelope(): Envelope { return new Envelope( - subject: 'Achtung: mögliche Doppelbuchung über '.$this->channel->name, + subject: ($this->conflicts === [] ? 'Erinnerung' : 'Achtung').': mögliche Doppelbuchung über '.$this->channel->name, ); } diff --git a/app/Mail/Digest.php b/app/Mail/Digest.php new file mode 100644 index 0000000..b6ed624 --- /dev/null +++ b/app/Mail/Digest.php @@ -0,0 +1,40 @@ +, more: int, url: string, link: string}> $sections + */ + public function __construct(public bool $weekly, public array $sections) {} + + public function envelope(): Envelope + { + $title = $this->weekly ? 'Wochenübersicht KW '.now()->isoWeek() : 'Tagesübersicht '.now()->format('d.m.Y'); + $count = array_sum(array_map(fn (array $section): int => count($section['items']) + $section['more'], $this->sections)); + + return new Envelope( + subject: $title.($count === 0 ? ': nichts Neues' : ": {$count} ".($count === 1 ? 'Punkt' : 'Punkte')), + ); + } + + public function content(): Content + { + return new Content( + markdown: 'mail.digest', + ); + } +} diff --git a/app/Models/InboxMessage.php b/app/Models/InboxMessage.php index e285c79..f8ca8db 100644 --- a/app/Models/InboxMessage.php +++ b/app/Models/InboxMessage.php @@ -16,7 +16,7 @@ * 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'])] +#[Fillable(['property_id', 'channel_id', 'kind', 'fingerprint', 'subject', 'body', 'action_url', 'notified_at', 'last_seen_at', 'read_at'])] class InboxMessage extends Model { /** @use HasFactory */ @@ -31,6 +31,8 @@ protected function casts(): array { return [ 'kind' => InboxMessageKind::class, + 'notified_at' => 'immutable_datetime', + 'last_seen_at' => 'immutable_datetime', 'read_at' => 'immutable_datetime', ]; } diff --git a/app/Models/Tenant.php b/app/Models/Tenant.php index c0ccac5..bf58c7d 100644 --- a/app/Models/Tenant.php +++ b/app/Models/Tenant.php @@ -26,12 +26,24 @@ 'retention_portal_email_excerpt_days', 'retention_attribution_months', 'spam_min_seconds', 'spam_per_ip_per_hour', 'spam_per_email_per_day', 'spam_open_requests_per_email', 'spam_max_links', 'channel_stale_after_minutes', 'channel_task_reminder_after_minutes', + 'reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', 'digest_sections', + 'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on', ])] class Tenant extends Model { /** @use HasFactory */ use HasFactory; + /** Reminder and summary defaults: repeat nothing, a daily summary from 7 a.m., the weekly one on Mondays. */ + protected $attributes = [ + 'reminder_interval_days' => 0, + 'digest_daily' => true, + 'digest_weekly' => false, + 'digest_weekday' => 1, + 'digest_hour' => 7, + 'digest_when_empty' => false, + ]; + /** * The landlord the existing single-website data belongs to. */ @@ -56,6 +68,15 @@ protected function casts(): array 'bank_name' => 'encrypted', 'tax_note' => 'encrypted', 'mailbox_password' => 'encrypted', + 'reminder_interval_days' => 'integer', + 'digest_daily' => 'boolean', + 'digest_weekly' => 'boolean', + 'digest_weekday' => 'integer', + 'digest_hour' => 'integer', + 'digest_sections' => 'array', + 'digest_when_empty' => 'boolean', + 'digest_daily_sent_on' => 'immutable_date', + 'digest_weekly_sent_on' => 'immutable_date', ]; } diff --git a/app/Support/DigestReport.php b/app/Support/DigestReport.php new file mode 100644 index 0000000..5591045 --- /dev/null +++ b/app/Support/DigestReport.php @@ -0,0 +1,218 @@ + $sections + * @return list, more: int, url: string, link: string}> + */ + public function build(array $sections, bool $weekly, CarbonImmutable $since): array + { + $this->namesProperty = Property::query()->count() > 1; + $report = []; + + foreach ($sections as $section) { + [$title, $lines, $url, $link] = match ($section) { + DigestSection::Inbox => ['Postfach: ungelesene Meldungen', $this->inbox(), InboxMessageResource::getUrl('index'), 'Postfach öffnen'], + DigestSection::Requests => ['Offene Anfragen und Angebote', $this->requests(), BookingResource::getUrl('index'), 'Buchungen öffnen'], + DigestSection::News => ['Neu seit '.$since->format('d.m. H:i').' Uhr', $this->news($since), BookingResource::getUrl('index'), 'Buchungen öffnen'], + DigestSection::Stays => [$weekly ? 'An- und Abreisen der nächsten 7 Tage' : 'An- und Abreisen heute und morgen', $this->stays($weekly ? 7 : 2), OccupancyCalendar::getUrl(), 'Belegungsplan öffnen'], + DigestSection::Payments => ['Überfällige Zahlungen', $this->payments(), BookingResource::getUrl('index'), 'Buchungen öffnen'], + DigestSection::Portals => ['Portale: Aufgaben und Klärungsfälle', $this->portals(), ChannelTaskResource::getUrl('index'), 'Portal-Aufgaben öffnen'], + DigestSection::Reviews => ['Bewertungen zur Freigabe', $this->reviews(), ReviewResource::getUrl('index'), 'Bewertungen öffnen'], + }; + + if ($lines->isEmpty()) { + continue; + } + + $report[] = [ + 'section' => $section, + 'title' => $title, + 'items' => $lines->take(self::MAX_ITEMS)->values()->all(), + 'more' => max(0, $lines->count() - self::MAX_ITEMS), + 'url' => $url, + 'link' => $link, + ]; + } + + return $report; + } + + /** + * @return Collection + */ + private function inbox(): Collection + { + return InboxMessage::query()->unread()->latest()->get() + ->map(fn (InboxMessage $message): string => $message->created_at->format('d.m.').' · '.e($message->subject).': '.e($message->body)); + } + + /** + * @return Collection + */ + private function requests(): Collection + { + return Booking::query()->whereIn('status', BookingStatus::holding())->with(['guest', 'property'])->orderBy('hold_expires_at')->get() + ->map(fn (Booking $booking): string => $this->booking($booking).' – '.$booking->status->getLabel().$this->deadline($booking)); + } + + /** + * @return Collection + */ + private function news(CarbonImmutable $since): Collection + { + $created = Booking::query()->where('created_at', '>=', $since)->with(['guest', 'property'])->oldest()->get() + ->map(fn (Booking $booking): string => 'Neu: '.$this->booking($booking).' – '.$booking->status->getLabel()); + $cancelled = Booking::query()->where('status', BookingStatus::Cancelled)->where('created_at', '<', $since)->where('updated_at', '>=', $since)->with(['guest', 'property'])->get() + ->map(fn (Booking $booking): string => 'Storniert: '.$this->booking($booking)); + $portal = BlockedPeriod::query()->reservations()->occupying()->where('created_at', '>=', $since)->with(['channel', 'originChannel', 'guest'])->oldest()->get() + ->map(fn (BlockedPeriod $block): string => 'Portalbuchung '.e($block->bookingChannelLabel()).': '.$this->period($block->starts_on, $block->ends_on).($block->guestName() ? ', '.e($block->guestName()) : '')); + + return $created->concat($cancelled)->concat($portal)->values(); + } + + /** + * Arrivals and departures from today on, $days days long, sorted by day (departures first). + * + * @return Collection + */ + private function stays(int $days): Collection + { + $from = CarbonImmutable::today(); + $last = $from->addDays($days - 1); + $within = fn (string $start, string $end) => fn (Builder $query) => $query + ->where(fn (Builder $query) => $query->whereDate($start, '>=', $from)->whereDate($start, '<=', $last)) + ->orWhere(fn (Builder $query) => $query->whereDate($end, '>=', $from)->whereDate($end, '<=', $last)); + $events = []; + + foreach (Booking::query()->whereIn('status', BookingStatus::occupying())->where($within('arrival', 'departure'))->with(['guest', 'property'])->get() as $booking) { + $this->stayEvents($events, $from, $last, $booking->arrival, $booking->departure, $this->booking($booking)); + } + foreach (BlockedPeriod::query()->reservations()->occupying()->where($within('starts_on', 'ends_on'))->with(['channel', 'originChannel', 'guest'])->get() as $block) { + $this->stayEvents($events, $from, $last, $block->starts_on, $block->ends_on, e(trim($block->bookingChannelLabel().' '.($block->guestName() ?? '')))); + } + + ksort($events); + + return collect(array_values($events)); + } + + /** + * @param array $events + */ + private function stayEvents(array &$events, CarbonImmutable $from, CarbonImmutable $last, CarbonImmutable $arrival, CarbonImmutable $departure, string $label): void + { + if ($departure->betweenIncluded($from, $last)) { + $events[$departure->toDateString().'-0-'.count($events)] = $this->day($departure).': Abreise '.$label; + } + if ($arrival->betweenIncluded($from, $last)) { + $events[$arrival->toDateString().'-1-'.count($events)] = $this->day($arrival).': Anreise '.$label.' (bis '.$departure->format('d.m.').')'; + } + } + + /** + * @return Collection + */ + private function payments(): Collection + { + return Booking::query()->whereIn('status', [BookingStatus::Confirmed, BookingStatus::DepositPaid])->with(['guest', 'property', 'payments'])->orderBy('arrival')->get() + ->map(fn (Booking $booking): ?string => match (true) { + $booking->status === BookingStatus::Confirmed && $booking->deposit_due_on?->isPast() && $booking->openDeposit() > 0 => $this->booking($booking).' – Anzahlung '.Money::format($booking->openDeposit()).' seit '.$booking->deposit_due_on->format('d.m.').' fällig', + $booking->balance_due_on?->isPast() && $booking->openAmount() > 0 => $this->booking($booking).' – offen '.Money::format($booking->openAmount()).' seit '.$booking->balance_due_on->format('d.m.').' fällig', + default => null, + }) + ->filter() + ->values(); + } + + /** + * @return Collection + */ + private function portals(): Collection + { + $tasks = ChannelTask::query()->open()->with('channel')->oldest()->get() + ->map(fn (ChannelTask $task): string => 'Aufgabe '.e($task->channel->name).': '.$task->action->getLabel().' '.$task->period()); + $mails = PortalEmail::query()->where('status', PortalEmailStatus::NeedsReview)->with('channel')->latest('received_at')->get() + ->map(fn (PortalEmail $mail): string => 'Portal-Mail prüfen ('.e($mail->channel->name).'): '.e($mail->subject)); + $unclear = BlockedPeriod::query()->unclear()->whereDate('ends_on', '>', today())->with('channel')->orderBy('starts_on')->get() + ->map(fn (BlockedPeriod $block): string => 'Kalendereintrag klären ('.e($block->channel->name ?? 'Portal').'): '.$this->period($block->starts_on, $block->ends_on) + .' · [ansehen]('.PortalOccupationResource::getUrl('view', ['record' => $block->id]).')'); + $channels = Channel::query()->active()->get()->filter(fn (Channel $channel): bool => $channel->isStale() || filled($channel->last_error)) + ->map(fn (Channel $channel): string => 'Kalenderabgleich '.e($channel->name).': '.e($channel->last_error ?: 'seit längerem kein erfolgreicher Abruf')); + + return $tasks->concat($mails)->concat($unclear)->concat($channels)->values(); + } + + /** + * @return Collection + */ + private function reviews(): Collection + { + return Review::query()->where('status', ReviewStatus::Pending)->oldest()->get() + ->map(fn (Review $review): string => $review->rating.'/5'.($review->title ? ' „'.e($review->title).'“' : '').($review->display_name ? ' von '.e($review->display_name) : '')); + } + + private function booking(Booking $booking): string + { + return '['.$booking->reference.']('.BookingResource::getUrl('view', ['record' => $booking]).') ' + .e($booking->guest?->full_name ?? 'Gast').', '.$this->period($booking->arrival, $booking->departure) + .($this->namesProperty ? ' ('.e($booking->property->name).')' : ''); + } + + private function deadline(Booking $booking): string + { + if ($booking->hold_expires_at === null) { + return ''; + } + + return ', Frist bis '.$booking->hold_expires_at->format('d.m. H:i').' Uhr'.($booking->hold_expires_at->isPast() ? ' (abgelaufen)' : ''); + } + + private function period(CarbonImmutable $from, CarbonImmutable $until): string + { + return $from->format('d.m.').'–'.$until->format('d.m.Y'); + } + + private function day(CarbonImmutable $date): string + { + return match (true) { + $date->isToday() => 'Heute', + $date->isTomorrow() => 'Morgen', + default => $date->locale('de')->isoFormat('dd DD.MM.'), + }; + } +} diff --git a/app/Support/Inbox.php b/app/Support/Inbox.php index f2a8140..aa293a2 100644 --- a/app/Support/Inbox.php +++ b/app/Support/Inbox.php @@ -9,19 +9,25 @@ /** * 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. + * per landlord, so a check that runs every few minutes does not report a lasting problem again and again. + * While the finding is still detected and the message is unread, it is repeated after the landlord's + * reminder interval (Settings::reminderIntervalDays(), 0 = never). */ class Inbox { /** - * @return InboxMessage|null the new message, or null when this finding was posted before + * @return InboxMessage|null the message to e-mail now – new (wasRecentlyCreated) or due for a reminder – else null */ 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; + $existing = InboxMessage::query()->where('fingerprint', $fingerprint)->first(); + if ($existing) { + $due = $this->reminderDue($existing); + $existing->forceFill(['last_seen_at' => now(), ...($due ? ['notified_at' => now()] : [])])->save(); + + return $due ? $existing : null; } try { @@ -33,9 +39,23 @@ public function post(InboxMessageKind $kind, string $fingerprint, string $subjec 'channel_id' => $channel?->id, 'property_id' => $channel?->property_id, 'action_url' => $actionUrl, + 'notified_at' => now(), + 'last_seen_at' => now(), ]); } catch (UniqueConstraintViolationException) { return null; } } + + /** + * Unread messages are repeated once the reminder interval has passed; reading one ends its reminders. + */ + public function reminderDue(InboxMessage $message): bool + { + $days = Settings::reminderIntervalDays($message->tenant); + + return $days > 0 + && ! $message->isRead() + && ($message->notified_at === null || $message->notified_at->lessThanOrEqualTo(now()->subDays($days))); + } } diff --git a/app/Support/Settings.php b/app/Support/Settings.php index 15b60e9..4892aa3 100644 --- a/app/Support/Settings.php +++ b/app/Support/Settings.php @@ -80,6 +80,14 @@ public static function mailRedirectFor(?Tenant $tenant): ?string return $tenant?->test_recipient ?: ($recipients[0] ?? null); } + /** + * After how many days an unread, still detected finding is e-mailed again; 0 = only once. + */ + public static function reminderIntervalDays(?Tenant $tenant = null): int + { + return (int) (($tenant ?? self::tenant())?->reminder_interval_days ?? 0); + } + /** * Applies the redirect of the current landlord to the mailer; called after saving. */ diff --git a/database/migrations/2026_10_30_100136_add_reminders_and_digests.php b/database/migrations/2026_10_30_100136_add_reminders_and_digests.php new file mode 100644 index 0000000..16bc6ec --- /dev/null +++ b/database/migrations/2026_10_30_100136_add_reminders_and_digests.php @@ -0,0 +1,47 @@ +unsignedSmallInteger('reminder_interval_days')->default(0); + $table->boolean('digest_daily')->default(true); + $table->boolean('digest_weekly')->default(false); + $table->unsignedTinyInteger('digest_weekday')->default(1); + $table->unsignedTinyInteger('digest_hour')->default(7); + $table->json('digest_sections')->nullable(); + $table->boolean('digest_when_empty')->default(false); + $table->date('digest_daily_sent_on')->nullable(); + $table->date('digest_weekly_sent_on')->nullable(); + }); + + Schema::table('inbox_messages', function (Blueprint $table) { + $table->timestamp('notified_at')->nullable()->after('action_url'); + $table->timestamp('last_seen_at')->nullable()->after('notified_at'); + }); + + DB::table('inbox_messages')->update(['notified_at' => DB::raw('created_at'), 'last_seen_at' => DB::raw('created_at')]); + } + + public function down(): void + { + Schema::table('inbox_messages', function (Blueprint $table) { + $table->dropColumn(['notified_at', 'last_seen_at']); + }); + + Schema::table('tenants', function (Blueprint $table) { + $table->dropColumn(['reminder_interval_days', 'digest_daily', 'digest_weekly', 'digest_weekday', 'digest_hour', + 'digest_sections', 'digest_when_empty', 'digest_daily_sent_on', 'digest_weekly_sent_on']); + }); + } +}; diff --git a/docs/STATUS.md b/docs/STATUS.md index a69ea46..8d82433 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,7 @@ # Projektstand +**Erinnerungen und Zusammenfassungen einstellbar (30.10.2026, Branch `feature/erinnerungen-zusammenfassung`):** Neuer Abschnitt System › Betrieb › **Benachrichtigungen** (Spalten auf `tenants`). „Offene Meldungen erneut senden“: nur einmal (Vorgabe), täglich, alle 2/3 Tage, wöchentlich – gilt für mögliche Doppelbuchungen (solange im Postfach ungelesen und weiter festgestellt; Lesen beendet die Erinnerung, `Inbox::reminderDue`) und offene Portal-Aufgaben (`RemindChannelTasks`). **Tägliche und/oder wöchentliche Zusammenfassung** (`SendDigests`, Scheduler alle 15 Minuten, ab wählbarer Uhrzeit, Wochentag wählbar; am Wochentag nur die Wochenübersicht) mit wählbaren Teilen (`DigestSection`, `DigestReport`): Postfach, offene Anfragen/Angebote mit Frist, Neues seit der letzten Übersicht (Anfragen, Buchungen, Stornierungen, Portalbuchungen), An-/Abreisen (heute+morgen bzw. 7 Tage), überfällige Zahlungen, Portal-Aufgaben/zu prüfende Portal-Mails/Kalender-Klärungsfälle/Abgleichsfehler, Bewertungen zur Freigabe. Leere Übersichten entfallen (abschaltbar), Knopf „Zusammenfassung jetzt senden“. Vorgabe: täglich 7 Uhr an, wöchentlich aus. Tests: **520 Feature-Tests / 2725 Assertions grün**, Pint. Seite nicht im Browser angesehen. + **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`):** diff --git a/resources/views/mail/channel-conflict.blade.php b/resources/views/mail/channel-conflict.blade.php index 972bab5..e13e9c8 100644 --- a/resources/views/mail/channel-conflict.blade.php +++ b/resources/views/mail/channel-conflict.blade.php @@ -1,15 +1,29 @@ -# Mögliche Doppelbuchung +# {{ $conflicts === [] ? 'Noch offen: mögliche Doppelbuchung' : 'Mögliche Doppelbuchung' }} -Beim Kalender-Abgleich mit **{{ $channel->name }}** wurde eine neue Belegung gefunden, die sich mit einer bestehenden Belegung überschneidet: +@if ($conflicts !== []) +Beim Kalender-Abgleich mit **{{ $channel->name }}** wurde eine Belegung gefunden, die sich mit einer bestehenden Belegung überschneidet: @foreach ($conflicts as $conflict) - {{ $conflict }} @endforeach +@endif +@if ($reminders !== []) +@if ($conflicts === []) +Diese Überschneidung mit **{{ $channel->name }}** besteht weiterhin und ist im Postfach noch ungelesen: +@else +Weiterhin offen und im Postfach noch ungelesen: +@endif + +@foreach ($reminders as $reminder) +- {{ $reminder }} +@endforeach + +@endif 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. -Diese Meldung steht auch im Postfach der Verwaltung. Sie kommt nur einmal, auch wenn die Überschneidung bei weiteren Abgleichen bestehen bleibt. +Die Meldung steht auch im Postfach der Verwaltung. Solange sie dort ungelesen ist und die Überschneidung besteht, erinnern wir im eingestellten Abstand daran (System › Betrieb › Benachrichtigungen). Postfach öffnen diff --git a/resources/views/mail/digest.blade.php b/resources/views/mail/digest.blade.php new file mode 100644 index 0000000..015e71e --- /dev/null +++ b/resources/views/mail/digest.blade.php @@ -0,0 +1,23 @@ + +# {{ $weekly ? 'Ihre Wochenübersicht' : 'Ihre Tagesübersicht' }} + +@if ($sections === []) +Es steht nichts an: keine offenen Anfragen, Meldungen oder Aufgaben. +@endif +@foreach ($sections as $section) +## {{ $section['title'] }} + +@foreach ($section['items'] as $item) +- {!! $item !!} +@endforeach +@if ($section['more'] > 0) +- … und {{ $section['more'] }} weitere +@endif + +[{{ $section['link'] }}]({{ $section['url'] }}) + +@endforeach +--- + +Was in dieser Übersicht steht und wann sie kommt, stellen Sie in der Verwaltung unter System › Betrieb › Benachrichtigungen ein. + diff --git a/routes/console.php b/routes/console.php index 922b268..7134df0 100644 --- a/routes/console.php +++ b/routes/console.php @@ -5,6 +5,8 @@ use App\Actions\RemindChannelTasks; use App\Actions\RequestReviews; use App\Actions\SendBookingReminders; +use App\Actions\SendDigests; +use App\Models\Tenant; use App\Tenancy\TenantRunner; use Illuminate\Support\Facades\Schedule; @@ -28,6 +30,11 @@ ->everyFifteenMinutes() ->withoutOverlapping(); +Schedule::call(fn (TenantRunner $runner, SendDigests $sendDigests) => $runner->each(fn (Tenant $tenant) => $sendDigests->handle($tenant))) + ->name('digests:send') + ->everyFifteenMinutes() + ->withoutOverlapping(); + Schedule::call(fn (TenantRunner $runner, SendBookingReminders $sendBookingReminders) => $runner->each(fn () => $sendBookingReminders->handle())) ->name('bookings:reminders') ->dailyAt('09:00') diff --git a/tests/Feature/ChannelSyncTest.php b/tests/Feature/ChannelSyncTest.php index 6f25a18..6a296fb 100644 --- a/tests/Feature/ChannelSyncTest.php +++ b/tests/Feature/ChannelSyncTest.php @@ -25,6 +25,7 @@ use App\Models\InboxMessage; use App\Models\Property; use App\Models\User; +use App\Tenancy\TenantContext; use Carbon\CarbonImmutable; use Database\Seeders\PropertySeeder; use Filament\Actions\CreateAction; @@ -149,6 +150,48 @@ public function test_a_lasting_double_booking_is_reported_once_however_often_the $this->assertSame(2, InboxMessage::count()); } + public function test_an_unread_double_booking_is_repeated_after_the_chosen_interval_until_it_is_read(): void + { + $this->property->tenant->update(['reminder_interval_days' => 3]); + 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']]); + (new SyncChannel)->handle($channel); + + $this->travel(2)->days(); + (new SyncChannel)->handle($channel); + Mail::assertSentCount(1); + + $this->travel(1)->days(); + (new SyncChannel)->handle($channel); + (new SyncChannel)->handle($channel); + Mail::assertSentCount(2); + Mail::assertSent(ChannelConflict::class, fn (ChannelConflict $mail): bool => $mail->conflicts === [] && count($mail->reminders) === 1 + && str_starts_with($mail->envelope()->subject, 'Erinnerung')); + + InboxMessage::sole()->update(['read_at' => now()]); + $this->travel(4)->days(); + (new SyncChannel)->handle($channel); + Mail::assertSentCount(2); + } + + public function test_open_portal_tasks_are_repeated_after_the_chosen_interval(): void + { + config(['fewo.channels.task_reminder_after_minutes' => 30]); + $this->property->tenant->update(['reminder_interval_days' => 1]); + app(TenantContext::class)->set($this->property->tenant); + ChannelTask::factory()->for($this->channel('Ostseeklar', manual: true))->create(['created_at' => now()->subHour()]); + + $this->assertSame(1, app(RemindChannelTasks::class)->handle()); + $this->assertSame(0, app(RemindChannelTasks::class)->handle()); + $this->travel(1)->days(); + $this->assertSame(1, app(RemindChannelTasks::class)->handle()); + + $this->property->tenant->update(['reminder_interval_days' => 0]); + $this->travel(5)->days(); + $this->assertSame(0, app(RemindChannelTasks::class)->handle()); + } + public function test_failed_import_is_logged_and_alerted_once_until_it_works_again(): void { $channel = $this->channel('Ostseeklar'); diff --git a/tests/Feature/DigestTest.php b/tests/Feature/DigestTest.php new file mode 100644 index 0000000..bb76a74 --- /dev/null +++ b/tests/Feature/DigestTest.php @@ -0,0 +1,156 @@ + null]); + $this->travelTo(CarbonImmutable::parse('2026-11-02 06:30')); + $this->tenant = Tenant::factory()->create(['notification_emails' => 'vermieterin@example.com']); + app(TenantContext::class)->set($this->tenant); + app(TenantConfig::class)->refresh(); + $this->property = Property::factory()->create(); + Mail::fake(); + } + + public function test_daily_summary_goes_out_once_from_the_chosen_hour(): void + { + $this->openRequest(); + $digests = app(SendDigests::class); + + $this->assertNull($digests->handle($this->tenant)); + $this->travelTo(CarbonImmutable::parse('2026-11-02 07:00')); + $this->assertSame('daily', $digests->handle($this->tenant->fresh())); + $this->assertNull($digests->handle($this->tenant->fresh())); + + Mail::assertSent(Digest::class, 1); + Mail::assertSent(Digest::class, fn (Digest $mail): bool => $mail->hasTo('vermieterin@example.com') && ! $mail->weekly + && str_starts_with($mail->envelope()->subject, 'Tagesübersicht 02.11.2026: 2 Punkte')); + } + + public function test_on_the_weekly_day_only_the_weekly_summary_goes_out(): void + { + $this->openRequest(); + $this->tenant->update(['digest_weekly' => true, 'digest_weekday' => 1, 'digest_hour' => 6]); + + $this->assertSame('weekly', app(SendDigests::class)->handle($this->tenant)); + $this->assertNull(app(SendDigests::class)->handle($this->tenant->fresh())); + Mail::assertSent(Digest::class, fn (Digest $mail): bool => $mail->weekly && str_starts_with($mail->envelope()->subject, 'Wochenübersicht KW 45')); + Mail::assertSent(Digest::class, 1); + + $this->travel(1)->days(); + $this->assertSame('daily', app(SendDigests::class)->handle($this->tenant->fresh())); + } + + public function test_nothing_to_report_sends_nothing_unless_wanted(): void + { + $this->tenant->update(['digest_hour' => 6]); + + $this->assertSame('daily', app(SendDigests::class)->handle($this->tenant)); + Mail::assertNothingSent(); + + $this->tenant->update(['digest_when_empty' => true, 'digest_daily_sent_on' => null]); + app(SendDigests::class)->handle($this->tenant->fresh()); + Mail::assertSent(Digest::class, fn (Digest $mail): bool => $mail->sections === [] && str_ends_with($mail->envelope()->subject, 'nichts Neues')); + } + + public function test_summary_lists_requests_stays_payments_and_inbox_and_only_the_chosen_sections(): void + { + $this->openRequest(); + $this->booking(['arrival' => '2026-11-03', 'departure' => '2026-11-07'], 'Erika Mustermann'); + $this->booking(['arrival' => '2026-12-01', 'departure' => '2026-12-05', 'balance_due_on' => '2026-10-20', 'created_at' => now()->subWeek()], 'Hans Säumig'); + InboxMessage::factory()->create(['subject' => 'Mögliche Doppelbuchung über FeWo-direkt', 'body' => 'Ostsee']); + + app(SendDigests::class)->send($this->tenant, weekly: false); + + Mail::assertSent(Digest::class, function (Digest $mail): bool { + $html = $mail->render(); + $titles = array_column($mail->sections, 'title'); + + return in_array('Offene Anfragen und Angebote', $titles, true) + && in_array('An- und Abreisen heute und morgen', $titles, true) + && in_array('Überfällige Zahlungen', $titles, true) + && str_contains($html, 'Morgen: Anreise') + && str_contains($html, 'Erika Mustermann') + && str_contains($html, 'Hans Säumig') + && str_contains($html, 'Frist bis') + && str_contains($html, '<b>Ostsee</b>') + && ! str_contains($html, 'Ostsee'); + }); + + Mail::fake(); + $this->tenant->update(['digest_sections' => [DigestSection::Inbox->value]]); + app(SendDigests::class)->send($this->tenant->fresh(), weekly: false); + Mail::assertSent(Digest::class, fn (Digest $mail): bool => array_column($mail->sections, 'section') === [DigestSection::Inbox]); + } + + public function test_settings_are_saved_on_the_operations_page_and_a_summary_can_be_sent_right_away(): void + { + $this->actingAs(User::factory()->create()); + + Livewire::test(Operations::class) + ->assertSet('data.reminder_interval_days', 0) + ->assertSet('data.digest_daily', true) + ->set('data.reminder_interval_days', 3) + ->set('data.digest_weekly', true) + ->set('data.digest_weekday', 5) + ->set('data.digest_hour', 18) + ->set('data.digest_sections', [DigestSection::Inbox->value, DigestSection::Portals->value]) + ->call('save') + ->assertHasNoErrors() + ->callAction('sendDigest', ['weekly' => 1]); + + $tenant = $this->tenant->fresh(); + $this->assertSame([3, true, 5, 18], [$tenant->reminder_interval_days, $tenant->digest_weekly, $tenant->digest_weekday, $tenant->digest_hour]); + $this->assertSame(['inbox', 'portals'], $tenant->digest_sections); + Mail::assertSent(Digest::class, fn (Digest $mail): bool => $mail->weekly); + } + + private function openRequest(): Booking + { + return Booking::factory()->for($this->property)->reserved()->create(['guest_id' => Guest::factory()->create(['first_name' => 'Anna', 'last_name' => 'Anfrage'])->id]); + } + + /** + * @param array $attributes + */ + private function booking(array $attributes, string $name): Booking + { + [$first, $last] = explode(' ', $name); + + return Booking::factory()->for($this->property)->create([ + 'status' => BookingStatus::Confirmed, + 'guest_id' => Guest::factory()->create(['first_name' => $first, 'last_name' => $last])->id, + ...$attributes, + ]); + } +}