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 <noreply@anthropic.com>
This commit is contained in:
1 parent
70a39315e2
commit
1c757f7429
20 files changed
+842
-22
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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<string, CarbonInterface> $conflicts description => first night of the portal occupation
|
||||
* @return list<string> the conflicts reported for the first time
|
||||
* @return list<string> 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];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Enums\DigestSection;
|
||||
use App\Mail\Digest;
|
||||
use App\Models\Tenant;
|
||||
use App\Support\DigestReport;
|
||||
use App\Support\Settings;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Support\Facades\Mail;
|
||||
|
||||
/**
|
||||
* Sends the landlord's daily and/or weekly summary once the chosen hour has come (System › Betrieb ›
|
||||
* Benachrichtigungen). On the weekly day only the weekly summary goes out, never both. Runs per landlord
|
||||
* from the scheduler; the sent dates on the landlord make every summary go out at most once a day.
|
||||
*/
|
||||
class SendDigests
|
||||
{
|
||||
public function __construct(private DigestReport $report) {}
|
||||
|
||||
/**
|
||||
* @return 'daily'|'weekly'|null which summary was due (also when it was skipped for being empty)
|
||||
*/
|
||||
public function handle(Tenant $tenant): ?string
|
||||
{
|
||||
$now = CarbonImmutable::now();
|
||||
$today = $now->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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
namespace App\Enums;
|
||||
|
||||
use Filament\Support\Contracts\HasDescription;
|
||||
use Filament\Support\Contracts\HasLabel;
|
||||
|
||||
/**
|
||||
* The parts of the daily/weekly summary a landlord can choose (System › Betrieb › Benachrichtigungen).
|
||||
*/
|
||||
enum DigestSection: string implements HasDescription, HasLabel
|
||||
{
|
||||
case Inbox = 'inbox';
|
||||
case Requests = 'requests';
|
||||
case News = 'news';
|
||||
case Stays = 'stays';
|
||||
case Payments = 'payments';
|
||||
case Portals = 'portals';
|
||||
case Reviews = 'reviews';
|
||||
|
||||
public function getLabel(): string
|
||||
{
|
||||
return match ($this) {
|
||||
self::Inbox => '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<string>|null $values stored choice; null = everything
|
||||
* @return list<self>
|
||||
*/
|
||||
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)));
|
||||
}
|
||||
}
|
||||
@@ -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)),
|
||||
]);
|
||||
|
||||
|
||||
@@ -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<string> $conflicts */
|
||||
public function __construct(public Channel $channel, public array $conflicts) {}
|
||||
/**
|
||||
* @param list<string> $conflicts reported for the first time
|
||||
* @param list<string> $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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
|
||||
namespace App\Mail;
|
||||
|
||||
use App\Enums\DigestSection;
|
||||
use Illuminate\Bus\Queueable;
|
||||
use Illuminate\Mail\Mailable;
|
||||
use Illuminate\Mail\Mailables\Content;
|
||||
use Illuminate\Mail\Mailables\Envelope;
|
||||
use Illuminate\Queue\SerializesModels;
|
||||
|
||||
/**
|
||||
* The landlord's daily or weekly summary of open points and news (SendDigests, DigestReport).
|
||||
*/
|
||||
class Digest extends Mailable
|
||||
{
|
||||
use Queueable, SerializesModels;
|
||||
|
||||
/**
|
||||
* @param list<array{section: DigestSection, title: string, items: list<string>, 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',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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<InboxMessageFactory> */
|
||||
@@ -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',
|
||||
];
|
||||
}
|
||||
|
||||
@@ -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<TenantFactory> */
|
||||
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',
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
<?php
|
||||
|
||||
namespace App\Support;
|
||||
|
||||
use App\Enums\BookingStatus;
|
||||
use App\Enums\DigestSection;
|
||||
use App\Enums\PortalEmailStatus;
|
||||
use App\Enums\ReviewStatus;
|
||||
use App\Filament\Pages\OccupancyCalendar;
|
||||
use App\Filament\Resources\Bookings\BookingResource;
|
||||
use App\Filament\Resources\ChannelTasks\ChannelTaskResource;
|
||||
use App\Filament\Resources\InboxMessages\InboxMessageResource;
|
||||
use App\Filament\Resources\PortalOccupations\PortalOccupationResource;
|
||||
use App\Filament\Resources\Reviews\ReviewResource;
|
||||
use App\Models\BlockedPeriod;
|
||||
use App\Models\Booking;
|
||||
use App\Models\Channel;
|
||||
use App\Models\ChannelTask;
|
||||
use App\Models\InboxMessage;
|
||||
use App\Models\PortalEmail;
|
||||
use App\Models\Property;
|
||||
use App\Models\Review;
|
||||
use Carbon\CarbonImmutable;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Collection;
|
||||
|
||||
/**
|
||||
* Collects what the landlord should know for the daily or weekly summary (SendDigests). Each section lists
|
||||
* at most MAX_ITEMS lines and says how many more there are; empty sections are left out. Lines are Markdown
|
||||
* with HTML-escaped data, so the mail renders them unescaped.
|
||||
*/
|
||||
class DigestReport
|
||||
{
|
||||
public const MAX_ITEMS = 10;
|
||||
|
||||
private bool $namesProperty = false;
|
||||
|
||||
/**
|
||||
* @param list<DigestSection> $sections
|
||||
* @return list<array{section: DigestSection, title: string, items: list<string>, 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<int, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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<string, string> $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<int, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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<int, string>
|
||||
*/
|
||||
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.'),
|
||||
};
|
||||
}
|
||||
}
|
||||
+24
-4
@@ -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)));
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user