Compare commits

..
2 Commits
Author SHA1 Message Date
kai 8d88e90a07 26.11.53: Mails zur Runde (#55)
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m2s
release / tag and release (push) Successful in 2s
2026-11-09 07:38:56 +00:00
kai 60ab3129ca Doku: Resend und Kalender-Abo in Betrieb (#54) 2026-11-09 07:20:54 +00:00
44 changed files with 1594 additions and 73 deletions

No files matched your search

+1 -1
View File
@@ -158,7 +158,7 @@ jobs:
mkdir -p "$RUNNER_TEMP/lunchdaten"
echo "LUNCH_DATA=$RUNNER_TEMP/lunchdaten" >> "$GITHUB_ENV"
# HOSTNAME: Next bindet sich daran; im Container ist es die Kennung des Containers.
(cd .next/standalone && HOSTNAME=0.0.0.0 PORT=3020 BACKUP_DISABLED=1 IMPORT_TEST_ORIGIN=http://127.0.0.1:3021 APP_DATA_DIR="$RUNNER_TEMP/lunchdaten" MAIL_TEST_DIR="$RUNNER_TEMP/lunchdaten/mails" \
(cd .next/standalone && HOSTNAME=0.0.0.0 PORT=3020 BACKUP_DISABLED=1 ROUND_MAIL_EVERY_MS=2000 IMPORT_TEST_ORIGIN=http://127.0.0.1:3021 APP_DATA_DIR="$RUNNER_TEMP/lunchdaten" MAIL_TEST_DIR="$RUNNER_TEMP/lunchdaten/mails" \
nohup node server.js > "$RUNNER_TEMP/server.log" 2>&1 &)
for i in $(seq 30); do curl -sf localhost:3020/api/ready && exit 0; sleep 1; done
cat "$RUNNER_TEMP/server.log"; exit 1
+4 -4
View File
@@ -7,7 +7,7 @@
> **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase,
> kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002).
> Verteilung über den Markt, Repo öffentlich (E-0005).
> **Status:** 26.11.52 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> **Status:** 26.11.53 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
> Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den
> Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit
> Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel
@@ -22,9 +22,9 @@
> (26.11.39, E-0016), Anmelden per Mail-Link über Resend (26.11.40, E-0017; nur
> anmelden, keine Geräte oder Passkeys aus einer Mail-Sitzung), Leiste bleibt nach der
> Tastatur unten (26.11.41), Icon Kochmütze mit Herz (26.11.42), Fotos aus der Mediathek (26.11.43), gleich große Karten (26.11.44), Runde beenden/löschen/ändern,
> Tage je Gericht von Hand und Kalender-Abo je Haushalt (26.11.45, E-0018), Einkaufsliste einsprechen (26.11.46), Herz für „Mein Gericht“ auf jeder Wunschkarte (26.11.47), Kochbuch mit bis zu sechs Seiten (26.11.48), Portionen rechnen beim Bearbeiten mit und mehr Maße (26.11.49), ml und l bei jeder Zutat (26.11.50), Fehlendes im Formular am Feld markiert und gezählt (26.11.51), Desktop zeigt die Handy-Spalte (26.11.52). Offen: Kai trägt
> den Resend-Schlüssel unter Mehr › Mails verschicken ein und abonniert den Kalender-Link einmal auf dem iPhone.
> **Letzte Aktualisierung:** 8. November 2026
> Tage je Gericht von Hand und Kalender-Abo je Haushalt (26.11.45, E-0018), Einkaufsliste einsprechen (26.11.46), Herz für „Mein Gericht“ auf jeder Wunschkarte (26.11.47), Kochbuch mit bis zu sechs Seiten (26.11.48), Portionen rechnen beim Bearbeiten mit und mehr Maße (26.11.49), ml und l bei jeder Zutat (26.11.50), Fehlendes im Formular am Feld markiert und gezählt (26.11.51), Desktop zeigt die Handy-Spalte (26.11.52), Mails zur Runde mit Frist, Countdown und Erinnerungen (26.11.53, E-0019). Mailweg über Resend
> auf der Box eingerichtet, Testmail angekommen; Kalender-Abo auf dem iPhone läuft (beides 9.11.2026).
> **Letzte Aktualisierung:** 9. November 2026
Diese Datei ist das Gedächtnis jeder Sitzung. Entscheidungen stehen in
`docs/entscheidungen.md` und gelten vor dem Konzept. Bei Unsicherheit: stoppen
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: foodplanhero
description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.52
version: 26.11.53
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.52'
versionName: '26.11.53'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+22 -2
View File
@@ -33,7 +33,7 @@ export default async function MorePage() {
const t = await getTranslations("more");
const tc = await getTranslations("costs.settings");
const locale = await getLocale();
const { members, passkeys, founder, kids, kidDevices, money, mail, calendar, dedication } = await withHousehold(session.householdId, async (client) => {
const { members, passkeys, founder, kids, kidDevices, money, mail, calendar, notifyCount, dedication } = await withHousehold(session.householdId, async (client) => {
const members = (await client.query("select id, display_name, role from members order by created_at")).rows;
const founder = (await client.query("select created_by from households")).rows[0]?.created_by as string | null;
const passkeys = (
@@ -62,7 +62,12 @@ export default async function MorePage() {
const calendar = (
await client.query("select calendar_token_hash is not null as active, to_char(meal_time, 'HH24:MI') as time, meal_minutes as minutes from households")
).rows[0] as { active: boolean; time: string; minutes: number };
return { members, passkeys, founder, kids, kidDevices, money, mail, calendar, dedication: await getDedication(client) };
const notifyCount = (
await client.query(
"select count(*)::int as n from members where role <> 'guest' and not notify_off and (notify_verified_at is not null or email_verified_at is not null)",
)
).rows[0].n as number;
return { members, passkeys, founder, kids, kidDevices, money, mail, calendar, notifyCount, dedication: await getDedication(client) };
});
const aiReady = !!(await aiFor(session.householdId));
const date = new Intl.DateTimeFormat(locale, { dateStyle: "medium" });
@@ -165,6 +170,21 @@ export default async function MorePage() {
</Section>
) : null}
{session.role === "admin" ? (
<Section title={t("roundMails.title")} id="runden-mails">
<Link
href="/mehr/runden-mails"
className="flex min-h-11 items-center justify-between gap-2 rounded-2xl bg-muted px-4 py-3 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
>
<span className="flex flex-col">
<span>{t("roundMails.count", { n: notifyCount })}</span>
<span className="text-sm text-muted-foreground">{t("roundMails.summary")}</span>
</span>
<ChevronRight aria-hidden className="size-5 text-muted-foreground" />
</Link>
</Section>
) : null}
{session.role === "admin" ? (
<Section title={t("ai.title")}>
<Link
+41
View File
@@ -0,0 +1,41 @@
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { NotifyAdmin, type NotifyMember } from "@/components/more/notify-admin";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { loadMail } from "@/lib/mail";
export const dynamic = "force-dynamic";
// Mails zur Runde (Kai, 9.11.2026, 26.11.53): Der Admin trägt für jede Person eine
// Adresse ein, auch für Kinder; bestätigt wird über einen Link an die Adresse.
export default async function RoundMailsPage() {
const session = await requireSession();
if (session.role !== "admin") redirect("/mehr");
const t = await getTranslations("more.roundMails");
const { members, ready } = await withHousehold(session.householdId, async (c) => ({
ready: !!(await loadMail(c))?.passwordEnc,
members: (
await c.query(
`select id, display_name as name, role, notify_email as "notifyEmail", notify_verified_at is not null as "notifyVerified",
notify_off as off, case when email_verified_at is not null then email end as "loginEmail"
from members where role <> 'guest' order by display_name`,
)
).rows as NotifyMember[],
}));
return (
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
<header className="flex flex-col gap-1">
<p className="eyebrow">{session.householdName}</p>
<h1 className="text-4xl leading-tight">{t("title")}</h1>
<p className="text-muted-foreground">{t("intro")}</p>
</header>
{!ready ? <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("notReady")}</p> : null}
{session.via === "mail" ? (
<p className="rounded-xl border border-border px-4 py-3 text-sm">{(await getTranslations("auth.errors"))("mailSession")}</p>
) : (
<NotifyAdmin members={members} />
)}
</main>
);
}
+2
View File
@@ -8,6 +8,7 @@ import { RateCard } from "@/components/cooking/rate-card";
import { InstallHint } from "@/components/install-hint";
import { pendingRatings, thanksForCook } from "@/lib/cooking";
import Link from "next/link";
import { Countdown } from "@/components/wishes/countdown";
import { getLocale, getTranslations } from "next-intl/server";
import { DishPhoto } from "@/components/dishes/dish-tile";
import { buttonVariants } from "@/components/ui/button";
@@ -94,6 +95,7 @@ export default async function TodayPage() {
{!guide.seenIntro && checklist === "none" ? <IntroCards simple={session.role === "child"} /> : null}
{checklist !== "none" ? <SetupChecklist steps={steps} finished={checklist === "finished"} /> : null}
{checklist !== "show" ? <RoundStepper stage={stageNow} next={next} simple={session.role === "child"} /> : null}
{data.round?.status === "open" && data.round.wishDeadline ? <Countdown deadline={data.round.wishDeadline} /> : null}
<div id="bewerten" className="contents" />
{after.toRate.map((r) => (
+1 -1
View File
@@ -55,7 +55,7 @@ export default async function PlanPage() {
<>
<PlanBoard slots={data.slots} members={data.members} dishes={data.dishes} status={data.round!.status} money={data.money!} startDay={data.round!.shoppingDate} />
<RoundActions
current={{ shoppingDate: data.round!.shoppingDate, slotsCount: data.round!.slotsCount, defaultPortions: data.round!.defaultPortions }}
current={{ shoppingDate: data.round!.shoppingDate, slotsCount: data.round!.slotsCount, defaultPortions: data.round!.defaultPortions, wishDeadline: data.round!.wishDeadline }}
canDelete={!data.slots.some((s) => s.cookedAt)}
/>
</>
+5 -2
View File
@@ -1,6 +1,7 @@
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { WishBoard } from "@/components/wishes/wish-board";
import { Countdown } from "@/components/wishes/countdown";
import { buttonVariants } from "@/components/ui/button";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
@@ -16,7 +17,8 @@ export default async function WishPage() {
const adult = session.role === "admin" || session.role === "member";
const data = await withHousehold(session.householdId, async (c) => {
const round = await currentRound(c);
if (!round || round.status !== "open") return { round };
// Nach der Frist ist Wünschen zu (26.11.53): kein Brett mehr, nur der Hinweis.
if (!round || round.status !== "open" || (round.wishDeadline && new Date(round.wishDeadline) <= new Date())) return { round };
return { round, tiles: await wishTiles(c), entries: await roundWishes(c, round.id, { memberId: session.memberId, adult }), budget: await budget(c, round.id, session.memberId) };
});
return (
@@ -25,11 +27,12 @@ export default async function WishPage() {
<p className="eyebrow">{t("eyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("title")}</h1>
</header>
{data.round?.status === "open" && data.round.wishDeadline ? <Countdown deadline={data.round.wishDeadline} /> : null}
{"tiles" in data && data.tiles ? (
<WishBoard tiles={data.tiles} entries={data.entries} me={session.memberId} budget={data.budget} canVeto={session.role !== "child"} />
) : (
<div className="flex flex-col gap-3 rounded-2xl border border-border p-4">
<p>{data.round ? t("closed") : t("noRound")}</p>
<p>{data.round ? (data.round.status === "open" ? t("deadlinePassed") : t("closed")) : t("noRound")}</p>
{!data.round && adult ? (
<Link href="/runde/neu" className={cn(buttonVariants({ size: "lg" }))}>
{t("openRound")}
+72
View File
@@ -0,0 +1,72 @@
import { z } from "zod";
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { createMailToken, linkMail, normalizeEmail } from "@/lib/auth/mail-login";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance } from "@/lib/auth/webauthn";
import { withAuth, withHousehold } from "@/lib/db";
import { MailNotConfigured, sendMail } from "@/lib/mail";
export const dynamic = "force-dynamic";
// Adressen für die Mails zur Runde (Kai, 9.11.2026, 26.11.53): Der Admin trägt sie
// für jede Person ein, auch für Kinder. Erst der Link an die Adresse selbst schaltet
// sie frei — so landet keine Mail bei einer vertippten oder fremden Adresse.
async function admin(request: Request) {
const session = await guardWrite(request, ["admin"]);
if (isResponse(session)) return session;
return noMailSession(session) ?? session;
}
const member = z.string().uuid();
export async function PUT(request: Request) {
const session = await admin(request);
if (isResponse(session)) return session;
const parsed = z.object({ memberId: member, email: z.string().trim().max(200).email() }).safeParse(await readJson(request));
if (!parsed.success) return fail("invalid", 400);
const email = normalizeEmail(parsed.data.email);
const target = await withHousehold(session.householdId, async (c) => {
const row = (await c.query("select id, locale from members where id = $1 and role <> 'guest'", [parsed.data.memberId])).rows[0];
if (!row) return null;
await c.query("update members set notify_email = $2, notify_verified_at = null, notify_off = false where id = $1", [row.id, email]);
return row as { id: string; locale: string | null };
});
if (!target) return fail("notFound", 404);
const prepared = await withAuth(async (client) => {
if (await tooManyAttempts(client, `notify-confirm:${session.householdId}`, 20, 60)) return fail("tooMany", 429);
const token = await createMailToken(client, { householdId: session.householdId, memberId: target.id, purpose: "notify", email });
return { token, locale: target.locale, origin: (await loadInstance(client))!.origin };
});
if (prepared instanceof Response) return prepared;
try {
await sendMail(session.householdId, await linkMail({ purpose: "notify", to: email, ...prepared }));
} catch (error) {
return fail(error instanceof MailNotConfigured ? "mailNotConfigured" : "mailFailed", 502);
}
return json({ pending: email });
}
/** Mails an oder aus (ohne die Adresse zu löschen). */
export async function PATCH(request: Request) {
const session = await admin(request);
if (isResponse(session)) return session;
const parsed = z.object({ memberId: member, off: z.boolean() }).safeParse(await readJson(request));
if (!parsed.success) return fail("invalid", 400);
const { rowCount } = await withHousehold(session.householdId, (c) =>
c.query("update members set notify_off = $2 where id = $1 and role <> 'guest'", [parsed.data.memberId, parsed.data.off]),
);
return rowCount ? json({ ok: true }) : fail("notFound", 404);
}
export async function DELETE(request: Request) {
const session = await admin(request);
if (isResponse(session)) return session;
const parsed = z.object({ memberId: member }).safeParse(await readJson(request));
if (!parsed.success) return fail("invalid", 400);
await withHousehold(session.householdId, async (c) => {
await c.query("update members set notify_email = null, notify_verified_at = null where id = $1", [parsed.data.memberId]);
await c.query("update mail_tokens set used_at = now() where member_id = $1 and purpose = 'notify' and used_at is null", [parsed.data.memberId]);
});
return json({ ok: true });
}
+25
View File
@@ -0,0 +1,25 @@
import { z } from "zod";
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
import { clientIp } from "@/lib/auth/request";
import { tooManyAttempts } from "@/lib/auth/throttle";
import { loadInstance } from "@/lib/auth/webauthn";
import { withAuth } from "@/lib/db";
import { macOk } from "@/lib/vault";
export const dynamic = "force-dynamic";
const body = z.object({ member: z.string().uuid(), mac: z.string().min(20).max(100) });
// „Keine Mails zur Runde mehr“ aus dem Fuß jeder Mail (26.11.53). Ohne Anmeldung —
// der Link trägt eine Prüfsumme über die Person (lib/vault.ts mac), mehr braucht es nicht.
export async function POST(request: Request) {
const parsed = body.safeParse(await readJson(request));
return withAuth(async (client) => {
const instance = await loadInstance(client);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
if (await tooManyAttempts(client, `unsubscribe:${clientIp(request)}`, 20, 15)) return fail("tooMany", 429);
if (!parsed.success || !(await macOk(`unsubscribe:${parsed.data.member}`, parsed.data.mac))) return fail("expired", 410);
await client.query("update members set notify_off = true where id = $1", [parsed.data.member]);
return json({ ok: true });
});
}
+7 -1
View File
@@ -1,12 +1,18 @@
import { fail, json } from "@/lib/auth/http";
import { approve } from "@/lib/plan";
import { withPlan } from "@/lib/plan-route";
import { sendRoundMailsSoon } from "@/lib/round-mails";
import { getSession } from "@/lib/auth/session";
export const dynamic = "force-dynamic";
// Plan freigeben: Die Familie sieht ihn, Wünschen ist für diese Runde vorbei.
export async function POST(request: Request) {
return withPlan(request, ["open"], async (c, round, session) =>
const res = await withPlan(request, ["open"], async (c, round, session) =>
(await approve(c, round, session.memberId)) ? json({ ok: true }) : fail("empty", 409),
);
// „Der Plan steht“ geht gleich raus, nicht erst beim nächsten Takt (26.11.53).
const session = res.ok ? await getSession() : null;
if (session) sendRoundMailsSoon(session.householdId);
return res;
}
+2
View File
@@ -4,6 +4,7 @@ import { withHousehold } from "@/lib/db";
import { getLocale } from "next-intl/server";
import { currentRound, openRound, RoundExists, roundInput, updateRound } from "@/lib/rounds";
import { syncList } from "@/lib/shopping";
import { sendRoundMailsSoon } from "@/lib/round-mails";
export const dynamic = "force-dynamic";
@@ -15,6 +16,7 @@ export async function POST(request: Request) {
if (!body.success) return fail("invalid", 400);
try {
const id = await withHousehold(session.householdId, (c) => openRound(c, session.householdId, session.memberId, body.data));
sendRoundMailsSoon(session.householdId); // Einladung gleich, nicht erst beim nächsten Takt (26.11.53)
return json({ id }, 201);
} catch (error) {
if (error instanceof RoundExists) return fail("roundExists", 409);
+7 -2
View File
@@ -41,6 +41,11 @@ export async function DELETE(request: Request) {
if (isResponse(session)) return session;
const body = z.object({ dishId }).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
const ok = await withHousehold(session.householdId, (c) => removeWish(c, session.memberId, body.data.dishId));
return ok ? json({ ok: true }) : fail("notFound", 404);
try {
const ok = await withHousehold(session.householdId, (c) => removeWish(c, session.memberId, body.data.dishId));
return ok ? json({ ok: true }) : fail("notFound", 404);
} catch (error) {
if (error instanceof WishRefused) return fail(error.reason, 409);
throw error;
}
}
+18
View File
@@ -0,0 +1,18 @@
import { Slogan, Wordmark } from "@/components/brand/brand";
import { Unsubscribe } from "@/components/auth/unsubscribe";
export const dynamic = "force-dynamic";
// „Keine Mails zur Runde mehr“ (26.11.53): Ziel des Links aus dem Fuß jeder Mail.
// Wie der Mail-Link: Erst ein Tipp schickt ihn ab, ein Mail-Scanner meldet niemanden ab.
export default function UnsubscribePage() {
return (
<main className="mx-auto flex min-h-dvh w-full max-w-sm flex-col justify-center gap-6 px-4 py-10">
<p className="flex flex-col items-center gap-2 text-center">
<Wordmark className="text-4xl" />
<Slogan />
</p>
<Unsubscribe />
</main>
);
}
+12 -9
View File
@@ -7,7 +7,8 @@ import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
type State = { kind: "ready"; purpose: "login" | "verify"; token: string } | { kind: "expired" } | { kind: "verified" } | { kind: "loading" };
type Purpose = "login" | "verify" | "notify";
type State = { kind: "ready"; purpose: Purpose; token: string } | { kind: "expired" } | { kind: "verified"; purpose: Purpose } | { kind: "loading" };
// Der Link aus der Mail (26.11.40): Der Token steht hinter # und geht nie an den
// Server, bis die Person tippt — ein Mail-Scanner, der nur abruft, verbraucht ihn nicht.
@@ -19,10 +20,10 @@ export function MailLink() {
const [error, setError] = useState<string | null>(null);
useEffect(() => {
const m = window.location.hash.match(/^#(login|verify)=([A-Za-z0-9_-]{20,100})$/);
const m = window.location.hash.match(/^#(login|verify|notify)=([A-Za-z0-9_-]{20,100})$/);
// Aus der Adresszeile nehmen: kein Token im Verlauf, kein zweites Einlösen beim Neuladen.
history.replaceState(null, "", window.location.pathname);
setState(m ? { kind: "ready", purpose: m[1] as "login" | "verify", token: m[2]! } : { kind: "expired" });
setState(m ? { kind: "ready", purpose: m[1] as Purpose, token: m[2]! } : { kind: "expired" });
}, []);
async function go() {
@@ -38,7 +39,7 @@ export function MailLink() {
if (res?.ok) {
const { purpose } = await res.json();
if (purpose === "login") router.replace("/");
else setState({ kind: "verified" });
else setState({ kind: "verified", purpose });
return;
}
if (res?.status === 410) return setState({ kind: "expired" });
@@ -60,21 +61,23 @@ export function MailLink() {
if (state.kind === "verified") {
return (
<div className="flex flex-col items-center gap-4 text-center">
<h1 className="text-balance text-4xl leading-tight">{t("mailLink.verified")}</h1>
<h1 className="text-balance text-4xl leading-tight">{t(state.purpose === "notify" ? "mailLink.notifyDone" : "mailLink.verified")}</h1>
{state.purpose === "notify" ? <p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t("mailLink.notifyDoneIntro")}</p> : null}
<Button asChild size="lg" className="self-stretch">
<Link href="/mehr">{t("mailLink.toMore")}</Link>
<Link href={state.purpose === "notify" ? "/" : "/mehr"}>{t("mailLink.toMore")}</Link>
</Button>
</div>
);
}
const login = state.purpose === "login";
const key = state.purpose === "notify" ? "notify" : login ? "login" : "verify";
return (
<div className="flex flex-col items-center gap-4 text-center">
<h1 className="text-balance text-4xl leading-tight">{t(login ? "mailLink.loginTitle" : "mailLink.verifyTitle")}</h1>
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t(login ? "mailLink.loginIntro" : "mailLink.verifyIntro")}</p>
<h1 className="text-balance text-4xl leading-tight">{t(`mailLink.${key}Title`)}</h1>
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t(`mailLink.${key}Intro`)}</p>
{error ? <ErrorNotice className="self-stretch">{t(`errors.${error}`)}</ErrorNotice> : null}
<Button size="lg" className="self-stretch" onClick={go} disabled={busy}>
{busy ? t("working") : t(login ? "mailLink.loginSubmit" : "mailLink.verifySubmit")}
{busy ? t("working") : t(`mailLink.${key}Submit`)}
</Button>
</div>
);
+52
View File
@@ -0,0 +1,52 @@
"use client";
import { useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
type State = { kind: "loading" } | { kind: "ready"; member: string; mac: string } | { kind: "done" } | { kind: "invalid" };
// Abmelden von den Mails zur Runde (26.11.53). Person und Prüfsumme stehen hinter #.
export function Unsubscribe() {
const t = useTranslations("roundMail.unsubscribePage");
const [state, setState] = useState<State>({ kind: "loading" });
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
useEffect(() => {
const m = window.location.hash.match(/^#([0-9a-f-]{36})\.([A-Za-z0-9_-]{20,100})$/);
history.replaceState(null, "", window.location.pathname);
setState(m ? { kind: "ready", member: m[1]!, mac: m[2]! } : { kind: "invalid" });
}, []);
async function go() {
if (state.kind !== "ready") return;
setBusy(true);
setError(false);
const res = await fetch("/api/mail/unsubscribe", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ member: state.member, mac: state.mac }),
}).catch(() => null);
setBusy(false);
if (res?.ok) return setState({ kind: "done" });
if (res?.status === 410) return setState({ kind: "invalid" });
setError(true);
}
if (state.kind === "loading") return null;
const key = state.kind === "done" ? "done" : state.kind === "invalid" ? "invalid" : "ask";
return (
<div className="flex flex-col items-center gap-4 text-center">
<h1 className="text-balance text-4xl leading-tight">{t(`${key}Title`)}</h1>
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t(`${key}Intro`)}</p>
{error ? <ErrorNotice className="self-stretch">{t("error")}</ErrorNotice> : null}
{state.kind === "ready" ? (
<Button size="lg" className="self-stretch" onClick={go} disabled={busy}>
{t("submit")}
</Button>
) : null}
</div>
);
}
+96
View File
@@ -0,0 +1,96 @@
"use client";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { ErrorNotice } from "@/components/ui/notice";
export type NotifyMember = {
id: string;
name: string;
role: string;
notifyEmail: string | null;
notifyVerified: boolean;
off: boolean;
loginEmail: string | null;
};
// Eine Zeile je Person: Adresse, Stand, Bestätigung schicken, Mails an/aus (26.11.53).
export function NotifyAdmin({ members }: { members: NotifyMember[] }) {
return (
<ul className="flex flex-col gap-4">
{members.map((m) => (
<NotifyRow key={m.id} member={m} />
))}
</ul>
);
}
function NotifyRow({ member: m }: { member: NotifyMember }) {
const t = useTranslations("more.roundMails");
const router = useRouter();
const [email, setEmail] = useState(m.notifyEmail ?? m.loginEmail ?? "");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [sent, setSent] = useState<string | null>(null);
const active = m.notifyVerified ? m.notifyEmail : m.loginEmail;
const status = m.off && active ? "off" : active ? "active" : m.notifyEmail ? "pending" : "none";
async function call(method: string, body: object) {
setBusy(true);
setError(null);
const res = await fetch("/api/household/notify", { method, headers: { "content-type": "application/json" }, body: JSON.stringify({ memberId: m.id, ...body }) }).catch(() => null);
const data = await res?.json().catch(() => ({}));
setBusy(false);
if (!res?.ok) {
setError(["mailNotConfigured", "mailFailed", "tooMany", "invalid"].includes(data?.error) ? data.error : "unknown");
return false;
}
router.refresh();
return true;
}
return (
<li className="flex flex-col gap-3 rounded-2xl bg-muted p-4" aria-label={m.name}>
<div className="flex items-baseline justify-between gap-2">
<h2 className="text-lg font-semibold">{m.name}</h2>
<span className="text-sm text-muted-foreground">{t(`status.${status}`, { email: active ?? m.notifyEmail ?? "" })}</span>
</div>
<form
className="flex flex-col gap-2"
onSubmit={async (e) => {
e.preventDefault();
if (await call("PUT", { email })) setSent(email);
}}
>
<Label htmlFor={`notify-${m.id}`}>{t("address", { name: m.name })}</Label>
<div className="flex gap-2">
<Input id={`notify-${m.id}`} type="email" inputMode="email" autoComplete="off" value={email} onChange={(e) => (setEmail(e.target.value), setSent(null))} />
<Button type="submit" variant="outline" disabled={busy || !email.includes("@")}>
{t("send")}
</Button>
</div>
</form>
{sent ? (
<p role="status" className="text-sm">
{t("sent", { email: sent })}
</p>
) : null}
{active ? (
<label className="flex min-h-11 items-center gap-3">
<input type="checkbox" className="size-5 accent-primary" checked={!m.off} disabled={busy} onChange={(e) => call("PATCH", { off: !e.target.checked })} />
{t("gets", { name: m.name })}
</label>
) : null}
{m.notifyEmail ? (
<Button type="button" variant="ghost" className="self-start" disabled={busy} onClick={() => call("DELETE", {})}>
{t("remove")}
</Button>
) : null}
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
</li>
);
}
+1 -1
View File
@@ -7,7 +7,7 @@ import { Button } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
import { RoundForm } from "@/components/wishes/round-form";
type Current = { shoppingDate: string | null; slotsCount: number; defaultPortions: number };
type Current = { shoppingDate: string | null; slotsCount: number; defaultPortions: number; wishDeadline: string | null };
// Runde bearbeiten, beenden, löschen (Kai, 8.11.2026, 26.11.45). Beenden und
// Löschen fragen im Knopf selbst nach, wie RemoveButton.
+38
View File
@@ -0,0 +1,38 @@
"use client";
import { Hourglass } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import { timeLeft } from "@/lib/round-mail-due";
// Countdown bis zur Frist der Runde (Kai, 9.11.2026, 26.11.53): „Wünsche bis Fr.,
// 13. Nov., 18:00 · noch 1 Tag 4 Std.“ — zählt jede Minute weiter.
export function Countdown({ deadline }: { deadline: string }) {
const t = useTranslations("wish.countdown");
const locale = useLocale();
const until = new Date(deadline);
const [now, setNow] = useState<Date | null>(null);
useEffect(() => {
setNow(new Date());
const tick = setInterval(() => setNow(new Date()), 30_000);
return () => clearInterval(tick);
}, []);
const when = new Intl.DateTimeFormat(locale, { weekday: "short", day: "numeric", month: "short", hour: "2-digit", minute: "2-digit" }).format(until);
const left = now ? timeLeft(until, now) : null;
const closed = now !== null && !left;
return (
<p className="flex items-center gap-2 rounded-2xl border-2 border-accent px-4 py-3 text-sm" data-testid="countdown">
<Hourglass aria-hidden className="size-5 shrink-0 text-accent" />
<span>
{closed ? (
t("closed")
) : (
<>
<span className="font-semibold">{t("until", { when })}</span>
{left ? <> · {t("left", { days: left.days, hours: left.hours, minutes: left.minutes })}</> : null}
</>
)}
</span>
</p>
);
}
+45 -3
View File
@@ -14,6 +14,17 @@ function nextSaturday(): string {
return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}
const pad = (n: number) => String(n).padStart(2, "0");
/** Für ein datetime-local-Feld: Ortszeit des Geräts. */
const localValue = (d: Date) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
/** Vorschlag für „Wünsche bis“ (26.11.53): Tag vor dem Einkauf, 18:00; ohne Einkaufstag in zwei Tagen. */
function suggestDeadline(shopping: string): string {
const d = shopping ? new Date(`${shopping}T18:00:00`) : new Date();
d.setDate(d.getDate() + (shopping ? -1 : 2));
d.setHours(18, 0, 0, 0);
return localValue(d);
}
function Stepper({ id, value, min, max, onChange, label }: { id: string; value: number; min: number; max: number; onChange: (n: number) => void; label: string }) {
const t = useTranslations("round");
return (
@@ -43,7 +54,7 @@ export function RoundForm({
onDone,
}: {
defaultPortions: number;
current?: { shoppingDate: string | null; slotsCount: number; defaultPortions: number };
current?: { shoppingDate: string | null; slotsCount: number; defaultPortions: number; wishDeadline?: string | null };
onDone?: () => void;
}) {
const t = useTranslations("round");
@@ -51,17 +62,24 @@ export function RoundForm({
const [date, setDate] = useState(() => (current ? current.shoppingDate ?? "" : nextSaturday()));
const [slots, setSlots] = useState(current?.slotsCount ?? 5);
const [portions, setPortions] = useState(current?.defaultPortions ?? defaultPortions);
// Frist: beim Eröffnen vorgeschlagen und mit dem Einkaufstag mitgeführt, bis man sie selbst ändert.
const [deadline, setDeadline] = useState(() =>
current ? (current.wishDeadline ? localValue(new Date(current.wishDeadline)) : "") : suggestDeadline(nextSaturday()),
);
const [deadlineTouched, setDeadlineTouched] = useState(!!current);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
async function submit(event: React.FormEvent) {
event.preventDefault();
const until = deadline ? new Date(deadline) : null;
if (until && until.getTime() <= Date.now()) return setError("deadlinePast");
setBusy(true);
setError(null);
const res = await fetch("/api/rounds", {
method: current ? "PATCH" : "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ shoppingDate: date || null, slotsCount: slots, defaultPortions: portions }),
body: JSON.stringify({ shoppingDate: date || null, slotsCount: slots, defaultPortions: portions, wishDeadline: until ? until.toISOString() : null }),
});
const data = await res.json().catch(() => ({}));
setBusy(false);
@@ -78,7 +96,31 @@ export function RoundForm({
<form onSubmit={submit} className="flex flex-col gap-5">
<div className="flex flex-col gap-2">
<Label htmlFor="shopping-date">{t("date")}</Label>
<Input id="shopping-date" type="date" value={date} onChange={(e) => setDate(e.target.value)} />
<Input
id="shopping-date"
type="date"
value={date}
onChange={(e) => {
setDate(e.target.value);
if (!deadlineTouched) setDeadline(suggestDeadline(e.target.value));
}}
/>
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="wish-deadline">{t("deadline")}</Label>
<Input
id="wish-deadline"
type="datetime-local"
value={deadline}
aria-describedby="wish-deadline-hint"
onChange={(e) => {
setDeadline(e.target.value);
setDeadlineTouched(true);
}}
/>
<p id="wish-deadline-hint" className="text-sm text-muted-foreground">
{t("deadlineHint")}
</p>
</div>
<Stepper id="slots" label={t("slots")} value={slots} min={1} max={14} onChange={setSlots} />
<Stepper id="portions" label={t("portions")} value={portions} min={1} max={30} onChange={setPortions} />
+1 -1
View File
@@ -107,7 +107,7 @@ export function WishBoard({
const data = await res.json().catch(() => ({}));
setBusy(null);
if (!res.ok) {
setError(["noTokens", "noVetos", "noRound", "noTrial", "dish", "alternative", "protected", "repeat", "notWished"].includes(data.error) ? data.error : "unknown");
setError(["noTokens", "noVetos", "noRound", "noTrial", "dish", "alternative", "protected", "repeat", "notWished", "closed"].includes(data.error) ? data.error : "unknown");
return null;
}
if (method !== "PATCH") setEdits(({ [key]: _, ...rest }) => rest); // neuer oder zurückgenommener Wunsch: Server gilt
+19
View File
@@ -0,0 +1,19 @@
-- Mails zur Runde (Kai, 9.11.2026, 26.11.53, E-0019): Einladung, Erinnerung
-- 24 h und 2 h vor der Frist, „Der Plan steht“.
--
-- Adressen trägt der Admin ein, auch für Kinder (notify_email); bestätigt wird
-- über einen Link an die Adresse selbst (mail_tokens, Zweck „notify“). Eine
-- bestätigte Anmelde-Adresse (email) gilt mit. Abmelden setzt notify_off.
-- Je Runde merkt sich ein Zeitstempel, welche Mail schon raus ist — höchstens einmal.
alter table members add column notify_email text check (notify_email = lower(notify_email) and notify_email like '%@%');
alter table members add column notify_verified_at timestamptz;
alter table members add column notify_off boolean not null default false;
alter table mail_tokens drop constraint mail_tokens_purpose_check;
alter table mail_tokens add constraint mail_tokens_purpose_check check (purpose in ('login', 'verify', 'notify'));
alter table rounds add column invite_sent_at timestamptz;
alter table rounds add column remind24_sent_at timestamptz;
alter table rounds add column remind2_sent_at timestamptz;
alter table rounds add column plan_mail_sent_at timestamptz;
+31
View File
@@ -336,6 +336,8 @@ statt 180. Adresse entfernen oder ändern beendet sie.
Sicherheitsprüfung: `docs/sicherheit/login-2026-11-07.md`.
In Betrieb seit 9.11.2026: Schlüssel unter Mehr › Mails verschicken eingetragen, Domain bei Resend geprüft, Testmail an Kai angekommen.
## E-0018 · Runde beenden, Tage von Hand, Kalender-Abo je Haushalt
*8.11.2026 · Kai („Ich möchte einen Plan löschen können und bearbeiten … die
@@ -370,6 +372,8 @@ Haushalts, Vorgabe 18:30, eine Stunde.
- Fehlversuche bremsen je Adresse und gemeinsam; gültige Abrufe zählen nicht,
weil Kalender stündlich nachfragen.
In Betrieb seit 9.11.2026: Kai hat den Haushalts-Link auf dem iPhone abonniert.
**Nachtrag 26.11.46 · Einkaufsliste einsprechen** (Kai, 8.11.2026): Neben dem
Freitextfeld der Einkaufsliste steht ein Mikrofon, sobald ein Sprachmodell
eingerichtet ist (dasselbe wie bei „Gericht einsprechen“). Die Abschrift zerlegt
@@ -411,3 +415,30 @@ wie beim Löffel). Stück-Zutaten nehmen g, kg, ml und l mit einer Größe je St
(„1 Brühwürfel = 500 ml“), gespeichert unter dem Maß `g` bzw. `ml` in
`household_pack_sizes` (Migration 0027). Das Rezept zeigt das eingegebene Maß
(„750 ml (1½ Stück)“), die Einkaufsliste weiter Stück.
## E-0019 · Mails zur Runde mit Frist und Countdown
*9.11.2026 · Kai („wenn eine neue Runde gemacht wird, dass dann eine E-Mail
versendet wird automatisch an alle … Countdown … Erinnerung“).*
**Adressen:** Der Admin trägt sie ein, auch für Kinder (Kai), unter Mehr › Mails
zur Runde. Jede Adresse wird per Link bestätigt (`mail_tokens`, Zweck `notify`,
7 Tage); die Bestätigung startet nie eine Sitzung. Ohne eigene Adresse gilt die
bestätigte Anmelde-Adresse. Gäste bekommen nichts.
**Frist:** beim Eröffnen wählbar (Kai), Feld „Wünsche bis“, Vorschlag am Tag vor
dem Einkauf um 18:00. Nach der Frist lehnt der Server Wünsche ab (`closed`);
„Heute“ und „Wünschen“ zählen herunter. Leer heißt keine Frist und keine
Erinnerungen.
**Mails** (Kai): Einladung bei Eröffnung, Erinnerung 24 h vorher, letzter
Aufruf 2 h vorher (beide nur an Personen ohne Wunsch), „Der Plan steht“ nach der
Freigabe. Ein Takt im Server schaut jede Minute nach (`lib/round-mail-schedule.ts`),
Eröffnen und Freigeben stoßen ihn sofort an. Der Zeitstempel je Mail wird unter
Zeilensperre gesetzt, bevor versendet wird — jede Mail höchstens einmal. Liegt eine
Erinnerung keine Stunde nach der vorigen Mail, entfällt sie. Ohne eingerichteten
Mailweg passiert nichts.
**Abmelden:** Jede Mail trägt einen Link `/mail/abmelden#<Person>.<Prüfsumme>`
(HMAC mit dem Tresor-Schlüssel), ohne Speicherung und ohne Anmeldung. Der Admin
kann eine Person wieder einschalten.
+100
View File
@@ -0,0 +1,100 @@
import { readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Browser, type Page } from "@playwright/test";
// Mails zur Runde (Kai, 9.11.2026, 26.11.53): Der Admin trägt Adressen ein (auch für
// Kinder), sie werden per Link bestätigt; eine neue Runde mit Frist lädt ein, der
// Countdown steht in der App, „Der Plan steht“ kommt nach der Freigabe, und der
// Abmelde-Link aus der Mail wirkt. Der Server schreibt Mails nach $LUNCH_DATA/mails
// und schaut alle 2 Sekunden nach fälligen Mails (ROUND_MAIL_EVERY_MS).
test.describe.configure({ mode: "serial" });
const DIR = path.join(process.env.LUNCH_DATA ?? "", "mails");
const KAI = "kai@test.example";
const BEN = "ben@test.example";
type Sent = { to: string; subject: string; text: string; html: string };
async function mails(to: string): Promise<Sent[]> {
const files = (await readdir(DIR).catch(() => [])).sort();
const all = await Promise.all(files.map(async (f) => JSON.parse(await readFile(path.join(DIR, f), "utf8")) as Sent));
return all.filter((m) => m.to === to);
}
const count = async (to: string, subject: RegExp) => (await mails(to)).filter((m) => subject.test(m.subject)).length;
async function fresh(browser: Browser): Promise<Page> {
const context = await browser.newContext({ ...test.info().project.use, storageState: undefined });
return context.newPage();
}
test("the admin adds an address for a child, confirmed by the link in it", async ({ page, browser }) => {
await page.goto("/mehr");
await page.getByRole("link", { name: /Mails zur Runde|bekommt Mails|bekommen Mails/ }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Mails zur Runde");
// Kai hat seine Adresse schon zum Anmelden bestätigt (mail.spec) — die gilt mit.
await expect(page.getByRole("listitem", { name: "Kai" })).toContainText(`bekommt Mails an ${KAI}`);
const ben = page.getByRole("listitem", { name: "Ben" });
await ben.getByLabel("Adresse für Ben").fill(BEN);
await ben.getByRole("button", { name: "Bestätigung schicken" }).click();
await expect(ben.getByRole("status")).toContainText(`Bestätigung an ${BEN} unterwegs.`);
await expect(ben).toContainText("wartet auf Bestätigung");
const confirm = (await mails(BEN)).at(-1)!;
const link = confirm.text.match(/https?:\/\/\S+\/anmelden\/mail#notify=\S+/)![0];
const inbox = await fresh(browser);
await inbox.goto(link);
await expect(inbox.getByRole("heading", { level: 1 })).toHaveText("Mails zur Runde bestätigen");
await inbox.getByRole("button", { name: "Bestätigen" }).click();
await expect(inbox.getByRole("heading", { level: 1 })).toHaveText("Alles klar!");
await inbox.context().close();
await page.reload();
await expect(page.getByRole("listitem", { name: "Ben" })).toContainText(`bekommt Mails an ${BEN}`);
});
test("a new round with a deadline invites everyone and counts down", async ({ page }) => {
const before = { kai: await count(KAI, /Du entscheidest mit/), ben: await count(BEN, /Du entscheidest mit/) };
await page.goto("/plan");
await page.getByRole("button", { name: "Runde beenden" }).click();
await page.getByRole("button", { name: /Wirklich beenden/ }).click();
await page.getByRole("link", { name: "Runde eröffnen" }).click();
// Frist in 90 Minuten, Ortszeit des Geräts.
const until = new Date(Date.now() + 90 * 60 * 1000);
const pad = (n: number) => String(n).padStart(2, "0");
await page
.getByLabel("Wünsche bis")
.fill(`${until.getFullYear()}-${pad(until.getMonth() + 1)}-${pad(until.getDate())}T${pad(until.getHours())}:${pad(until.getMinutes())}`);
await page.getByRole("button", { name: "Runde eröffnen" }).click();
await expect(page).toHaveURL(/\/$/);
await expect(page.getByTestId("countdown")).toContainText("Wünsche bis");
await expect.poll(() => count(BEN, /Du entscheidest mit/), { timeout: 15_000 }).toBe(before.ben + 1);
await expect.poll(() => count(KAI, /Du entscheidest mit/), { timeout: 15_000 }).toBe(before.kai + 1);
const invite = (await mails(BEN)).filter((m) => /Du entscheidest mit/.test(m.subject)).at(-1)!;
expect(invite.html).toContain("Hey Ben, die neue Runde ist offen!");
expect(invite.text).toMatch(/\/wuenschen/);
await page.goto("/wuenschen");
await expect(page.getByTestId("countdown")).toContainText(/noch .*Std\./);
});
test("the unsubscribe link from the mail stops further mails", async ({ page, browser }) => {
const invite = (await mails(BEN)).filter((m) => /Du entscheidest mit/.test(m.subject)).at(-1)!;
const link = invite.text.match(/https?:\/\/\S+\/mail\/abmelden#\S+/)![0];
const inbox = await fresh(browser);
await inbox.goto(link);
await expect(inbox.getByRole("heading", { level: 1 })).toHaveText("Keine Mails zur Runde mehr?");
await inbox.getByRole("button", { name: "Abmelden" }).click();
await expect(inbox.getByRole("heading", { level: 1 })).toHaveText("Abgemeldet");
await inbox.context().close();
await page.goto("/mehr/runden-mails");
await expect(page.getByRole("listitem", { name: "Ben" })).toContainText("abgemeldet");
});
test("approving the plan sends “the plan is ready”", async ({ page }) => {
const before = { kai: await count(KAI, /Der Plan steht/), ben: await count(BEN, /Der Plan steht/) };
await page.goto("/plan");
await page.getByRole("button", { name: "Vorschlag erstellen" }).click();
await expect(page.locator("main ol > li").first()).toBeVisible();
await page.getByRole("button", { name: "Plan freigeben" }).click();
await expect.poll(() => count(KAI, /Der Plan steht/), { timeout: 15_000 }).toBe(before.kai + 1);
// Ben hat sich abgemeldet.
expect(await count(BEN, /Der Plan steht/)).toBe(before.ben);
});
+2
View File
@@ -20,6 +20,7 @@ const SIGNED_IN = [
{ path: "/gerichte/sprechen", heading: "Gericht einsprechen" },
{ path: "/mehr/ki", heading: "AI" },
{ path: "/mehr/mail", heading: "Mails verschicken" },
{ path: "/mehr/runden-mails", heading: "Mails zur Runde" },
{ path: "/wuenschen", heading: "Wünschen" },
{ path: "/plan", heading: "Plan" },
{ path: "/einkauf", heading: "Einkaufsliste" },
@@ -29,6 +30,7 @@ const SIGNED_OUT = [
{ path: "/anmelden", heading: "Anmelden" },
{ path: "/wiederherstellen", heading: "Zugang wiederherstellen" },
{ path: "/anmelden/mail", heading: "Dieser Link gilt nicht mehr" },
{ path: "/mail/abmelden", heading: "Dieser Link gilt nicht" },
{ path: "/kinder", heading: "Kein Kindergerät" },
{ path: "/offline", heading: "Kein Netz" },
];
+9 -3
View File
@@ -1,7 +1,13 @@
// Läuft einmal beim Start des Servers (Next.js). Startet den Takt der
// Sicherung — nur in Node, nicht beim Bauen und nicht im Edge-Laufzeitteil.
// Läuft einmal beim Start des Servers (Next.js). Startet die Takte im Hintergrund
// — nur in Node, nicht beim Bauen und nicht im Edge-Laufzeitteil: die Sicherung
// und die Mails zur Runde (26.11.53).
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs" || process.env.BACKUP_DISABLED === "1") return;
if (process.env.NEXT_RUNTIME !== "nodejs") return;
if (process.env.ROUND_MAILS_DISABLED !== "1") {
const { startRoundMailSchedule } = await import("./lib/round-mail-schedule");
startRoundMailSchedule();
}
if (process.env.BACKUP_DISABLED === "1") return;
const { startBackupSchedule } = await import("./lib/backup-schedule");
startBackupSchedule();
}
+11 -2
View File
@@ -11,8 +11,10 @@ import { hashToken, randomToken } from "./tokens";
// abruft, verbraucht ihn nicht, und der Token steht in keinem Server-Log.
// Die Adresse im Link kommt aus der Tabelle instance, nie aus dem Host-Kopf.
export type Purpose = "login" | "verify";
const LIFETIME_MINUTES: Record<Purpose, number> = { login: 15, verify: 24 * 60 };
// notify (26.11.53): Adresse für die Mails zur Runde, vom Admin eingetragen — auch
// für Kinder. Bestätigen beginnt nie eine Sitzung.
export type Purpose = "login" | "verify" | "notify";
const LIFETIME_MINUTES: Record<Purpose, number> = { login: 15, verify: 24 * 60, notify: 7 * 24 * 60 };
/** Wer sich per Mail anmelden darf: Erwachsene und Jugendliche, keine Kinder, keine Gäste. */
const MAIL_ROLES = ["admin", "member", "teen"];
@@ -63,6 +65,13 @@ export async function consumeMailToken(client: PoolClient, token: string): Promi
const member = await findMailMember(client, hit.email);
return member?.id === hit.memberId ? hit : null;
}
if (hit.purpose === "notify") {
const { rowCount } = await client.query(
"update members set notify_email = $2, notify_verified_at = now(), notify_off = false where id = $1 and role <> 'guest'",
[hit.memberId, hit.email],
);
return rowCount ? hit : null;
}
// Bestätigen: Gehört die Adresse inzwischen jemand anderem, gilt der Link nicht.
const taken = await client.query("select 1 from members where email = $1 and id <> $2", [hit.email, hit.memberId]);
if (taken.rowCount) return null;
+67
View File
@@ -80,3 +80,70 @@ export function buttonMail(p: { to: string; subject: string; lead: string; butto
</div></body></html>`;
return { to: p.to, subject: p.subject, text, html };
}
/**
* Mails zur Runde (26.11.53): Kopf in Koralle, große Frist-Box, Knopf, kurze Liste,
* Fuß mit Abmelde-Link. Nur Inline-Stile, keine Bilder von außen, kein Tracking —
* die Gerichtsfotos sind privat und bleiben auf der Box.
*/
export function roundMail(p: {
to: string;
subject: string;
preheader: string;
eyebrow: string;
title: string;
lead: string;
box?: { big: string; small: string } | null;
points?: string[];
listTitle?: string;
list?: { title: string; meta: string }[];
button: string;
url: string;
footer: string;
unsubscribe: { label: string; url: string };
}): Mail {
const lines = [
p.title,
"",
p.lead,
...(p.box ? ["", `${p.box.big} — ${p.box.small}`] : []),
...(p.points?.length ? ["", ...p.points.map((x) => `• ${x}`)] : []),
...(p.list?.length ? ["", p.listTitle ?? "", ...p.list.map((x) => `• ${x.title}${x.meta ? ` (${x.meta})` : ""}`)] : []),
"",
`${p.button}: ${p.url}`,
"",
p.footer,
`${p.unsubscribe.label}: ${p.unsubscribe.url}`,
];
const box = p.box
? `<div style="margin:0 0 24px;padding:20px;border-radius:16px;background:#fff3ee;border:2px solid #f39380;text-align:center">
<p style="margin:0;font-size:30px;font-weight:700;color:#1f1d2b">${escape(p.box.big)}</p>
<p style="margin:6px 0 0;font-size:14px;color:#5e5a70">${escape(p.box.small)}</p></div>`
: "";
const points = p.points?.length
? `<ul style="margin:0 0 24px;padding:0 0 0 20px;font-size:15px;line-height:1.6">${p.points.map((x) => `<li>${escape(x)}</li>`).join("")}</ul>`
: "";
const list = p.list?.length
? `<p style="margin:0 0 8px;font-size:13px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#5b4a9e">${escape(p.listTitle ?? "")}</p>
<table role="presentation" style="width:100%;border-collapse:collapse;margin:0 0 24px">${p.list
.map(
(x) =>
`<tr><td style="padding:10px 0;border-bottom:1px solid #ece8f6;font-size:15px;font-weight:600">${escape(x.title)}</td><td style="padding:10px 0;border-bottom:1px solid #ece8f6;font-size:13px;color:#5e5a70;text-align:right">${escape(x.meta)}</td></tr>`,
)
.join("")}</table>`
: "";
const html = `<!doctype html><html><body style="margin:0;padding:0;background:#faf8ff;font-family:Poppins,Helvetica,Arial,sans-serif;color:#1f1d2b">
<span style="display:none;max-height:0;overflow:hidden">${escape(p.preheader)}</span>
<div style="max-width:520px;margin:0 auto;padding:24px 16px">
<div style="background:#f39380;border-radius:20px 20px 0 0;padding:24px 28px">
<p style="margin:0;font-size:13px;font-weight:700;letter-spacing:.1em;text-transform:uppercase;color:#3b1d14">${escape(p.eyebrow)}</p>
<p style="margin:6px 0 0;font-size:26px;line-height:1.25;font-weight:700;color:#1f1d2b">${escape(p.title)}</p></div>
<div style="background:#ffffff;border-radius:0 0 20px 20px;padding:28px">
<p style="margin:0 0 24px;font-size:16px;line-height:1.6">${escape(p.lead)}</p>
${box}${points}${list}
<p style="margin:0 0 8px;text-align:center"><a href="${escape(p.url)}" style="display:inline-block;background:#5b4a9e;color:#ffffff;text-decoration:none;font-weight:600;font-size:17px;padding:16px 32px;border-radius:999px">${escape(p.button)}</a></p>
</div>
<p style="margin:20px 8px 0;font-size:12px;line-height:1.6;color:#5e5a70;text-align:center">${escape(p.footer)}<br><a href="${escape(p.unsubscribe.url)}" style="color:#5e5a70">${escape(p.unsubscribe.label)}</a></p>
</div></body></html>`;
return { to: p.to, subject: p.subject, text: lines.join("\n"), html };
}
+63
View File
@@ -0,0 +1,63 @@
// Welche Mail zur Runde ist fällig (Kai, 9.11.2026, 26.11.53)? Rein, ohne
// Datenbank, damit jeder Fall im Test steht.
//
// - Einladung, sobald die Runde offen ist (und die Frist nicht vorbei).
// - Erinnerung ab 24 h vor der Frist, letzter Aufruf ab 2 h davor — nur, solange
// die Frist läuft. Was schon kurz nach der Einladung fällig wäre, entfällt:
// Niemand bekommt zwei Mails in derselben Stunde.
// - „Der Plan steht“ nach der Freigabe — nur für Runden, die eingeladen haben
// (ältere Runden vor 26.11.53 bekommen keine nachträgliche Mail).
export type RoundMailKind = "invite" | "remind24" | "remind2" | "plan";
export type RoundMailState = {
status: "open" | "planned" | "shopping" | "done";
wishDeadline: Date | null;
inviteSentAt: Date | null;
remind24SentAt: Date | null;
remind2SentAt: Date | null;
planMailSentAt: Date | null;
};
const HOUR = 60 * 60 * 1000;
/** Abstand, unter dem eine Erinnerung nach der letzten Mail entfällt. */
const QUIET = HOUR;
/** send: jetzt verschicken; skip: als erledigt markieren, ohne zu schicken. */
export function dueMails(r: RoundMailState, now: Date): { send: RoundMailKind[]; skip: RoundMailKind[] } {
const send: RoundMailKind[] = [];
const skip: RoundMailKind[] = [];
const t = now.getTime();
const deadline = r.wishDeadline?.getTime() ?? null;
if (r.status === "open") {
if (!r.inviteSentAt) {
if (deadline !== null && t >= deadline) return { send, skip: ["invite"] };
send.push("invite");
// Erinnerungen, deren Zeit schon da ist, wären doppelt.
if (deadline !== null && t >= deadline - 24 * HOUR && !r.remind24SentAt) skip.push("remind24");
if (deadline !== null && t >= deadline - 2 * HOUR - QUIET && !r.remind2SentAt) skip.push("remind2");
return { send, skip };
}
if (deadline === null || t >= deadline) return { send, skip };
const last = Math.max(r.inviteSentAt.getTime(), r.remind24SentAt?.getTime() ?? 0);
if (!r.remind2SentAt && t >= deadline - 2 * HOUR) {
(last > deadline - 2 * HOUR - QUIET ? skip : send).push("remind2");
if (!r.remind24SentAt) skip.push("remind24");
return { send, skip };
}
if (!r.remind24SentAt && t >= deadline - 24 * HOUR) {
(r.inviteSentAt.getTime() > deadline - 24 * HOUR - QUIET ? skip : send).push("remind24");
}
return { send, skip };
}
if ((r.status === "planned" || r.status === "shopping") && r.inviteSentAt && !r.planMailSentAt) send.push("plan");
return { send, skip };
}
/** „noch 2 Tage 4 Std.“ — Teile für die Sprache; null, wenn vorbei. */
export function timeLeft(deadline: Date, now: Date): { days: number; hours: number; minutes: number } | null {
const ms = deadline.getTime() - now.getTime();
if (ms <= 0) return null;
const minutes = Math.floor(ms / 60000);
return { days: Math.floor(minutes / 1440), hours: Math.floor((minutes % 1440) / 60), minutes: minutes % 60 };
}
+24
View File
@@ -0,0 +1,24 @@
import { sendAllRoundMails } from "./round-mails";
// Mails zur Runde (26.11.53): jede Minute nachsehen, was fällig ist. Im Test schneller
// (ROUND_MAIL_EVERY_MS), damit Erinnerungen nicht eine Minute auf sich warten lassen.
let started = false;
export function startRoundMailSchedule(): void {
if (started) return;
started = true;
const every = Number(process.env.ROUND_MAIL_EVERY_MS) || 60 * 1000;
let running = false;
const run = async () => {
if (running) return;
running = true;
try {
await sendAllRoundMails();
} catch (error) {
console.error("round mail schedule:", error instanceof Error ? error.message : error);
} finally {
running = false;
}
};
setInterval(run, every).unref();
}
+165
View File
@@ -0,0 +1,165 @@
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<Recipient[]> {
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<string> {
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<Mail> {
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<RoundMailKind, string> = {
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<void> {
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));
}
+15 -6
View File
@@ -12,16 +12,21 @@ export type Round = {
shoppingDate: string | null;
slotsCount: number;
defaultPortions: number;
/** Bis wann gewünscht werden kann (ISO, UTC), oder null (26.11.53). */
wishDeadline: string | null;
};
export const roundInput = z.object({
shoppingDate: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable(),
slotsCount: z.number().int().min(1).max(14),
defaultPortions: z.number().int().min(1).max(30),
// „Wünsche bis“ (26.11.53): ein Zeitpunkt mit Zone; leer heißt keine Frist und keine Erinnerungen.
wishDeadline: z.string().datetime({ offset: true }).nullable().optional(),
});
const columns = `id, status, to_char(shopping_date, 'YYYY-MM-DD') as "shoppingDate", slots_count as "slotsCount",
default_portions as "defaultPortions"`;
default_portions as "defaultPortions",
to_char(wish_deadline at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') as "wishDeadline"`;
/** Die laufende Runde (nicht abgeschlossen), oder null. Es gibt höchstens eine. */
export async function currentRound(client: PoolClient): Promise<Round | null> {
@@ -37,9 +42,9 @@ export async function openRound(client: PoolClient, householdId: string, memberI
if (await currentRound(client)) throw new RoundExists();
const store = (await client.query("select id from stores where is_default limit 1")).rows[0]?.id ?? null;
const { rows } = await client.query(
`insert into rounds (household_id, shopping_date, slots_count, default_portions, store_id, created_by)
values ($1, $2, $3, $4, $5, $6) returning id`,
[householdId, input.shoppingDate, input.slotsCount, input.defaultPortions, store, memberId],
`insert into rounds (household_id, shopping_date, slots_count, default_portions, store_id, created_by, wish_deadline)
values ($1, $2, $3, $4, $5, $6, $7) returning id`,
[householdId, input.shoppingDate, input.slotsCount, input.defaultPortions, store, memberId, input.wishDeadline ?? null],
);
return rows[0].id;
}
@@ -66,8 +71,12 @@ export async function deleteRound(client: PoolClient, roundId: string): Promise<
/** Einkaufstag, Zahl der Mahlzeiten und Standardportionen nachträglich ändern. */
export async function updateRound(client: PoolClient, roundId: string, input: z.infer<typeof roundInput>): Promise<boolean> {
const { rowCount } = await client.query(
"update rounds set shopping_date = $2, slots_count = $3, default_portions = $4 where id = $1 and status <> 'done'",
[roundId, input.shoppingDate, input.slotsCount, input.defaultPortions],
// Eine verschobene Frist erinnert neu: Erinnerungen, deren Zeit noch kommt, gehen wieder raus.
`update rounds set shopping_date = $2, slots_count = $3, default_portions = $4, wish_deadline = $5,
remind24_sent_at = case when wish_deadline is distinct from $5 then null else remind24_sent_at end,
remind2_sent_at = case when wish_deadline is distinct from $5 then null else remind2_sent_at end
where id = $1 and status <> 'done'`,
[roundId, input.shoppingDate, input.slotsCount, input.defaultPortions, input.wishDeadline ?? null],
);
return rowCount === 1;
}
+15 -1
View File
@@ -1,5 +1,5 @@
import "server-only";
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";
import path from "node:path";
@@ -51,6 +51,20 @@ export async function unseal(data: Buffer): Promise<string> {
return Buffer.concat([decipher.update(data.subarray(29)), decipher.final()]).toString("utf8");
}
/**
* Prüfsumme über einen Text mit dem Tresor-Schlüssel (26.11.53): für Links, die
* dauerhaft gelten und nichts speichern müssen, etwa „Mails abbestellen“.
*/
export async function mac(text: string): Promise<string> {
return createHmac("sha256", await key()).update(text, "utf8").digest("base64url");
}
export async function macOk(text: string, given: string): Promise<boolean> {
const want = Buffer.from(await mac(text));
const got = Buffer.from(given);
return want.length === got.length && timingSafeEqual(want, got);
}
/** Nur für Tests: Schlüssel neu lesen. */
export function forgetKeyForTests() {
cached = null;
+17 -5
View File
@@ -65,7 +65,7 @@ export function favorites(entries: WishEntry[]): Set<string> {
}
export class WishRefused extends Error {
constructor(public reason: "noRound" | "noTokens" | "noVetos" | "dish" | "already" | "alternative" | "protected" | "repeat" | "notWished") {
constructor(public reason: "noRound" | "noTokens" | "noVetos" | "dish" | "already" | "alternative" | "protected" | "repeat" | "notWished" | "closed") {
super(reason);
}
}
@@ -73,10 +73,22 @@ export class WishRefused extends Error {
type WishOptions = { note?: string | null; wantsToCook?: boolean; veto?: boolean; alternativeDishId?: string };
/** Wunsch oder Veto für ein Gericht der offenen Runde. Zählt unter Sperre je Person. */
/**
* Die offene Runde, in der man noch wünschen darf. Nach der Frist (rounds.wish_deadline,
* 26.11.53) ist Wünschen geschlossen — der Plan bleibt für Planende änderbar.
*/
async function openRoundFor(client: PoolClient): Promise<{ id: string }> {
const round = (
await client.query("select id, coalesce(wish_deadline <= now(), false) as closed from rounds where status = 'open' order by created_at desc limit 1")
).rows[0] as { id: string; closed: boolean } | undefined;
if (!round) throw new WishRefused("noRound");
if (round.closed) throw new WishRefused("closed");
return { id: round.id };
}
export async function addWish(client: PoolClient, householdId: string, memberId: string, dishId: string, opts: WishOptions = {}) {
await client.query("select pg_advisory_xact_lock(hashtext('wish:' || $1))", [memberId]);
const round = (await client.query("select id from rounds where status = 'open' order by created_at desc limit 1")).rows[0];
if (!round) throw new WishRefused("noRound");
const round = await openRoundFor(client);
const dish = (await client.query("select id from dishes where id = $1 and archived_at is null", [dishId])).rows[0];
if (!dish) throw new WishRefused("dish");
// Gegen „Mein Gericht“ hilft kein Veto — es würde nur verbraucht.
@@ -143,8 +155,7 @@ export async function lastMine(client: PoolClient, roundId: string): Promise<{ m
// (ein Jeton) — in derselben Transaktion, also ganz oder gar nicht.
export async function setMine(client: PoolClient, memberId: string, dishId: string, on: boolean, opts: { wishIn?: string } = {}): Promise<void> {
await client.query("select pg_advisory_xact_lock(hashtext('wish:' || $1))", [memberId]);
const round = (await client.query("select id from rounds where status = 'open' order by created_at desc limit 1")).rows[0];
if (!round) throw new WishRefused("noRound");
const round = await openRoundFor(client);
if (!on) {
await client.query("update wishes set is_mine = false where round_id = $1 and member_id = $2 and dish_id = $3", [round.id, memberId, dishId]);
return;
@@ -191,6 +202,7 @@ export async function updateWish(client: PoolClient, memberId: string, dishId: s
/** Eigenen Wunsch oder eigenes Veto zurücknehmen (nur solange die Runde offen ist). */
export async function removeWish(client: PoolClient, memberId: string, dishId: string): Promise<boolean> {
await openRoundFor(client);
const { rows } = await client.query(
`delete from wishes where member_id = $1 and dish_id = $2
and round_id = (select id from rounds where status = 'open' order by created_at desc limit 1)
+102 -5
View File
@@ -113,7 +113,12 @@
"toMore": "Weiter",
"expiredTitle": "Dieser Link gilt nicht mehr",
"expiredIntro": "Links aus der Mail gelten einmal und nur kurz. Fordere einfach einen neuen an.",
"back": "Zur Anmeldung"
"back": "Zur Anmeldung",
"notifyTitle": "Mails zur Runde bestätigen",
"notifyIntro": "Danach kommt eine Mail, wenn eine neue Essens-Runde startet – mit Frist und Erinnerung.",
"notifySubmit": "Bestätigen",
"notifyDone": "Alles klar!",
"notifyDoneIntro": "Du bekommst jetzt die Mails zur Runde."
}
},
"more": {
@@ -328,6 +333,31 @@
"confirmStop": "Wirklich beenden? Noch einmal tippen",
"locked": "Nach der Anmeldung per Mail geht das nicht. Melde dich mit dem Passkey an.",
"error": "Das hat nicht geklappt. Bitte versuch es noch einmal."
},
"roundMails": {
"title": "Mails zur Runde",
"count": "{n, plural, =0 {Noch niemand bekommt Mails} one {1 Person bekommt Mails} other {# Personen bekommen Mails}}",
"summary": "Einladung, Erinnerungen und „Der Plan steht“",
"intro": "Trag für jede Person eine Adresse ein – auch für Kinder. Sie bekommt einen Link zum Bestätigen; erst danach gehen Mails dorthin.",
"notReady": "Noch kein Mailweg eingerichtet. Das geht unter Mehr › Mails verschicken.",
"status": {
"active": "bekommt Mails an {email}",
"pending": "wartet auf Bestätigung",
"none": "keine Adresse",
"off": "abgemeldet"
},
"address": "Adresse für {name}",
"send": "Bestätigung schicken",
"sent": "Bestätigung an {email} unterwegs.",
"gets": "{name} bekommt Mails zur Runde",
"remove": "Adresse entfernen",
"errors": {
"mailNotConfigured": "Noch kein Mailweg eingerichtet.",
"mailFailed": "Die Mail ließ sich nicht verschicken.",
"tooMany": "Zu viele Versuche. Bitte warte eine Stunde.",
"invalid": "Bitte prüfe die Adresse.",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal."
}
}
},
"nav": {
@@ -612,9 +642,12 @@
"more": "{what}: mehr",
"errors": {
"roundExists": "Es läuft schon eine Runde.",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal."
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.",
"deadlinePast": "Die Frist liegt in der Vergangenheit. Bitte wähle einen späteren Zeitpunkt."
},
"save": "Speichern"
"save": "Speichern",
"deadline": "Wünsche bis",
"deadlineHint": "Bis dahin kann jede Person wünschen. Alle mit Adresse bekommen eine Einladung und vor Schluss zwei Erinnerungen. Leer lassen: keine Frist."
},
"wish": {
"eyebrow": "Runde",
@@ -667,7 +700,8 @@
"alternative": "Bitte wähl ein anderes Gericht aus dem Pool, das noch niemand gewünscht hat.",
"protected": "Das ist das Gericht von jemandem — dagegen gibt es kein Veto.",
"repeat": "Das war letzte Runde schon dein Gericht. Such dir diesmal ein anderes aus.",
"notWished": "Wünsch dir das Gericht zuerst, dann kannst du es zu deinem machen."
"notWished": "Wünsch dir das Gericht zuerst, dann kannst du es zu deinem machen.",
"closed": "Die Frist ist vorbei – Wünschen ist geschlossen."
},
"wishAction": "Wünschen:",
"unwishAction": "Wunsch zurücknehmen:",
@@ -688,7 +722,13 @@
"vetoCount": "{n, plural, one {1 Veto} other {# Vetos}}",
"jokerShort": "Neues",
"mineToggle": "{title} als mein Gericht",
"mineUntoggle": "{title} nicht mehr mein Gericht"
"mineUntoggle": "{title} nicht mehr mein Gericht",
"countdown": {
"until": "Wünsche bis {when}",
"left": "noch {days, plural, =0 {} one {# Tag } other {# Tage }}{hours} Std. {minutes} Min.",
"closed": "Die Frist ist vorbei – Wünschen ist geschlossen."
},
"deadlinePassed": "Die Frist für Wünsche ist vorbei. Der Plan kommt bald."
},
"kids": {
"title": "Wer bist du?",
@@ -1211,6 +1251,12 @@
"lead": "Wenn du das liest, kann foodplanhero Mails verschicken.",
"button": "foodplanhero öffnen",
"note": "Diese Mail kam über die Einstellung unter Mehr › Mails verschicken."
},
"notify": {
"subject": "Mails zur Essens-Runde bestätigen",
"lead": "Diese Adresse wurde bei foodplanhero für die Mails zur Essens-Runde eingetragen: Einladung, wenn ihr plant, und eine Erinnerung vor Schluss. Bitte bestätige sie. Der Link gilt 7 Tage.",
"button": "Adresse bestätigen",
"note": "Nicht erwartet? Dann ignoriere diese Mail – ohne Bestätigung kommt nichts."
}
},
"calendar": {
@@ -1218,5 +1264,56 @@
"cook": "Es kocht {name}",
"portions": "{n, plural, one {# Portion} other {# Portionen}}",
"open": "In foodplanhero öffnen: {url}"
},
"roundMail": {
"left": "noch {days, plural, =0 {} one {# Tag } other {# Tage }}{hours} Std.",
"until": "Wünsche bis {when}",
"unsubscribe": "Keine Mails zur Runde mehr",
"footer": "foodplanhero · {household}",
"teaserTitle": "Vielleicht diesmal?",
"button": "Jetzt wünschen",
"points": {
"tokens": "Du hast {n, plural, one {# Jeton} other {# Jetons}} – jeder ist ein Wunsch.",
"mine": "Tipp aufs Herz: Dein Gericht kommt sicher auf den Tisch, kein Veto streicht es.",
"shopping": "Eingekauft wird {day}, geplant sind {n, plural, one {# warme Mahlzeit} other {# warme Mahlzeiten}}."
},
"invite": {
"subject": "Was gibt’s diese Woche? Du entscheidest mit",
"preheader": "Die neue Runde ist offen – wünsch dir was.",
"title": "Hey {name}, die neue Runde ist offen!",
"lead": "Das Essen für die nächsten Tage steht an. Wünsch dir, was auf den Tisch kommt – mit etwas Glück ist dein Lieblingsessen dabei."
},
"remind24": {
"subject": "Noch 24 Stunden: Was möchtest du essen?",
"preheader": "Morgen um diese Zeit ist Schluss.",
"title": "{name}, dein Wunsch fehlt noch",
"lead": "Morgen ist Schluss mit Wünschen. Sonst entscheiden die anderen für dich"
},
"remind2": {
"subject": "Letzter Aufruf: noch 2 Stunden zum Wünschen",
"preheader": "Gleich ist Schluss.",
"title": "Letzter Aufruf, {name}!",
"lead": "In zwei Stunden steht fest, was es gibt. Ein Tipp genügt."
},
"plan": {
"subject": "Der Plan steht",
"preheader": "{n, plural, one {# Gericht} other {# Gerichte}} für die nächsten Tage.",
"title": "{name}, der Plan steht!",
"lead": "Das kommt in den nächsten Tagen auf den Tisch.",
"leadShopping": "Eingekauft wird {day} – das kommt in den nächsten Tagen auf den Tisch.",
"listTitle": "Der Plan",
"cook": "kocht: {name}",
"button": "Zum Plan"
},
"unsubscribePage": {
"askTitle": "Keine Mails zur Runde mehr?",
"askIntro": "Du bekommst dann keine Einladung und keine Erinnerung mehr. Ein Admin kann es wieder einschalten.",
"submit": "Abmelden",
"doneTitle": "Abgemeldet",
"doneIntro": "Du bekommst keine Mails zur Runde mehr.",
"invalidTitle": "Dieser Link gilt nicht",
"invalidIntro": "Bitte nimm den Link aus einer Mail von foodplanhero.",
"error": "Das hat nicht geklappt. Bitte versuch es noch einmal."
}
}
}
+102 -5
View File
@@ -113,7 +113,12 @@
"toMore": "Continue",
"expiredTitle": "This link is no longer valid",
"expiredIntro": "Mail links work once and only for a short time. Just request a new one.",
"back": "To sign in"
"back": "To sign in",
"notifyTitle": "Confirm round emails",
"notifyIntro": "You will then get an email when a new meal round starts – with deadline and reminder.",
"notifySubmit": "Confirm",
"notifyDone": "All set!",
"notifyDoneIntro": "You will now get the round emails."
}
},
"more": {
@@ -328,6 +333,31 @@
"confirmStop": "Really stop? Tap again",
"locked": "This doesn’t work after signing in by mail. Sign in with your passkey.",
"error": "That didn’t work. Please try again."
},
"roundMails": {
"title": "Round emails",
"count": "{n, plural, =0 {Nobody gets emails yet} one {1 person gets emails} other {# people get emails}}",
"summary": "Invitation, reminders and “The plan is ready”",
"intro": "Add an address for each person – children too. They get a link to confirm; only then do emails go there.",
"notReady": "No email sending set up yet. That is under More › Send emails.",
"status": {
"active": "gets emails at {email}",
"pending": "waiting for confirmation",
"none": "no address",
"off": "unsubscribed"
},
"address": "Address for {name}",
"send": "Send confirmation",
"sent": "Confirmation on its way to {email}.",
"gets": "{name} gets round emails",
"remove": "Remove address",
"errors": {
"mailNotConfigured": "No email sending set up yet.",
"mailFailed": "The email could not be sent.",
"tooMany": "Too many attempts. Please wait an hour.",
"invalid": "Please check the address.",
"unknown": "That didn’t work. Please try again."
}
}
},
"nav": {
@@ -612,9 +642,12 @@
"more": "{what}: more",
"errors": {
"roundExists": "A round is already running.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"deadlinePast": "The deadline is in the past. Please pick a later time."
},
"save": "Save"
"save": "Save",
"deadline": "Wishes until",
"deadlineHint": "Everyone can wish until then. Everyone with an address gets an invitation and two reminders before the end. Leave empty: no deadline."
},
"wish": {
"eyebrow": "Round",
@@ -667,7 +700,8 @@
"alternative": "Please pick another pool dish nobody has wished for yet.",
"protected": "This is someone's dish — there is no veto against it.",
"repeat": "That was already your dish last round. Pick a different one this time.",
"notWished": "Wish for the dish first, then you can make it yours."
"notWished": "Wish for the dish first, then you can make it yours.",
"closed": "The deadline has passed – wishing is closed."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
@@ -688,7 +722,13 @@
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new",
"mineToggle": "{title} as my dish",
"mineUntoggle": "{title} no longer my dish"
"mineUntoggle": "{title} no longer my dish",
"countdown": {
"until": "Wishes until {when}",
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h {minutes} min left",
"closed": "The deadline has passed – wishing is closed."
},
"deadlinePassed": "The deadline for wishes has passed. The plan is coming soon."
},
"kids": {
"title": "Who are you?",
@@ -1211,6 +1251,12 @@
"lead": "If you can read this, foodplanhero can send mail.",
"button": "Open foodplanhero",
"note": "This mail was sent with the setting under More › Sending mail."
},
"notify": {
"subject": "Confirm meal round emails",
"lead": "This address was added at foodplanhero for the meal round emails: an invitation when you plan, and a reminder before the end. Please confirm it. The link is valid for 7 days.",
"button": "Confirm address",
"note": "Not expected? Just ignore this email – without confirmation nothing is sent."
}
},
"calendar": {
@@ -1218,5 +1264,56 @@
"cook": "{name} is cooking",
"portions": "{n, plural, one {# portion} other {# portions}}",
"open": "Open in foodplanhero: {url}"
},
"roundMail": {
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h left",
"until": "Wishes until {when}",
"unsubscribe": "No more round emails",
"footer": "foodplanhero · {household}",
"teaserTitle": "Maybe this time?",
"button": "Make a wish",
"points": {
"tokens": "You have {n, plural, one {# token} other {# tokens}} – each one is a wish.",
"mine": "Tap the heart: your dish is sure to make the table, no veto can strike it.",
"shopping": "Shopping is on {day}, with {n, plural, one {# hot meal} other {# hot meals}} planned."
},
"invite": {
"subject": "What’s for dinner this week? You decide too",
"preheader": "The new round is open – make a wish.",
"title": "Hey {name}, the new round is open!",
"lead": "Meals for the next few days are coming up. Wish for what ends up on the table – with a bit of luck your favourite is among them."
},
"remind24": {
"subject": "24 hours left: what would you like to eat?",
"preheader": "Wishing ends this time tomorrow.",
"title": "{name}, your wish is still missing",
"lead": "Tomorrow wishing ends. Otherwise the others decide for you"
},
"remind2": {
"subject": "Last call: 2 hours left to wish",
"preheader": "Almost closed.",
"title": "Last call, {name}!",
"lead": "In two hours it’s decided what’s for dinner. One tap is enough."
},
"plan": {
"subject": "The plan is ready",
"preheader": "{n, plural, one {# dish} other {# dishes}} for the next few days.",
"title": "{name}, the plan is ready!",
"lead": "This is what’s coming to the table in the next few days.",
"leadShopping": "Shopping is on {day}. This is what’s coming to the table in the next few days.",
"listTitle": "The plan",
"cook": "cooking: {name}",
"button": "To the plan"
},
"unsubscribePage": {
"askTitle": "No more round emails?",
"askIntro": "You will no longer get invitations or reminders. An admin can switch it back on.",
"submit": "Unsubscribe",
"doneTitle": "Unsubscribed",
"doneIntro": "You will no longer get round emails.",
"invalidTitle": "This link is not valid",
"invalidIntro": "Please use the link from an email by foodplanhero.",
"error": "That didn’t work. Please try again."
}
}
}
+102 -5
View File
@@ -113,7 +113,12 @@
"toMore": "Continuar",
"expiredTitle": "Este enlace ya no es válido",
"expiredIntro": "Los enlaces por correo valen una vez y poco tiempo. Pide uno nuevo.",
"back": "Ir a entrar"
"back": "Ir a entrar",
"notifyTitle": "Confirm round emails",
"notifyIntro": "You will then get an email when a new meal round starts – with deadline and reminder.",
"notifySubmit": "Confirm",
"notifyDone": "All set!",
"notifyDoneIntro": "You will now get the round emails."
}
},
"more": {
@@ -328,6 +333,31 @@
"confirmStop": "¿Terminar de verdad? Toca otra vez",
"locked": "No funciona tras entrar por correo. Entra con tu passkey.",
"error": "No ha funcionado. Inténtalo de nuevo."
},
"roundMails": {
"title": "Round emails",
"count": "{n, plural, =0 {Nobody gets emails yet} one {1 person gets emails} other {# people get emails}}",
"summary": "Invitation, reminders and “The plan is ready”",
"intro": "Add an address for each person – children too. They get a link to confirm; only then do emails go there.",
"notReady": "No email sending set up yet. That is under More › Send emails.",
"status": {
"active": "gets emails at {email}",
"pending": "waiting for confirmation",
"none": "no address",
"off": "unsubscribed"
},
"address": "Address for {name}",
"send": "Send confirmation",
"sent": "Confirmation on its way to {email}.",
"gets": "{name} gets round emails",
"remove": "Remove address",
"errors": {
"mailNotConfigured": "No email sending set up yet.",
"mailFailed": "The email could not be sent.",
"tooMany": "Too many attempts. Please wait an hour.",
"invalid": "Please check the address.",
"unknown": "That didn’t work. Please try again."
}
}
},
"nav": {
@@ -612,9 +642,12 @@
"more": "{what}: more",
"errors": {
"roundExists": "A round is already running.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"deadlinePast": "The deadline is in the past. Please pick a later time."
},
"save": "Guardar"
"save": "Guardar",
"deadline": "Wishes until",
"deadlineHint": "Everyone can wish until then. Everyone with an address gets an invitation and two reminders before the end. Leave empty: no deadline."
},
"wish": {
"eyebrow": "Round",
@@ -667,7 +700,8 @@
"alternative": "Elige otro plato del pool que nadie haya deseado aún.",
"protected": "This is someone's dish — there is no veto against it.",
"repeat": "That was already your dish last round. Pick a different one this time.",
"notWished": "Wish for the dish first, then you can make it yours."
"notWished": "Wish for the dish first, then you can make it yours.",
"closed": "The deadline has passed – wishing is closed."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
@@ -688,7 +722,13 @@
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new",
"mineToggle": "{title} como mi plato",
"mineUntoggle": "{title} ya no es mi plato"
"mineUntoggle": "{title} ya no es mi plato",
"countdown": {
"until": "Wishes until {when}",
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h {minutes} min left",
"closed": "The deadline has passed – wishing is closed."
},
"deadlinePassed": "The deadline for wishes has passed. The plan is coming soon."
},
"kids": {
"title": "Who are you?",
@@ -1211,6 +1251,12 @@
"lead": "Si lees esto, foodplanhero puede enviar correos.",
"button": "Abrir foodplanhero",
"note": "Este correo usó el ajuste de Más › Envío de correos."
},
"notify": {
"subject": "Confirm meal round emails",
"lead": "This address was added at foodplanhero for the meal round emails: an invitation when you plan, and a reminder before the end. Please confirm it. The link is valid for 7 days.",
"button": "Confirm address",
"note": "Not expected? Just ignore this email – without confirmation nothing is sent."
}
},
"calendar": {
@@ -1218,5 +1264,56 @@
"cook": "Cocina {name}",
"portions": "{n, plural, one {# ración} other {# raciones}}",
"open": "Abrir en foodplanhero: {url}"
},
"roundMail": {
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h left",
"until": "Wishes until {when}",
"unsubscribe": "No more round emails",
"footer": "foodplanhero · {household}",
"teaserTitle": "Maybe this time?",
"button": "Make a wish",
"points": {
"tokens": "You have {n, plural, one {# token} other {# tokens}} – each one is a wish.",
"mine": "Tap the heart: your dish is sure to make the table, no veto can strike it.",
"shopping": "Shopping is on {day}, with {n, plural, one {# hot meal} other {# hot meals}} planned."
},
"invite": {
"subject": "What’s for dinner this week? You decide too",
"preheader": "The new round is open – make a wish.",
"title": "Hey {name}, the new round is open!",
"lead": "Meals for the next few days are coming up. Wish for what ends up on the table – with a bit of luck your favourite is among them."
},
"remind24": {
"subject": "24 hours left: what would you like to eat?",
"preheader": "Wishing ends this time tomorrow.",
"title": "{name}, your wish is still missing",
"lead": "Tomorrow wishing ends. Otherwise the others decide for you"
},
"remind2": {
"subject": "Last call: 2 hours left to wish",
"preheader": "Almost closed.",
"title": "Last call, {name}!",
"lead": "In two hours it’s decided what’s for dinner. One tap is enough."
},
"plan": {
"subject": "The plan is ready",
"preheader": "{n, plural, one {# dish} other {# dishes}} for the next few days.",
"title": "{name}, the plan is ready!",
"lead": "This is what’s coming to the table in the next few days.",
"leadShopping": "Shopping is on {day}. This is what’s coming to the table in the next few days.",
"listTitle": "The plan",
"cook": "cooking: {name}",
"button": "To the plan"
},
"unsubscribePage": {
"askTitle": "No more round emails?",
"askIntro": "You will no longer get invitations or reminders. An admin can switch it back on.",
"submit": "Unsubscribe",
"doneTitle": "Unsubscribed",
"doneIntro": "You will no longer get round emails.",
"invalidTitle": "This link is not valid",
"invalidIntro": "Please use the link from an email by foodplanhero.",
"error": "That didn’t work. Please try again."
}
}
}
+102 -5
View File
@@ -113,7 +113,12 @@
"toMore": "Continuer",
"expiredTitle": "Ce lien n’est plus valable",
"expiredIntro": "Les liens par e-mail ne servent qu’une fois et peu de temps. Demandes-en un nouveau.",
"back": "Vers la connexion"
"back": "Vers la connexion",
"notifyTitle": "Confirm round emails",
"notifyIntro": "You will then get an email when a new meal round starts – with deadline and reminder.",
"notifySubmit": "Confirm",
"notifyDone": "All set!",
"notifyDoneIntro": "You will now get the round emails."
}
},
"more": {
@@ -328,6 +333,31 @@
"confirmStop": "Vraiment arrêter ? Touchez encore",
"locked": "Impossible après une connexion par e-mail. Connectez-vous avec votre passkey.",
"error": "Cela n’a pas marché. Veuillez réessayer."
},
"roundMails": {
"title": "Round emails",
"count": "{n, plural, =0 {Nobody gets emails yet} one {1 person gets emails} other {# people get emails}}",
"summary": "Invitation, reminders and “The plan is ready”",
"intro": "Add an address for each person – children too. They get a link to confirm; only then do emails go there.",
"notReady": "No email sending set up yet. That is under More › Send emails.",
"status": {
"active": "gets emails at {email}",
"pending": "waiting for confirmation",
"none": "no address",
"off": "unsubscribed"
},
"address": "Address for {name}",
"send": "Send confirmation",
"sent": "Confirmation on its way to {email}.",
"gets": "{name} gets round emails",
"remove": "Remove address",
"errors": {
"mailNotConfigured": "No email sending set up yet.",
"mailFailed": "The email could not be sent.",
"tooMany": "Too many attempts. Please wait an hour.",
"invalid": "Please check the address.",
"unknown": "That didn’t work. Please try again."
}
}
},
"nav": {
@@ -612,9 +642,12 @@
"more": "{what}: more",
"errors": {
"roundExists": "A round is already running.",
"unknown": "That did not work. Please try again."
"unknown": "That did not work. Please try again.",
"deadlinePast": "The deadline is in the past. Please pick a later time."
},
"save": "Enregistrer"
"save": "Enregistrer",
"deadline": "Wishes until",
"deadlineHint": "Everyone can wish until then. Everyone with an address gets an invitation and two reminders before the end. Leave empty: no deadline."
},
"wish": {
"eyebrow": "Round",
@@ -667,7 +700,8 @@
"alternative": "Choisis un autre plat du pool que personne n'a encore souhaité.",
"protected": "This is someone's dish — there is no veto against it.",
"repeat": "That was already your dish last round. Pick a different one this time.",
"notWished": "Wish for the dish first, then you can make it yours."
"notWished": "Wish for the dish first, then you can make it yours.",
"closed": "The deadline has passed – wishing is closed."
},
"wishAction": "Wish:",
"unwishAction": "Take back wish:",
@@ -688,7 +722,13 @@
"vetoCount": "{n, plural, one {1 veto} other {# vetoes}}",
"jokerShort": "Something new",
"mineToggle": "{title} comme mon plat",
"mineUntoggle": "{title} n’est plus mon plat"
"mineUntoggle": "{title} n’est plus mon plat",
"countdown": {
"until": "Wishes until {when}",
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h {minutes} min left",
"closed": "The deadline has passed – wishing is closed."
},
"deadlinePassed": "The deadline for wishes has passed. The plan is coming soon."
},
"kids": {
"title": "Who are you?",
@@ -1211,6 +1251,12 @@
"lead": "Si tu lis ceci, foodplanhero peut envoyer des e-mails.",
"button": "Ouvrir foodplanhero",
"note": "Cet e-mail utilise le réglage sous Plus › Envoi d’e-mails."
},
"notify": {
"subject": "Confirm meal round emails",
"lead": "This address was added at foodplanhero for the meal round emails: an invitation when you plan, and a reminder before the end. Please confirm it. The link is valid for 7 days.",
"button": "Confirm address",
"note": "Not expected? Just ignore this email – without confirmation nothing is sent."
}
},
"calendar": {
@@ -1218,5 +1264,56 @@
"cook": "{name} cuisine",
"portions": "{n, plural, one {# portion} other {# portions}}",
"open": "Ouvrir dans foodplanhero : {url}"
},
"roundMail": {
"left": "{days, plural, =0 {} one {# day } other {# days }}{hours} h left",
"until": "Wishes until {when}",
"unsubscribe": "No more round emails",
"footer": "foodplanhero · {household}",
"teaserTitle": "Maybe this time?",
"button": "Make a wish",
"points": {
"tokens": "You have {n, plural, one {# token} other {# tokens}} – each one is a wish.",
"mine": "Tap the heart: your dish is sure to make the table, no veto can strike it.",
"shopping": "Shopping is on {day}, with {n, plural, one {# hot meal} other {# hot meals}} planned."
},
"invite": {
"subject": "What’s for dinner this week? You decide too",
"preheader": "The new round is open – make a wish.",
"title": "Hey {name}, the new round is open!",
"lead": "Meals for the next few days are coming up. Wish for what ends up on the table – with a bit of luck your favourite is among them."
},
"remind24": {
"subject": "24 hours left: what would you like to eat?",
"preheader": "Wishing ends this time tomorrow.",
"title": "{name}, your wish is still missing",
"lead": "Tomorrow wishing ends. Otherwise the others decide for you"
},
"remind2": {
"subject": "Last call: 2 hours left to wish",
"preheader": "Almost closed.",
"title": "Last call, {name}!",
"lead": "In two hours it’s decided what’s for dinner. One tap is enough."
},
"plan": {
"subject": "The plan is ready",
"preheader": "{n, plural, one {# dish} other {# dishes}} for the next few days.",
"title": "{name}, the plan is ready!",
"lead": "This is what’s coming to the table in the next few days.",
"leadShopping": "Shopping is on {day}. This is what’s coming to the table in the next few days.",
"listTitle": "The plan",
"cook": "cooking: {name}",
"button": "To the plan"
},
"unsubscribePage": {
"askTitle": "No more round emails?",
"askIntro": "You will no longer get invitations or reminders. An admin can switch it back on.",
"submit": "Unsubscribe",
"doneTitle": "Unsubscribed",
"doneIntro": "You will no longer get round emails.",
"invalidTitle": "This link is not valid",
"invalidIntro": "Please use the link from an email by foodplanhero.",
"error": "That didn’t work. Please try again."
}
}
}
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: foodplanhero (Plan. Cook. Smile.) — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.52 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.52" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.53 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.53" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: foodplanhero
description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
version: 26.11.52
version: 26.11.53
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.52'
versionName: '26.11.53'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# Mails for each round, with a deadline and countdown
v26.11.53: When a round opens, everyone gets a mail inviting them to wish, with the deadline and a countdown. A reminder follows 24 hours before the deadline and a last call 2 hours before, only for people who have not wished yet, and "The plan is ready" once it is approved. Admins enter the addresses under More, including for children; each address is confirmed by a link, and every mail can be unsubscribed. The deadline is set when the round opens; after it, wishing closes.
## Deutsch
v26.11.53: Wird eine Runde eröffnet, bekommen alle eine Mail zum Wünschen, mit Frist und Countdown. 24 Stunden vor der Frist folgt eine Erinnerung, 2 Stunden vorher der letzte Aufruf, beide nur an alle ohne Wunsch, und nach der Freigabe „Der Plan steht“. Die Adressen trägt der Admin unter Mehr ein, auch für Kinder; jede wird per Link bestätigt, und jede Mail lässt sich abbestellen. Die Frist wird beim Eröffnen gewählt, danach ist das Wünschen geschlossen.
+10 -3
View File
@@ -84,21 +84,28 @@ export default defineConfig({
{
// Anmelden per Mail-Link (26.11.40): braucht MAIL_TEST_DIR am Server ($LUNCH_DATA/mails).
name: "mail",
testMatch: /mail\.spec\.ts/,
testMatch: /(^|\/)mail\.spec\.ts$/,
dependencies: ["leiste"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
// Runde beenden/löschen, Tage, Kalender (26.11.45): beendet die Runde, deshalb spät.
name: "runde",
testMatch: /runde\.spec\.ts/,
testMatch: /(^|\/)runde\.spec\.ts$/,
dependencies: ["mail"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
// Mails zur Runde (26.11.53): Adressen, Einladung, Countdown, Abmelden, „Der Plan steht“.
name: "rundenmail",
testMatch: /rundenmail\.spec\.ts/,
dependencies: ["runde"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
name: "iphone-hell",
testMatch: /rundgang\.spec\.ts/,
dependencies: ["runde"],
dependencies: ["rundenmail"],
use: { ...iphone, colorScheme: "light", storageState: "e2e/.auth/kai.json" },
},
{
+41
View File
@@ -0,0 +1,41 @@
import { describe, expect, it } from "vitest";
import { dueMails, timeLeft, type RoundMailState } from "@/lib/round-mail-due";
const H = 3600 * 1000;
const D = new Date("2026-11-13T17:00:00Z");
const at = (hoursBefore: number) => new Date(D.getTime() - hoursBefore * H);
const base: RoundMailState = { status: "open", wishDeadline: D, inviteSentAt: null, remind24SentAt: null, remind2SentAt: null, planMailSentAt: null };
describe("round mails (26.11.53)", () => {
it("invites when the round opens, and not after the deadline", () => {
expect(dueMails(base, at(72))).toEqual({ send: ["invite"], skip: [] });
expect(dueMails({ ...base, wishDeadline: null }, at(72))).toEqual({ send: ["invite"], skip: [] });
expect(dueMails(base, at(-1))).toEqual({ send: [], skip: ["invite"] });
});
it("an invite close to the deadline skips reminders that would come right after it", () => {
expect(dueMails(base, at(10))).toEqual({ send: ["invite"], skip: ["remind24"] });
expect(dueMails(base, at(2.5))).toEqual({ send: ["invite"], skip: ["remind24", "remind2"] });
});
it("reminds 24 h and 2 h before, once each", () => {
const invited = { ...base, inviteSentAt: at(72) };
expect(dueMails(invited, at(30))).toEqual({ send: [], skip: [] });
expect(dueMails(invited, at(24))).toEqual({ send: ["remind24"], skip: [] });
const reminded = { ...invited, remind24SentAt: at(24) };
expect(dueMails(reminded, at(3))).toEqual({ send: [], skip: [] });
expect(dueMails(reminded, at(2))).toEqual({ send: ["remind2"], skip: [] });
expect(dueMails({ ...reminded, remind2SentAt: at(2) }, at(1))).toEqual({ send: [], skip: [] });
// Verpasster 24-h-Takt (Box aus): nur noch der letzte Aufruf.
expect(dueMails(invited, at(1.5))).toEqual({ send: ["remind2"], skip: ["remind24"] });
// Nach der Frist nichts mehr.
expect(dueMails(invited, at(-0.1))).toEqual({ send: [], skip: [] });
});
it("says the plan is ready once, only for rounds that invited", () => {
expect(dueMails({ ...base, status: "planned", inviteSentAt: at(72) }, at(-5))).toEqual({ send: ["plan"], skip: [] });
expect(dueMails({ ...base, status: "planned" }, at(-5))).toEqual({ send: [], skip: [] });
expect(dueMails({ ...base, status: "shopping", inviteSentAt: at(72), planMailSentAt: at(-1) }, at(-5))).toEqual({ send: [], skip: [] });
});
it("counts down", () => {
expect(timeLeft(D, at(52.5))).toEqual({ days: 2, hours: 4, minutes: 30 });
expect(timeLeft(D, at(-1))).toBeNull();
});
});
+134
View File
@@ -0,0 +1,134 @@
import { randomUUID } from "node:crypto";
import { mkdtempSync, readdirSync, readFileSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
vi.mock("next-intl/server", async () => {
const { createTranslator } = await import("next-intl");
const { readFileSync: read } = await import("node:fs");
return {
getTranslations: async ({ locale, namespace }: { locale: string; namespace: string }) =>
createTranslator({ locale, messages: JSON.parse(read(`messages/${locale}.json`, "utf8")), namespace: namespace as never }),
};
});
// Mails zur Runde (26.11.53): wer sie bekommt, wann, höchstens einmal; Frist schließt
// das Wünschen; Abmelde-Link; Bestätigung einer Adresse ohne Sitzung.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("round mails", () => {
const client = new pg.Client({ connectionString: url });
const h = randomUUID();
// Eigener Ordner im System-Temp; die Mails landen dort statt beim Mailweg.
const dir = mkdtempSync(path.join(tmpdir(), "rundenmail-"));
const ids: Record<string, string> = {};
let roundId = "";
let db: typeof import("@/lib/db");
let mails: typeof import("@/lib/round-mails");
let wishes: typeof import("@/lib/wishes");
let tokens: typeof import("@/lib/auth/mail-login");
let vault: typeof import("@/lib/vault");
const H = 3600 * 1000;
const deadline = new Date(Date.now() + 72 * H);
const sent = () =>
readdirSync(dir)
.filter((f) => f.endsWith(".json"))
.sort()
.map((f) => JSON.parse(readFileSync(path.join(dir, f), "utf8")) as { to: string; subject: string; html: string; text: string });
const as = <T>(fn: (c: pg.PoolClient) => Promise<T>) => db.withHousehold(h, fn);
beforeAll(async () => {
process.env.DATABASE_URL = url;
process.env.MAIL_TEST_DIR = dir;
process.env.APP_DATA_DIR = path.join(dir, "data");
await client.connect();
const ingredient = (await client.query("select id from ingredients limit 1")).rows[0].id;
ids.kai = (await seedHousehold(client, h, ingredient)).member;
db = await import("@/lib/db");
mails = await import("@/lib/round-mails");
wishes = await import("@/lib/wishes");
tokens = await import("@/lib/auth/mail-login");
vault = await import("@/lib/vault");
await db.withAuth(async (c) => {
if (!(await c.query("select 1 from instance")).rowCount) await c.query("insert into instance (origin, rp_id) values ('https://lunch.example', 'lunch.example')");
});
const key = await vault.seal("re_test");
await as(async (c) => {
await c.query("update household_mail set password_enc = $1", [key]);
await c.query("update members set notify_email = $2, notify_verified_at = now() where id = $1", [ids.kai, `kai-${h}@test.example`]);
const add = async (name: string, role: string, extra: string, params: unknown[]) =>
(
await c.query(
`insert into members (household_id, display_name, role${extra}) values ($1, $2, $3${params.map((_, i) => `, $${i + 4}`).join("")}) returning id`,
[h, name, role, ...params],
)
).rows[0].id as string;
ids.ben = await add("Ben", "child", ", notify_email, notify_verified_at", [`ben-${h}@test.example`, new Date()]);
ids.lea = await add("Lea", "teen", ", notify_email", [`lea-${h}@test.example`]); // nicht bestätigt
ids.max = await add("Max", "member", ", notify_email, notify_verified_at, notify_off", [`max-${h}@test.example`, new Date(), true]);
ids.gast = await add("Gast", "guest", ", notify_email, notify_verified_at", [`gast-${h}@test.example`, new Date()]);
await c.query("update rounds set status = 'done'");
roundId = (await c.query("insert into rounds (household_id, slots_count, default_portions, wish_deadline) values ($1, 3, 4, $2) returning id", [h, deadline])).rows[0].id;
});
});
afterAll(async () => {
await db.pool.end();
await client.end();
});
it("invites confirmed, subscribed people once — not unconfirmed, unsubscribed or guests", async () => {
const got = await mails.sendRoundMails(h, new Date());
expect(got).toEqual([{ kind: "invite", to: [`ben-${h}@test.example`, `kai-${h}@test.example`] }]);
const invite = sent().find((m) => m.to.startsWith("kai-"))!;
expect(invite.subject).toContain("Du entscheidest mit");
expect(invite.html).toMatch(/href="https?:\/\/[^"]+\/wuenschen"/);
expect(invite.html).toMatch(/\/mail\/abmelden#[0-9a-f-]{36}\./);
expect(invite.text).toMatch(/noch 2 Tage 23 Std\./);
expect(await mails.sendRoundMails(h, new Date())).toEqual([]);
});
it("reminds only those who have not wished yet", async () => {
const dish = await as(async (c) => (await c.query("select id from dishes limit 1")).rows[0].id as string);
await as((c) => wishes.addWish(c, h, ids.ben!, dish));
const got = await mails.sendRoundMails(h, new Date(deadline.getTime() - 23 * H));
expect(got).toEqual([{ kind: "remind24", to: [`kai-${h}@test.example`] }]);
expect(await mails.sendRoundMails(h, new Date(deadline.getTime() - 1.5 * H))).toEqual([{ kind: "remind2", to: [`kai-${h}@test.example`] }]);
});
it("closes wishing after the deadline", async () => {
await as((c) => c.query("update rounds set wish_deadline = now() - interval '1 minute' where id = $1", [roundId]));
const dish = await as(async (c) => (await c.query("select id from dishes limit 1")).rows[0].id as string);
await expect(as((c) => wishes.addWish(c, h, ids.kai!, dish))).rejects.toMatchObject({ reason: "closed" });
await expect(as((c) => wishes.removeWish(c, ids.ben!, dish))).rejects.toMatchObject({ reason: "closed" });
});
it("says the plan is ready after approval", async () => {
await as((c) => c.query("update rounds set status = 'planned' where id = $1", [roundId]));
const got = await mails.sendRoundMails(h, new Date());
expect(got[0]).toMatchObject({ kind: "plan" });
expect(sent().some((m) => m.subject.includes("Der Plan steht"))).toBe(true);
});
it("the unsubscribe link carries a check sum that cannot be forged", async () => {
const link = await mails.unsubscribeUrl("https://lunch.example", ids.kai!);
const [member, mac] = link.split("#")[1]!.split(".");
expect(member).toBe(ids.kai);
expect(await vault.macOk(`unsubscribe:${ids.kai}`, mac!)).toBe(true);
expect(await vault.macOk(`unsubscribe:${ids.ben}`, mac!)).toBe(false);
});
it("confirming an address for round mails starts no session", async () => {
const token = await db.withAuth((c) => tokens.createMailToken(c, { householdId: h, memberId: ids.lea!, purpose: "notify", email: `lea-${h}@test.example` }));
const hit = await db.withAuth((c) => tokens.consumeMailToken(c, token));
expect(hit).toMatchObject({ purpose: "notify", memberId: ids.lea });
const lea = await as(async (c) => (await c.query("select notify_verified_at is not null as ok from members where id = $1", [ids.lea])).rows[0].ok);
expect(lea).toBe(true);
const sessions = await as(async (c) => (await c.query("select count(*)::int as n from sessions where member_id = $1", [ids.lea])).rows[0].n);
expect(sessions).toBe(0);
});
});