Files
fewo-stommer/app/Support/DigestReport.php
T
LarsandClaude Opus 5.5 1c757f7429 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>
2026-10-30 10:11:15 +01:00

219 lines
11 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?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.'),
};
}
}