import "server-only"; import type { PoolClient } from "pg"; import { getTranslations } from "next-intl/server"; import { loadInstance } from "@/lib/auth/webauthn"; import { withAuth, withHousehold } from "@/lib/db"; import { isLocale } from "@/lib/locale"; import { loadMail, roundMail, sendMail, type Mail } from "@/lib/mail"; import { planSlots } from "@/lib/plan"; import { dueMails, timeLeft, type RoundMailKind } from "@/lib/round-mail-due"; import { mac } from "@/lib/vault"; // Mails zur Runde (Kai, 9.11.2026, 26.11.53, E-0019): Einladung, Erinnerung 24 h // und 2 h vor der Frist (nur an wer noch nichts gewünscht hat), „Der Plan steht“. // Fällig nach lib/round-mail-due.ts; der Zeitstempel wird vor dem Versand gesetzt, // damit keine Mail doppelt rausgeht — lieber eine zu wenig als zwei. const ZONE = "Europe/Berlin"; export type Recipient = { id: string; name: string; locale: string | null; address: string; wished: boolean }; /** Wer Mails zur Runde bekommt: bestätigte Adresse (eigens eingetragen, sonst die zum Anmelden), nicht abgemeldet, keine Gäste. */ export async function recipients(client: PoolClient, roundId: string): Promise { const { rows } = await client.query( `select m.id, m.display_name as name, m.locale, case when m.notify_verified_at is not null then m.notify_email else m.email end as address, exists (select 1 from wishes w where w.round_id = $1 and w.member_id = m.id) as wished from members m where m.role <> 'guest' and not m.notify_off and ((m.notify_verified_at is not null and m.notify_email is not null) or (m.email_verified_at is not null and m.email is not null)) order by m.display_name`, [roundId], ); return rows; } /** Abmelde-Link: gilt dauerhaft, speichert nichts (HMAC mit dem Tresor-Schlüssel). */ export async function unsubscribeUrl(origin: string, memberId: string): Promise { return `${origin}/mail/abmelden#${memberId}.${await mac(`unsubscribe:${memberId}`)}`; } type Context = { origin: string; household: { name: string; tokens: number }; round: { id: string; shoppingDate: string | null; deadline: Date | null; slotsCount: number }; teasers: string[]; plan: { title: string; day: string | null; cook: string | null }[]; }; async function compose(kind: RoundMailKind, to: Recipient, ctx: Context, now: Date): Promise { const locale = isLocale(to.locale) ? to.locale : "de"; const t = await getTranslations({ locale, namespace: "roundMail" }); const when = (d: Date) => new Intl.DateTimeFormat(locale, { timeZone: ZONE, weekday: "long", day: "numeric", month: "long", hour: "2-digit", minute: "2-digit" }).format(d); const day = (iso: string) => new Intl.DateTimeFormat(locale, { timeZone: ZONE, weekday: "short", day: "numeric", month: "short" }).format(new Date(`${iso}T12:00:00Z`)); const left = ctx.round.deadline ? timeLeft(ctx.round.deadline, now) : null; const box = ctx.round.deadline && left ? { big: t("left", { days: left.days, hours: left.hours, minutes: left.minutes }), small: t("until", { when: when(ctx.round.deadline) }) } : null; const unsubscribe = { label: t("unsubscribe"), url: await unsubscribeUrl(ctx.origin, to.id) }; const footer = t("footer", { household: ctx.household.name }); const shopping = ctx.round.shoppingDate ? day(ctx.round.shoppingDate) : null; if (kind === "plan") { return roundMail({ to: to.address, subject: t("plan.subject"), preheader: t("plan.preheader", { n: ctx.plan.length }), eyebrow: ctx.household.name, title: t("plan.title", { name: to.name }), lead: shopping ? t("plan.leadShopping", { day: shopping }) : t("plan.lead"), listTitle: t("plan.listTitle"), list: ctx.plan.map((s) => ({ title: s.title, meta: [s.day ? day(s.day) : null, s.cook ? t("plan.cook", { name: s.cook }) : null].filter(Boolean).join(" · ") })), button: t("plan.button"), url: `${ctx.origin}/`, footer, unsubscribe, }); } const points = [ t("points.tokens", { n: ctx.household.tokens }), t("points.mine"), ...(shopping ? [t("points.shopping", { day: shopping, n: ctx.round.slotsCount })] : []), ]; return roundMail({ to: to.address, subject: t(`${kind}.subject`), preheader: t(`${kind}.preheader`), eyebrow: ctx.household.name, title: t(`${kind}.title`, { name: to.name }), lead: t(`${kind}.lead`), box, points: kind === "invite" ? points : undefined, listTitle: t("teaserTitle"), list: kind === "invite" ? ctx.teasers.map((title) => ({ title, meta: "" })) : undefined, button: t("button"), url: `${ctx.origin}/wuenschen`, footer, unsubscribe, }); } const COLUMN: Record = { invite: "invite_sent_at", remind24: "remind24_sent_at", remind2: "remind2_sent_at", plan: "plan_mail_sent_at", }; /** Fällige Mails eines Haushalts verschicken. Gibt zurück, was verschickt wurde (für Tests und Log). */ export async function sendRoundMails(householdId: string, now = new Date()): Promise<{ kind: RoundMailKind; to: string[] }[]> { const origin = (await withAuth(loadInstance))?.origin; if (!origin) return []; const work = await withHousehold(householdId, async (c) => { if (!(await loadMail(c))?.passwordEnc) return null; // kein Mailweg: nichts tun, nichts als erledigt markieren const round = ( await c.query( `select id, status, to_char(shopping_date, 'YYYY-MM-DD') as "shoppingDate", slots_count as "slotsCount", wish_deadline as "wishDeadline", invite_sent_at as "inviteSentAt", remind24_sent_at as "remind24SentAt", remind2_sent_at as "remind2SentAt", plan_mail_sent_at as "planMailSentAt" from rounds where status <> 'done' order by created_at desc limit 1 for update`, ) ).rows[0]; if (!round) return null; const { send, skip } = dueMails(round, now); for (const kind of [...send, ...skip]) await c.query(`update rounds set ${COLUMN[kind]} = $2 where id = $1`, [round.id, now]); if (!send.length) return null; const people = await recipients(c, round.id); const household = (await c.query("select name, tokens_per_round as tokens from households")).rows[0]; const teasers = (await c.query("select title from dishes where archived_at is null and not is_trial order by random() limit 3")).rows.map((r) => r.title as string); const plan = send.includes("plan") ? (await planSlots(c, round.id)).filter((s) => s.title).map((s) => ({ title: s.title!, day: s.plannedDay, cook: s.cookName })) : []; return { send, people, ctx: { origin, household, round: { id: round.id, shoppingDate: round.shoppingDate, deadline: round.wishDeadline, slotsCount: round.slotsCount }, teasers, plan } }; }); if (!work) return []; const done: { kind: RoundMailKind; to: string[] }[] = []; for (const kind of work.send) { // Erinnerungen nur an wer noch nichts gewünscht hat. const to = kind === "remind24" || kind === "remind2" ? work.people.filter((p) => !p.wished) : work.people; for (const person of to) { try { await sendMail(householdId, await compose(kind, person, work.ctx, now)); } catch (error) { console.error(`round mail ${kind} failed:`, (error as Error).message); } } done.push({ kind, to: to.map((p) => p.address) }); } return done; } /** Alle Haushalte durchgehen (für den Takt im Hintergrund). */ export async function sendAllRoundMails(now = new Date()): Promise { const ids = await withAuth(async (c) => (await c.query("select id from households")).rows.map((r) => r.id as string)); for (const id of ids) { try { await sendRoundMails(id, now); } catch (error) { console.error("round mails failed:", (error as Error).message); } } } /** Nach Eröffnen oder Freigeben: gleich schauen, statt auf den nächsten Takt zu warten. */ export function sendRoundMailsSoon(householdId: string): void { void sendRoundMails(householdId).catch((error) => console.error("round mails failed:", (error as Error).message)); }