add('news', 'Neuigkeiten', 10, fn (User $user, CarbonImmutable $since) => [ * ['title' => '…', 'url' => '…', 'meta' => '…', 'text' => '…'], … * ]); * * Es gilt, was die Person im Portal sieht. Leere Abschnitte fallen weg; ist alles leer, * geht keine E-Mail raus. */ class Digest { public const WEEKDAYS = [1 => 'Montag', 2 => 'Dienstag', 3 => 'Mittwoch', 4 => 'Donnerstag', 5 => 'Freitag', 6 => 'Samstag', 7 => 'Sonntag']; /** @var array */ private array $sections = []; public function __construct(private readonly Settings $settings) {} public function add(string $key, string $label, int $sort, callable $items): void { $this->sections[$key] = ['label' => $label, 'sort' => $sort, 'items' => $items]; } public function enabled(): bool { return (bool) $this->settings->get('digest.enabled', true); } public function weekday(): int { return (int) $this->settings->get('digest.weekday', 1); } public function hour(): int { return (int) $this->settings->get('digest.hour', 7); } /** „montags ab 7 Uhr“ */ public function scheduleLabel(): string { return mb_strtolower(self::WEEKDAYS[$this->weekday()]).'s ab '.$this->hour().' Uhr'; } /** * @return list>}> */ public function build(User $user, CarbonImmutable $since): array { $access = app(PluginAccess::class); return collect($this->sections) ->filter(fn ($section, $key) => $access->allows($key.'.digest', $user)) ->sortBy('sort') ->map(function (array $section, string $key) use ($user, $since) { try { $items = array_values(($section['items'])($user, $since)); } catch (Throwable $e) { report($e); $items = []; } return ['key' => $key, 'label' => $section['label'], 'items' => $items]; }) ->filter(fn (array $section) => $section['items'] !== []) ->values()->all(); } /** * Stündlich aufgerufen: am eingestellten Tag ab der eingestellten Stunde an alle, * die ihn eingeschaltet haben – je Person höchstens einmal in sechs Tagen. */ public function sendDue(): int { $now = CarbonImmutable::now(config('app.timezone')); if (! $this->enabled() || $now->dayOfWeekIso !== $this->weekday() || $now->hour < $this->hour()) { return 0; } $sent = 0; User::query()->active()->where('weekly_digest', true)->whereNotNull('email') ->where(fn ($q) => $q->whereNull('digest_sent_at')->orWhere('digest_sent_at', '<', $now->subDays(6))) ->chunkById(100, function ($users) use ($now, &$sent) { foreach ($users as $user) { $user->forceFill(['digest_sent_at' => $now])->saveQuietly(); $sent += $this->sendTo($user, $now->subDays(7)) ? 1 : 0; } }); return $sent; } public function sendTo(User $user, CarbonImmutable $since): bool { $sections = $this->build($user, $since); if ($sections === []) { return false; } Mail::to($user)->queue(new WeeklyDigest($user, $sections, $since)); return true; } }