Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d88e90a07 | ||
|
|
60ab3129ca | ||
|
|
f95956205b | ||
|
|
06a0cb9cf4 | ||
|
|
10831c7f65 | ||
|
|
582b4a0fca | ||
|
|
15d484c763 | ||
|
|
afdbf34b89 | ||
|
|
5952eda953 | ||
|
|
6f43b81f9b | ||
|
|
def3272442 | ||
|
|
92f852e335 | ||
|
|
cfb816b724 | ||
|
|
4e413fe600 | ||
|
|
68fd9dfc15 | ||
|
|
1d875fa02e |
No files matched your search
@@ -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" \
|
||||
(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
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
{
|
||||
"projekt": "lunch",
|
||||
"lauf": "2026-11-07",
|
||||
"auth_typ": "passkey+magic-link",
|
||||
"asvs_level": 2,
|
||||
"gesamturteil": "solide",
|
||||
"live_geprueft": true,
|
||||
"abdeckung": {
|
||||
"geprueft": 14,
|
||||
"erfuellt": 13,
|
||||
"verletzt": 0,
|
||||
"nicht_anwendbar": 0,
|
||||
"nicht_angestrebt": 1
|
||||
},
|
||||
"befunde": [
|
||||
{
|
||||
"id": "passkey-ohne-user-verification",
|
||||
"titel": "Passkey ohne Prüfung der Person",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"6.5.x"
|
||||
],
|
||||
"datei": "lib/auth/webauthn.ts",
|
||||
"angriff": "Ein Schlüssel ohne PIN genügt.",
|
||||
"fix": "userVerification required, requireUserVerification true",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "geraet-person-nicht-entfernbar",
|
||||
"titel": "Verlorenes Gerät und Personen nicht entfernbar",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"7.4.x",
|
||||
"7.5.x"
|
||||
],
|
||||
"datei": "app/(app)/mehr/page.tsx",
|
||||
"angriff": "Verlorenes Handy bleibt 180 Tage angemeldet.",
|
||||
"fix": "Passkey und Person entfernen, Sitzungen hängen am Passkey",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "kein-rueckweg-letzter-passkey",
|
||||
"titel": "Kein Rückweg bei Verlust des letzten Passkeys",
|
||||
"schweregrad": "mittel",
|
||||
"asvs": [
|
||||
"6.4.x"
|
||||
],
|
||||
"datei": "lib/auth/codes.ts",
|
||||
"angriff": "Haushalt verloren, wenn das einzige Gerät weg ist.",
|
||||
"fix": "Wiederherstellungscode in /app/data",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "bremse-xff-umgehbar",
|
||||
"titel": "Bremse über X-Forwarded-For umgehbar",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.1"
|
||||
],
|
||||
"datei": "lib/auth/request.ts",
|
||||
"angriff": "Je Versuch neue vorgetäuschte Adresse.",
|
||||
"fix": "gemeinsamer Topf je Bremse",
|
||||
"belegt_durch": "live",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "kein-anmeldeprotokoll",
|
||||
"titel": "Anmeldungen werden nicht protokolliert",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"16.x"
|
||||
],
|
||||
"datei": "lib/auth/",
|
||||
"angriff": "Missbrauch bleibt unbemerkt.",
|
||||
"fix": "Protokolltabelle mit Arbeitspaket 2",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "sitzung-ohne-hoechstdauer",
|
||||
"titel": "Sitzung ohne absolute Höchstdauer",
|
||||
"schweregrad": "info",
|
||||
"asvs": [
|
||||
"7.3.2"
|
||||
],
|
||||
"datei": "lib/auth/session.ts",
|
||||
"angriff": "Gestohlener Keks bleibt gültig, solange benutzt.",
|
||||
"fix": "feste Obergrenze erwägen",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "keine-csp-hsts",
|
||||
"titel": "Keine CSP, HSTS ungeklärt",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"3.4.x"
|
||||
],
|
||||
"datei": "next.config.ts",
|
||||
"angriff": "Härtung gegen XSS und Downgrade fehlt.",
|
||||
"fix": "CSP mit Nonces, HSTS auf der Box prüfen",
|
||||
"belegt_durch": "live",
|
||||
"status": "offen"
|
||||
},
|
||||
{
|
||||
"id": "mail-versand-flutbar",
|
||||
"titel": "Mail-Kontingent und Postfach ließen sich fluten",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.1",
|
||||
"6.6.3"
|
||||
],
|
||||
"datei": "app/api/auth/mail/request/route.ts",
|
||||
"angriff": "Mit wechselnden IPs viele Links an eine bekannte Adresse, Resend-Kontingent verbraucht.",
|
||||
"fix": "Je Adresse 3/15 min und 10/Tag, gemeinsamer Topf 30/h",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-adresse-aufzaehlbar",
|
||||
"titel": "Vergebene Adressen ließen sich beim Eintragen erkennen",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"6.3.7"
|
||||
],
|
||||
"datei": "app/api/me/email/route.ts",
|
||||
"angriff": "Angemeldete Person prüft fremde Adressen auf Konten, auch haushaltsübergreifend.",
|
||||
"fix": "Gleiche Antwort; Link greift bei vergebener Adresse nicht",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-sitzung-ueberlebt-adresse",
|
||||
"titel": "Mail-Sitzungen überlebten das Entfernen der Adresse",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"7.4.x"
|
||||
],
|
||||
"datei": "app/api/me/email/route.ts",
|
||||
"angriff": "Wer das Postfach mitliest, bleibt angemeldet, obwohl die Adresse entfernt wurde.",
|
||||
"fix": "Adresse entfernen/ändern beendet Sitzungen via mail",
|
||||
"belegt_durch": "test",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-sitzung-zu-lang",
|
||||
"titel": "Mail-Sitzungen lebten 180 Tage",
|
||||
"schweregrad": "niedrig",
|
||||
"asvs": [
|
||||
"7.3.x"
|
||||
],
|
||||
"datei": "lib/auth/session.ts",
|
||||
"angriff": "Ein einmal geöffneter Link hält ein halbes Jahr.",
|
||||
"fix": "30 Tage gleitend für via mail",
|
||||
"belegt_durch": "code",
|
||||
"status": "behoben"
|
||||
},
|
||||
{
|
||||
"id": "mail-link-nicht-geraetegebunden",
|
||||
"titel": "Mail-Link nicht an das anfragende Gerät gebunden",
|
||||
"schweregrad": "info",
|
||||
"asvs": [
|
||||
"6.6.2"
|
||||
],
|
||||
"datei": "lib/auth/mail-login.ts",
|
||||
"angriff": "Wer den Link hat, meldet sich an — auch auf einem anderen Gerät.",
|
||||
"fix": "Bewusst: Link soll auch auf anderem Gerät gehen; 15 min, einmal, nur Anmelden",
|
||||
"belegt_durch": "code",
|
||||
"status": "akzeptiert"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -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.38 — 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
|
||||
@@ -18,9 +18,13 @@
|
||||
> Führung (26.11.27), Präsentationsmodus und Küchendisplay (26.11.28),
|
||||
> lange Bons und Aldi (26.11.29), „Mein Gericht“ (26.11.30), Bons „nicht zum Kochen“
|
||||
> (26.11.33), foodplanhero für Maike (26.11.35), eine Schrift (26.11.37), Produktgruppen,
|
||||
> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015). Offen ist der
|
||||
> Magic Link (braucht SMTP).
|
||||
> **Letzte Aktualisierung:** 7. November 2026
|
||||
> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015), Löffel und Gebinde
|
||||
> (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), 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
@@ -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.38
|
||||
version: 26.11.53
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -61,7 +61,7 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.38'
|
||||
versionName: '26.11.53'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
|
||||
@@ -4,6 +4,7 @@ import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { ShoppingList } from "@/components/shopping/shopping-list";
|
||||
import { StorePicker } from "@/components/shopping/store-picker";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { aiFor } from "@/lib/ai-settings";
|
||||
import { requireAdult } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { currentRound } from "@/lib/rounds";
|
||||
@@ -37,7 +38,7 @@ export default async function ShoppingPage() {
|
||||
</Link>
|
||||
{data.chains.length ? <StorePicker chains={data.chains} /> : null}
|
||||
{"items" in data && data.items ? (
|
||||
<ShoppingList initial={data.items} aisles={data.aisles} me={session.displayName} />
|
||||
<ShoppingList initial={data.items} aisles={data.aisles} me={session.displayName} canRecord={!!(await aiFor(session.householdId))?.speechModel} />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3 rounded-2xl border border-border p-4">
|
||||
<p>{data.round ? t("notYet") : t("noRound")}</p>
|
||||
|
||||
@@ -4,11 +4,18 @@ import { DishForm } from "@/components/dishes/dish-form";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { getDish } from "@/lib/dishes";
|
||||
import { fromBase, niceQty, type BaseUnit, type DisplayUnit } from "@/lib/units";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Bearbeiten zeigt die Mengen für vier Portionen (oder was man dort einträgt).
|
||||
const PORTIONS = 4;
|
||||
// Bearbeiten zeigt die Mengen für so viele Portionen, wie das Rezept eingegeben wurde
|
||||
// (26.11.49); ältere Gerichte für vier. Gerundet, wie man es tippen würde.
|
||||
const OLDER = 4;
|
||||
|
||||
function amountIn(qty: number, unit: BaseUnit, display: DisplayUnit | null, packSize: number | null) {
|
||||
const n = display ? fromBase(qty, display, unit, packSize) : null;
|
||||
return n === null ? { qty: niceQty(qty, unit), unit } : { qty: niceQty(n, display!), unit: display as string };
|
||||
}
|
||||
|
||||
export default async function EditDishPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
@@ -19,6 +26,7 @@ export default async function EditDishPage({ params }: { params: Promise<{ id: s
|
||||
const t = await getTranslations("dishes");
|
||||
const dish = await withHousehold(session.householdId, (c) => getDish(c, id, locale));
|
||||
if (!dish) notFound();
|
||||
const portions = dish.recipePortions ?? OLDER;
|
||||
return (
|
||||
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
|
||||
<header className="flex flex-col gap-1">
|
||||
@@ -29,15 +37,16 @@ export default async function EditDishPage({ params }: { params: Promise<{ id: s
|
||||
initial={{
|
||||
id: dish.id,
|
||||
title: dish.title,
|
||||
portions: PORTIONS,
|
||||
portions,
|
||||
base: dish.base,
|
||||
tags: dish.tags,
|
||||
effortMinutes: dish.effortMinutes,
|
||||
isTrial: dish.isTrial,
|
||||
sourceUrl: dish.sourceUrl,
|
||||
ingredients: dish.ingredients.map((i) => ({
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit },
|
||||
qty: i.qtyPerPortion * PORTIONS,
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit, kitchenUnit: i.kitchenUnit, packKind: i.packKind, packSize: i.kindSize, sizes: i.sizes },
|
||||
// Im Maß, in dem sie eingegeben wurde: „2 EL“, „1 Dose“ (26.11.39).
|
||||
...amountIn(i.qtyPerPortion * portions, i.unit, i.displayUnit, i.packSize),
|
||||
note: i.note,
|
||||
product: i.product,
|
||||
})),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ChevronLeft, MonitorPlay } from "lucide-react";
|
||||
import { TrialNote } from "@/components/dishes/trial-note";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
@@ -50,11 +51,11 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
|
||||
.join(" · ");
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex max-w-2xl flex-col gap-5 pb-6">
|
||||
<main className="mx-auto flex max-w-md flex-col gap-5 pb-6">
|
||||
<div className="relative aspect-[4/3] overflow-hidden sm:mx-4 sm:mt-4 sm:rounded-2xl">
|
||||
<DishPhoto dishId={dish.id} photo={dish.photo} />
|
||||
<Link
|
||||
href="/gerichte"
|
||||
href={dish.isTrial ? "/gerichte?ansicht=ausprobieren" : "/gerichte"}
|
||||
aria-label={t("title")}
|
||||
className="absolute left-3 top-3 flex size-11 items-center justify-center rounded-full bg-background/90 text-foreground"
|
||||
>
|
||||
@@ -75,6 +76,7 @@ export default async function DishPage({ params }: { params: Promise<{ id: strin
|
||||
) : null}
|
||||
</header>
|
||||
{photos.length ? <PhotoGallery dishId={dish.id} title={dish.title} photos={photos} canManage={canWrite} /> : null}
|
||||
{dish.isTrial ? <TrialNote id={dish.id} canWrite={canWrite} /> : null}
|
||||
{canWrite ? <DishActions id={dish.id} /> : null}
|
||||
{dish.steps.length || dish.ingredients.length ? (
|
||||
<Link
|
||||
|
||||
@@ -47,7 +47,7 @@ export default async function DishesPage({ searchParams }: { searchParams: Promi
|
||||
[d.effortMinutes ? t("minutes", { n: d.effortMinutes }) : null, d.base ? t(`bases.${d.base}`) : null, cost(d.id)].filter(Boolean).join(" · ");
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex max-w-2xl flex-col gap-5 px-4 py-6">
|
||||
<main className="mx-auto flex max-w-md flex-col gap-5 px-4 py-6">
|
||||
<header className="flex items-end justify-between gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<p className="eyebrow">{t("eyebrow")}</p>
|
||||
@@ -83,9 +83,9 @@ export default async function DishesPage({ searchParams }: { searchParams: Promi
|
||||
</nav>
|
||||
|
||||
{dishes.length ? (
|
||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
<ul className="grid grid-cols-2 gap-3">
|
||||
{dishes.map((d) => (
|
||||
<li key={d.id}>
|
||||
<li key={d.id} className="h-full">
|
||||
<DishTile id={d.id} title={d.title} photo={d.photo} meta={meta(d)} />
|
||||
</li>
|
||||
))}
|
||||
@@ -107,7 +107,7 @@ export default async function DishesPage({ searchParams }: { searchParams: Promi
|
||||
href="/gerichte/hinzufuegen"
|
||||
className={cn(
|
||||
buttonVariants({ size: "lg" }),
|
||||
"fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] right-4 z-10 shadow-lg",
|
||||
"kb-shift fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] right-[max(1rem,calc((100vw-28rem)/2+1rem))] z-10 shadow-lg",
|
||||
)}
|
||||
>
|
||||
<Plus aria-hidden />
|
||||
|
||||
@@ -4,13 +4,16 @@ import { requireSession } from "@/lib/auth/session";
|
||||
// Alles hier drin verlangt eine Sitzung. Die Prüfung steht im Layout und
|
||||
// zusätzlich in jeder Seite, die Daten liest (requireSession) — Layouts
|
||||
// werden beim Navigieren nicht jedes Mal neu ausgeführt.
|
||||
// Jede Seite steht in einer Spalte wie am Handy, auch am Desktop (max-w-md; Kai,
|
||||
// 9.11.2026). Nur Küchendisplay, Präsentation und Kochmodus im Querformat sind breiter.
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export default async function AppLayout({ children }: { children: React.ReactNode }) {
|
||||
const session = await requireSession();
|
||||
return (
|
||||
<>
|
||||
<div className="pb-[calc(3.5rem+env(safe-area-inset-bottom))]">{children}</div>
|
||||
{/* Oben Platz für die Statusleiste des iPhones in der Web-App (26.11.44); im Browser 0. */}
|
||||
<div className="pb-[calc(3.5rem+env(safe-area-inset-bottom))] pt-[env(safe-area-inset-top)]">{children}</div>
|
||||
<AppNav variant={session.role === "child" ? "child" : session.role === "teen" ? "teen" : "adult"} />
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { MailSettings } from "@/components/more/mail-settings";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { loadMail, RESEND } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Mails verschicken (26.11.40), nur für Admins; per Mail-Link angemeldet nur lesen.
|
||||
export default async function MailSettingsPage() {
|
||||
const session = await requireSession();
|
||||
if (session.role !== "admin") redirect("/mehr");
|
||||
const t = await getTranslations("more.mailSettings");
|
||||
const { stored, me } = await withHousehold(session.householdId, async (c) => ({
|
||||
stored: await loadMail(c),
|
||||
me: (await c.query("select email from members where id = $1", [session.memberId])).rows[0]?.email as string | null,
|
||||
}));
|
||||
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>
|
||||
{session.via === "mail" ? (
|
||||
<p className="rounded-xl border border-border px-4 py-3 text-sm">{(await getTranslations("auth.errors"))("mailSession")}</p>
|
||||
) : (
|
||||
<MailSettings
|
||||
me={me}
|
||||
current={
|
||||
stored
|
||||
? { host: stored.host, port: stored.port, secure: stored.secure, username: stored.username, fromAddress: stored.fromAddress, fromName: stored.fromName, hasPassword: !!stored.passwordEnc }
|
||||
: null
|
||||
}
|
||||
defaults={{ ...RESEND, fromAddress: "hallo@foodplanhero.de", fromName: "foodplanhero", hasPassword: false }}
|
||||
/>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
+67
-4
@@ -12,6 +12,9 @@ import { getDedication, photoVersion } from "@/lib/dedication";
|
||||
import { aiFor } from "@/lib/ai-settings";
|
||||
import { InstallHint } from "@/components/install-hint";
|
||||
import { BudgetSettings } from "@/components/more/budget-settings";
|
||||
import { MailSignIn } from "@/components/more/mail-sign-in";
|
||||
import { CalendarSettings } from "@/components/more/calendar-settings";
|
||||
import { can, WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { isLocale } from "@/lib/locale";
|
||||
|
||||
@@ -30,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, 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 = (
|
||||
@@ -46,7 +49,25 @@ export default async function MorePage() {
|
||||
)
|
||||
).rows;
|
||||
const money = (await client.query("select budget_per_round::float as budget, expensive_per_slots as per, currency from households")).rows[0];
|
||||
return { members, passkeys, founder, kids, kidDevices, money, dedication: await getDedication(client) };
|
||||
// Anmelden per Mail (26.11.40): bestätigte Adresse, offene Bestätigung, eingerichteter Versand.
|
||||
const me = (await client.query("select email, email_verified_at is not null as verified from members where id = $1", [session.memberId])).rows[0];
|
||||
const pending = (
|
||||
await client.query(
|
||||
"select email from mail_tokens where member_id = $1 and purpose = 'verify' and used_at is null and expires_at > now() order by created_at desc limit 1",
|
||||
[session.memberId],
|
||||
)
|
||||
).rows[0]?.email as string | undefined;
|
||||
const sending = (await client.query("select from_address from household_mail where password_enc is not null")).rows[0]?.from_address as string | undefined;
|
||||
const mail = { verified: me?.verified ? (me.email as string) : null, pending: pending ?? null, sending: sending ?? null };
|
||||
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 };
|
||||
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" });
|
||||
@@ -87,7 +108,7 @@ export default async function MorePage() {
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("invitePerson")} id="einladen">
|
||||
<InvitePerson />
|
||||
{session.via === "mail" ? <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("mail.locked")}</p> : <InvitePerson />}
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
@@ -105,9 +126,15 @@ export default async function MorePage() {
|
||||
</ul>
|
||||
{passkeys.length > 1 ? <p className="text-sm text-muted-foreground">{t("removeHint")}</p> : null}
|
||||
<h3 className="text-sm font-medium">{t("addDevice")}</h3>
|
||||
<AddDevice />
|
||||
{session.via === "mail" ? <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("mail.locked")}</p> : <AddDevice />}
|
||||
</Section>
|
||||
|
||||
{can(WITH_PASSKEY, session.role) ? (
|
||||
<Section title={t("mail.title")} id="mail">
|
||||
<MailSignIn verified={mail.verified} pending={mail.pending} locked={session.via === "mail"} />
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<>
|
||||
<Section title={t("kids.title")}>
|
||||
@@ -122,6 +149,42 @@ export default async function MorePage() {
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("calendar.title")} id="kalender">
|
||||
<CalendarSettings active={calendar.active} mealTime={calendar.time} mealMinutes={calendar.minutes} locked={session.via === "mail"} />
|
||||
</Section>
|
||||
) : null}
|
||||
|
||||
{session.role === "admin" ? (
|
||||
<Section title={t("mail.sendingTitle")} id="mails">
|
||||
<Link
|
||||
href="/mehr/mail"
|
||||
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>{mail.sending ? t("mail.sendingReady", { from: mail.sending }) : t("mail.sendingNotReady")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("mail.sendingSummary")}</span>
|
||||
</span>
|
||||
<ChevronRight aria-hidden className="size-5 text-muted-foreground" />
|
||||
</Link>
|
||||
</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
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+6
-3
@@ -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";
|
||||
@@ -17,7 +18,7 @@ import { withHousehold } from "@/lib/db";
|
||||
import { currentRound } from "@/lib/rounds";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { budget, favorites, roundWishes } from "@/lib/wishes";
|
||||
import { planSlots } from "@/lib/plan";
|
||||
import { dayLabel, planSlots } from "@/lib/plan";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -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) => (
|
||||
@@ -188,6 +190,7 @@ async function FamilyWishes({
|
||||
|
||||
async function PlanToday({ slots, adult, cook }: { slots: Awaited<ReturnType<typeof planSlots>>; adult: boolean; cook: boolean }) {
|
||||
const t = await getTranslations("today");
|
||||
const locale = await getLocale();
|
||||
const next = slots.find((s) => s.dishId && !s.cookedAt);
|
||||
return (
|
||||
<>
|
||||
@@ -200,7 +203,7 @@ async function PlanToday({ slots, adult, cook }: { slots: Awaited<ReturnType<typ
|
||||
<p className="eyebrow">{t("next")}</p>
|
||||
<h2 className="text-3xl leading-snug">{next.title}</h2>
|
||||
<p className="text-muted-foreground">
|
||||
{[t("portions", { n: next.portions }), next.cookName ? t("cook", { name: next.cookName }) : null].filter(Boolean).join(" · ")}
|
||||
{[dayLabel(next.plannedDay, locale), t("portions", { n: next.portions }), next.cookName ? t("cook", { name: next.cookName }) : null].filter(Boolean).join(" · ")}
|
||||
</p>
|
||||
<Link href={`/kochen/${next.id}`} className={cn(buttonVariants({ size: "lg" }), "mt-2")}>
|
||||
<ChefHat aria-hidden />
|
||||
@@ -227,7 +230,7 @@ async function PlanToday({ slots, adult, cook }: { slots: Awaited<ReturnType<typ
|
||||
<span className="mr-2 text-sm text-muted-foreground">{i + 1}.</span>
|
||||
{s.title}
|
||||
</span>
|
||||
<span className="text-right text-sm text-muted-foreground">{s.cookName ?? ""}</span>
|
||||
<span className="text-right text-sm text-muted-foreground">{[dayLabel(s.plannedDay, locale), s.cookName].filter(Boolean).join(" · ")}</span>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
|
||||
@@ -2,6 +2,7 @@ import Link from "next/link";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { buttonVariants } from "@/components/ui/button";
|
||||
import { PlanBoard, type SlotCost } from "@/components/plan/plan-board";
|
||||
import { RoundActions } from "@/components/plan/round-actions";
|
||||
import { costOverview } from "@/lib/costs";
|
||||
import { requirePlanner } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
@@ -51,7 +52,13 @@ export default async function PlanPage() {
|
||||
) : null}
|
||||
</header>
|
||||
{"slots" in data && data.slots ? (
|
||||
<PlanBoard slots={data.slots} members={data.members} dishes={data.dishes} status={data.round!.status} money={data.money!} />
|
||||
<>
|
||||
<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, wishDeadline: data.round!.wishDeadline }}
|
||||
canDelete={!data.slots.some((s) => s.cookedAt)}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<div className="flex flex-col gap-3 rounded-2xl border border-border p-4">
|
||||
<p>{t("noRound")}</p>
|
||||
|
||||
@@ -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,20 +17,22 @@ 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 (
|
||||
<main className="mx-auto flex max-w-2xl flex-col gap-4 px-4 py-6">
|
||||
<main className="mx-auto flex max-w-md flex-col gap-4 px-4 py-6">
|
||||
<header className="flex flex-col gap-1">
|
||||
<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")}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { Slogan, Wordmark } from "@/components/brand/brand";
|
||||
import { MailLink } from "@/components/auth/mail-link";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Ziel des Links aus der Mail (26.11.40). Wie AuthShell, nur dass Titel und Text
|
||||
// erst im Browser feststehen (der Token steht hinter #).
|
||||
export default function MailLinkPage() {
|
||||
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>
|
||||
<MailLink />
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { KIDS_COOKIE } from "@/lib/auth/kids";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { AuthShell } from "@/components/auth/auth-shell";
|
||||
import { LoginButton } from "@/components/auth/login-button";
|
||||
import { MailLogin } from "@/components/auth/mail-login";
|
||||
import { getSession, isSetUp } from "@/lib/auth/session";
|
||||
import { photoVersion, publicDedication } from "@/lib/dedication";
|
||||
|
||||
@@ -19,6 +20,7 @@ export default async function SignInPage() {
|
||||
return (
|
||||
<AuthShell title={t("title")} intro={t("intro")} portrait={portrait}>
|
||||
<LoginButton />
|
||||
<MailLogin />
|
||||
{(await cookies()).has(KIDS_COOKIE) ? (
|
||||
<Link href="/kinder" className="mx-auto inline-flex min-h-11 items-center text-sm font-semibold underline-offset-4 hover:underline">
|
||||
{t("kids")}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { createMailToken, findMailMember, linkMail, normalizeEmail, sendInBackground } from "@/lib/auth/mail-login";
|
||||
import { clientIp } from "@/lib/auth/request";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ email: z.string().trim().max(200).email() });
|
||||
|
||||
// Link per Mail anfordern (26.11.40). Die Antwort ist immer dieselbe — ob es die
|
||||
// Adresse gibt, verrät sie nicht, auch nicht durch ihre Dauer (Versand im Hintergrund).
|
||||
export async function POST(request: Request) {
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
const result = await withAuth(async (client) => {
|
||||
const instance = await loadInstance(client);
|
||||
if (!instance) return fail("notSetUp", 409);
|
||||
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const email = normalizeEmail(parsed.data.email);
|
||||
if (
|
||||
(await tooManyAttempts(client, `mail:${clientIp(request)}`, 10, 15)) ||
|
||||
(await tooManyAttempts(client, `mail-to:${email}`, 3, 15)) ||
|
||||
(await tooManyAttempts(client, `mail-to-day:${email}`, 10, 24 * 60)) ||
|
||||
// Gemeinsamer Topf: hält Resend-Kontingent und Absender-Ruf, auch wenn jemand Adressen variiert.
|
||||
(await tooManyAttempts(client, "mail:*", 30, 60))
|
||||
) {
|
||||
return fail("tooMany", 429);
|
||||
}
|
||||
const member = await findMailMember(client, email);
|
||||
if (!member) return null;
|
||||
const token = await createMailToken(client, { householdId: member.householdId, memberId: member.id, purpose: "login", email });
|
||||
return { member, token, email, origin: instance.origin };
|
||||
});
|
||||
if (result instanceof Response) return result;
|
||||
if (result) {
|
||||
sendInBackground(result.member.householdId, linkMail({ purpose: "login", to: result.email, token: result.token, origin: result.origin, locale: result.member.locale }));
|
||||
}
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import { z } from "zod";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { fail, isSecure, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { consumeMailToken } from "@/lib/auth/mail-login";
|
||||
import { clientIp } from "@/lib/auth/request";
|
||||
import { startSession } from "@/lib/auth/session";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ token: z.string().min(20).max(100) });
|
||||
|
||||
// Einen Link aus der Mail einlösen: „login“ beginnt eine Sitzung (via mail — nur
|
||||
// anmelden, E-0006), „verify“ bestätigt die eigene Adresse.
|
||||
export async function POST(request: Request) {
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
return withAuth(async (client) => {
|
||||
const instance = await loadInstance(client);
|
||||
if (!instance) return fail("notSetUp", 409);
|
||||
if (!sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if ((await tooManyAttempts(client, `mail-verify:${clientIp(request)}`, 20, 15)) || (await tooManyAttempts(client, "mail-verify:*", 200, 15))) {
|
||||
return fail("tooMany", 429);
|
||||
}
|
||||
if (!parsed.success) return fail("expired", 410);
|
||||
const hit = await consumeMailToken(client, parsed.data.token);
|
||||
if (!hit) return fail("expired", 410);
|
||||
if (hit.purpose === "login") {
|
||||
await startSession(client, { id: hit.memberId, householdId: hit.householdId, viaMail: true }, request, isSecure(instance.origin));
|
||||
}
|
||||
return json({ purpose: hit.purpose });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// „In den Pool“ (26.11.41): ein Gericht aus „Ausprobieren“ zu den Stammgerichten.
|
||||
export async function POST(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
const r = await withHousehold(session.householdId, (c) =>
|
||||
c.query("update dishes set is_trial = false, updated_at = now() where id = $1 and archived_at is null", [id]),
|
||||
);
|
||||
return r.rowCount === 1 ? new Response(null, { status: 204 }) : fail("notFound", 404);
|
||||
}
|
||||
@@ -16,7 +16,8 @@ export async function PUT(request: Request, { params }: { params: Promise<{ id:
|
||||
await withHousehold(session.householdId, (c) => saveDish(c, session.householdId, session.memberId, body.data, id));
|
||||
return json({ id });
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidAmount) return fail("amount", 400);
|
||||
// Welche Zutat nicht passt, sagt die Antwort mit — das Formular markiert die Zeile (26.11.51).
|
||||
if (error instanceof InvalidAmount) return json({ error: "amount", ingredientId: error.message }, 400);
|
||||
if (error instanceof Error && error.message === "not found") return fail("notFound", 404);
|
||||
throw error;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ import { draftFromRecipe } from "@/lib/recipe-draft";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
/** Seiten je Rezept (26.11.48); dieselbe Zahl wie in components/dishes/photo-import.tsx. */
|
||||
const MAX_PAGES = 6;
|
||||
|
||||
// Kochbuchfoto → Entwurf. Das Bildmodell schreibt die Zutatenzeilen wörtlich
|
||||
// ab; Zuordnung und Umrechnung macht die App selbst (lib/recipe-import.ts).
|
||||
// Das Foto wird nicht gespeichert.
|
||||
@@ -17,8 +20,8 @@ export async function POST(request: Request) {
|
||||
const ai = await aiFor(session.householdId);
|
||||
if (!ai?.visionModel) return fail("aiNotConfigured", 409);
|
||||
const form = await request.formData().catch(() => null);
|
||||
const files = (form?.getAll("photos") ?? []).filter((f): f is File => f instanceof File).slice(0, 2);
|
||||
if (!files.length) return fail("photo", 400);
|
||||
const files = (form?.getAll("photos") ?? []).filter((f): f is File => f instanceof File);
|
||||
if (!files.length || files.length > MAX_PAGES) return fail("photo", 400);
|
||||
let images: string[];
|
||||
try {
|
||||
images = await Promise.all(files.map(imageForModel));
|
||||
@@ -30,9 +33,15 @@ export async function POST(request: Request) {
|
||||
try {
|
||||
recipe = recipeFromReply(
|
||||
await askJson(ai, "vision", RECIPE_PROMPT, [
|
||||
{ type: "text", text: "Read the recipe on these cookbook pages." },
|
||||
{
|
||||
type: "text",
|
||||
text:
|
||||
images.length > 1
|
||||
? `Read the recipe on these ${images.length} cookbook pages, in order; it may continue from one page to the next.`
|
||||
: "Read the recipe on this cookbook page.",
|
||||
},
|
||||
...images.map((url) => ({ type: "image_url" as const, image_url: { url } })),
|
||||
]),
|
||||
], { timeoutMs: 120_000 + 30_000 * (images.length - 1) }),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error instanceof AiNotConfigured) return fail("aiNotConfigured", 409);
|
||||
|
||||
@@ -29,7 +29,8 @@ export async function POST(request: Request) {
|
||||
if (body.data.imageUrl) await attachImage(session.householdId, id, session.memberId, body.data.imageUrl);
|
||||
return json({ id }, 201);
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidAmount) return fail("amount", 400);
|
||||
// Welche Zutat nicht passt, sagt die Antwort mit — das Formular markiert die Zeile (26.11.51).
|
||||
if (error instanceof InvalidAmount) return json({ error: "amount", ingredientId: error.message }, 400);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -1,30 +1,13 @@
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { AiNotConfigured, AiUnavailable, transcribe } from "@/lib/ai";
|
||||
import { aiFor } from "@/lib/ai-settings";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { json } from "@/lib/auth/http";
|
||||
import { transcribeUpload } from "@/lib/voice";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const MAX_BYTES = 25 * 1024 * 1024; // rund zehn Minuten Sprache
|
||||
|
||||
// Gericht einsprechen, Schritt 1: Aufnahme → Abschrift (Router „default-stt“ oder
|
||||
// eigenes Sprachmodell). Die Aufnahme wird nicht gespeichert.
|
||||
// Gericht einsprechen, Schritt 1: Aufnahme → Abschrift.
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
const form = await request.formData().catch(() => null);
|
||||
const audio = form?.get("audio");
|
||||
if (!(audio instanceof File) || audio.size === 0 || audio.size > MAX_BYTES || !/^(audio|video)\//.test(audio.type)) return fail("audio", 400);
|
||||
const ai = await aiFor(session.householdId);
|
||||
if (!ai?.speechModel) return fail("noSpeech", 409);
|
||||
try {
|
||||
const ext = audio.type.includes("mp4") || audio.type.includes("m4a") ? "m4a" : audio.type.includes("ogg") ? "ogg" : audio.type.includes("wav") ? "wav" : "webm";
|
||||
const text = await transcribe(ai, audio, `aufnahme.${ext}`, await getLocale());
|
||||
if (!text) return fail("empty", 422);
|
||||
return json({ text });
|
||||
} catch (error) {
|
||||
if (error instanceof AiUnavailable || error instanceof AiNotConfigured) return fail("aiUnavailable", 503);
|
||||
throw error;
|
||||
}
|
||||
const result = await transcribeUpload(request, session.householdId);
|
||||
return result instanceof Response ? result : json(result);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { getLocale } from "next-intl/server";
|
||||
import { z } from "zod";
|
||||
import { newCalendarToken, removeCalendarToken } from "@/lib/auth/calendar";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Kalender-Abo (26.11.45), nur für Admins und nie aus einer Mail-Sitzung: Der
|
||||
// Link zeigt den Plan jedem, der ihn hat.
|
||||
async function admin(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
return noMailSession(session) ?? session;
|
||||
}
|
||||
|
||||
/** Neuen Link erzeugen (auch: den alten ersetzen). Der Link kommt nur hier einmal heraus. */
|
||||
export async function POST(request: Request) {
|
||||
const session = await admin(request);
|
||||
if (isResponse(session)) return session;
|
||||
const locale = await getLocale();
|
||||
const token = await withHousehold(session.householdId, (c) => newCalendarToken(c, session.householdId, locale));
|
||||
const instance = await withAuth(loadInstance);
|
||||
const url = `${instance!.origin}/kalender/${token}.ics`;
|
||||
return json({ url }, 201);
|
||||
}
|
||||
|
||||
const timeInput = z.object({
|
||||
mealTime: z.string().regex(/^([01]\d|2[0-3]):[0-5]\d$/),
|
||||
mealMinutes: z.number().int().min(15).max(240),
|
||||
});
|
||||
|
||||
/** Essenszeit für die Termine. */
|
||||
export async function PATCH(request: Request) {
|
||||
const session = await admin(request);
|
||||
if (isResponse(session)) return session;
|
||||
const body = timeInput.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
await withHousehold(session.householdId, (c) =>
|
||||
c.query("update households set meal_time = $2, meal_minutes = $3 where id = $1", [session.householdId, body.data.mealTime, body.data.mealMinutes]),
|
||||
);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
/** Abo beenden: Der Link gilt nicht mehr. */
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await admin(request);
|
||||
if (isResponse(session)) return session;
|
||||
await withHousehold(session.householdId, (c) => removeCalendarToken(c, session.householdId));
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { can, WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, json, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { createInvitationBody } from "@/lib/auth/schemas";
|
||||
@@ -16,6 +17,8 @@ const DAYS = { person: 7, device: 1 } as const;
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
const body = createInvitationBody.safeParse(await readJson(request));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { guardWrite, noMailSession, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { createKidDeviceLink, LINK_HOURS } from "@/lib/auth/kids";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
@@ -11,6 +11,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = z.object({ label: z.string().trim().min(1).max(60), kind: z.enum(["kids", "kitchen"]).default("kids") }).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const instance = (await withAuth(loadInstance))!;
|
||||
@@ -22,6 +24,8 @@ export async function POST(request: Request) {
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = z.object({ id: z.string().uuid() }).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const removed = await withHousehold(session.householdId, (c) => c.query("delete from kid_devices where id = $1", [body.data.id]));
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { seal } from "@/lib/vault";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Mailweg des Haushalts (26.11.40), nur für Admins. Das Passwort (bei Resend der
|
||||
// API-Schlüssel) geht nur hinein: verschlüsselt gespeichert, nie zurückgegeben.
|
||||
const input = z.object({
|
||||
host: z.string().trim().min(1).max(200).regex(/^[a-z0-9.-]+$/i),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
secure: z.boolean(),
|
||||
username: z.string().trim().min(1).max(200),
|
||||
// undefined: bleibt; Text: neu; null: entfernen
|
||||
password: z.string().trim().min(1).max(500).nullable().optional(),
|
||||
fromAddress: z.string().trim().max(200).email(),
|
||||
fromName: z.string().trim().max(80).nullable().optional(),
|
||||
});
|
||||
|
||||
export async function PUT(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const body = input.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const d = body.data;
|
||||
const sealed = d.password ? await seal(d.password) : null;
|
||||
await withHousehold(session.householdId, (c) =>
|
||||
c.query(
|
||||
`insert into household_mail (household_id, host, port, secure, username, password_enc, from_address, from_name, updated_by)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
on conflict (household_id) do update set host = $2, port = $3, secure = $4, username = $5,
|
||||
password_enc = case when $10 then $6 else household_mail.password_enc end,
|
||||
from_address = $7, from_name = $8, updated_by = $9, updated_at = now()`,
|
||||
[session.householdId, d.host.toLowerCase(), d.port, d.secure, d.username, sealed, d.fromAddress.toLowerCase(), d.fromName || null, session.memberId, d.password !== undefined],
|
||||
),
|
||||
);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
await withHousehold(session.householdId, (c) => c.query("delete from household_mail"));
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from "zod";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { guardWrite, isResponse, noMailSession } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { buttonMail, MailNotConfigured, sendMail } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ to: z.string().trim().max(200).email() });
|
||||
|
||||
// „Testmail an mich“: prüft den Zugang mit einer echten Mail. Nur Admins, gebremst.
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, ["admin"]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const origin = await withAuth(async (client) => {
|
||||
if (await tooManyAttempts(client, `mail-test:${session.householdId}`, 5, 15)) return null;
|
||||
return (await loadInstance(client))!.origin;
|
||||
});
|
||||
if (!origin) return fail("tooMany", 429);
|
||||
const t = await getTranslations("mail.test");
|
||||
try {
|
||||
await sendMail(session.householdId, buttonMail({ to: parsed.data.to.toLowerCase(), subject: t("subject"), lead: t("lead"), button: t("button"), url: origin, note: t("note") }));
|
||||
} catch (error) {
|
||||
if (error instanceof MailNotConfigured) return fail("mailNotConfigured", 409);
|
||||
// Der Grund des Servers hilft beim Einrichten (falscher Schlüssel, Absender nicht bestätigt) — nur für Admins.
|
||||
return json({ error: "mailFailed", detail: String((error as Error).message).slice(0, 300) }, 502);
|
||||
}
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
@@ -11,6 +12,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
if (session.role !== "admin") return fail("forbidden", 403);
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { PLANNERS } from "@/lib/auth/roles";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { setPackSize } from "@/lib/ingredients";
|
||||
import { COUNT_UNITS } from "@/lib/units";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ size: z.number().positive().max(100000), unit: z.enum([...COUNT_UNITS, "g", "ml"]).optional() });
|
||||
|
||||
// Gebindegröße für den Haushalt (26.11.39): „bei uns hat die Dose 500 g“ — gilt für
|
||||
// alle Gerichte des Haushalts; ein Produkt mit Packung am Gericht geht vor.
|
||||
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await guardWrite(request, [...PLANNERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success || !/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
const size = Math.round(parsed.data.size * 1000) / 1000;
|
||||
const ok = await withHousehold(session.householdId, (c) => setPackSize(c, session.householdId, id, size, parsed.data.unit));
|
||||
return ok ? json({ size }) : fail("noPack", 404);
|
||||
}
|
||||
@@ -20,6 +20,11 @@ const view = (i: IngredientEntry, locale: string, all: IngredientEntry[], produc
|
||||
own: !!i.own,
|
||||
// Gemerktes Produkt des Haushalts — das Formular zeigt es gleich beim Wählen.
|
||||
product: products.get(i.id) ?? null,
|
||||
// Küchenmaß und Gebinde (26.11.39); die Größe mit der des Haushalts verrechnet.
|
||||
kitchenUnit: i.kitchenUnit ?? null,
|
||||
packKind: i.packKind ?? null,
|
||||
packSize: i.packSize ?? null,
|
||||
sizes: i.sizes ?? {},
|
||||
});
|
||||
|
||||
// Zutaten-Suche beim Tippen, in der Sprache der Person — mit den eigenen des
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
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 { WITH_PASSKEY } from "@/lib/auth/roles";
|
||||
import { tooManyAttempts } from "@/lib/auth/throttle";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
import { withAuth } from "@/lib/db";
|
||||
import { MailNotConfigured, sendMail } from "@/lib/mail";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ email: z.string().trim().max(200).email() });
|
||||
|
||||
// Die eigene Adresse für den Mail-Link (26.11.40): eintragen schickt eine
|
||||
// Bestätigung; erst der Link darin schaltet die Anmeldung per Mail frei.
|
||||
export async function PUT(request: Request) {
|
||||
const session = await guardWrite(request, [...WITH_PASSKEY]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success) return fail("invalid", 400);
|
||||
const email = normalizeEmail(parsed.data.email);
|
||||
const prepared = await withAuth(async (client) => {
|
||||
if (await tooManyAttempts(client, `mail-confirm:${session.memberId}`, 5, 60)) return fail("tooMany", 429);
|
||||
// Ob die Adresse schon jemandem gehört, sagt diese Antwort nicht (auch nicht über Haushalte
|
||||
// hinweg): Die Mail geht raus, der Link darin greift dann nicht (consumeMailToken).
|
||||
const locale = (await client.query("select locale from members where id = $1", [session.memberId])).rows[0]?.locale ?? null;
|
||||
const token = await createMailToken(client, { householdId: session.householdId, memberId: session.memberId, purpose: "verify", email });
|
||||
return { token, locale, origin: (await loadInstance(client))!.origin };
|
||||
});
|
||||
if (prepared instanceof Response) return prepared;
|
||||
try {
|
||||
await sendMail(session.householdId, await linkMail({ purpose: "verify", to: email, ...prepared }));
|
||||
} catch (error) {
|
||||
return fail(error instanceof MailNotConfigured ? "mailNotConfigured" : "mailFailed", 502);
|
||||
}
|
||||
return json({ pending: email });
|
||||
}
|
||||
|
||||
export async function DELETE(request: Request) {
|
||||
const session = await guardWrite(request, [...WITH_PASSKEY]);
|
||||
if (isResponse(session)) return session;
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
await withAuth(async (client) => {
|
||||
await client.query("update members set email = null, email_verified_at = null where id = $1", [session.memberId]);
|
||||
await client.query("update mail_tokens set used_at = now() where member_id = $1 and used_at is null", [session.memberId]);
|
||||
// Wer die Adresse entfernt, beendet auch jede Sitzung, die über sie begann.
|
||||
await client.query("delete from sessions where member_id = $1 and via = 'mail'", [session.memberId]);
|
||||
});
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { z } from "zod";
|
||||
import { noMailSession } from "@/lib/auth/guard";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
import { fail, readJson, sameOrigin } from "@/lib/auth/http";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
@@ -12,6 +13,8 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await getSession();
|
||||
if (!session) return fail("signedOut", 401);
|
||||
const mail = noMailSession(session);
|
||||
if (mail) return mail;
|
||||
const instance = await withAuth(loadInstance);
|
||||
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
|
||||
const body = z.object({ id: z.string().min(1).max(1024) }).safeParse(await readJson(request));
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -12,6 +12,8 @@ const change = z.object({
|
||||
portions: z.number().int().min(1).max(30).optional(),
|
||||
cookMemberId: id.nullable().optional(),
|
||||
locked: z.boolean().optional(),
|
||||
// Wochentag von Hand (26.11.45); null nimmt ihn weg.
|
||||
plannedDay: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).nullable().optional(),
|
||||
});
|
||||
|
||||
async function dishExists(c: import("pg").PoolClient, dishId: string) {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { currentRound, deleteRound, RoundHasCooked } from "@/lib/rounds";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Runde ganz löschen (26.11.45) — nur solange nichts gekocht ist. Wünsche,
|
||||
// Plan und Einkaufsliste gehen mit (on delete cascade).
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
return withHousehold(session.householdId, async (c) => {
|
||||
const round = await currentRound(c);
|
||||
if (!round) return fail("noRound", 409);
|
||||
try {
|
||||
await deleteRound(c, round.id);
|
||||
} catch (error) {
|
||||
if (error instanceof RoundHasCooked) return fail("cooked", 409);
|
||||
throw error;
|
||||
}
|
||||
return json({ ok: true });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { currentRound, endRound } from "@/lib/rounds";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Runde beenden (26.11.45): Gekochtes bleibt Geschichte, danach ist Platz für die nächste.
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
return withHousehold(session.householdId, async (c) => {
|
||||
const round = await currentRound(c);
|
||||
if (!round) return fail("noRound", 409);
|
||||
await endRound(c, round.id);
|
||||
return json({ ok: true });
|
||||
});
|
||||
}
|
||||
+23
-1
@@ -1,7 +1,10 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { openRound, RoundExists, roundInput } from "@/lib/rounds";
|
||||
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";
|
||||
|
||||
@@ -13,9 +16,28 @@ 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);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Einstellungen der laufenden Runde ändern (26.11.45). Vorhandene Gerichte bleiben;
|
||||
// die Einkaufsliste rechnet sich neu, wenn es sie schon gibt.
|
||||
export async function PATCH(request: Request) {
|
||||
const session = await guardWrite(request);
|
||||
if (isResponse(session)) return session;
|
||||
const body = roundInput.safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const locale = await getLocale();
|
||||
return withHousehold(session.householdId, async (c) => {
|
||||
const round = await currentRound(c);
|
||||
if (!round) return fail("noRound", 409);
|
||||
await updateRound(c, round.id, body.data);
|
||||
const next = await currentRound(c);
|
||||
if (next && next.status !== "open") await syncList(c, session.householdId, next, locale);
|
||||
return json({ ok: true });
|
||||
});
|
||||
}
|
||||
@@ -14,10 +14,13 @@ export async function PATCH(request: Request) {
|
||||
}
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const body = z.object({ label: z.string().trim().min(1).max(80) }).safeParse(await readJson(request));
|
||||
// Ein Posten getippt, oder mehrere auf einmal nach dem Einsprechen (26.11.46).
|
||||
const label = z.string().trim().min(1).max(80);
|
||||
const body = z.union([z.object({ label }), z.object({ labels: z.array(label).min(1).max(20) })]).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
const labels = "labels" in body.data ? body.data.labels : [body.data.label];
|
||||
return withShopping(request, async (c, round, session) => {
|
||||
await addManual(c, session.householdId, round.id, body.data.label);
|
||||
for (const l of labels) await addManual(c, session.householdId, round.id, l);
|
||||
return json({ ok: true }, 201);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { json } from "@/lib/auth/http";
|
||||
import { SHOPPERS } from "@/lib/auth/roles";
|
||||
import { splitSpoken } from "@/lib/spoken-list";
|
||||
import { transcribeUpload } from "@/lib/voice";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Einkaufsliste einsprechen (Kai, 8.11.2026): Abschrift → einzelne Posten. Kein
|
||||
// Sprachmodell zerlegt — die Regeln in lib/spoken-list.ts tun es, und auf die
|
||||
// Liste kommt erst, was die Person geprüft hat.
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, [...SHOPPERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const result = await transcribeUpload(request, session.householdId);
|
||||
if (result instanceof Response) return result;
|
||||
return json({ text: result.text, items: splitSpoken(result.text) });
|
||||
}
|
||||
@@ -10,10 +10,10 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
const session = await guardWrite(request, [...WISHERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const body = z.object({ dishId: z.string().uuid(), mine: z.boolean() }).safeParse(await readJson(request));
|
||||
const body = z.object({ dishId: z.string().uuid(), mine: z.boolean(), wish: z.boolean().optional() }).safeParse(await readJson(request));
|
||||
if (!body.success) return fail("invalid", 400);
|
||||
try {
|
||||
await withHousehold(session.householdId, (c) => setMine(c, session.memberId, body.data.dishId, body.data.mine));
|
||||
await withHousehold(session.householdId, (c) => setMine(c, session.memberId, body.data.dishId, body.data.mine, body.data.wish ? { wishIn: session.householdId } : {}));
|
||||
return json({ ok: true });
|
||||
} catch (error) {
|
||||
if (error instanceof WishRefused) return fail(error.reason, 409);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,12 @@
|
||||
--nav-space: 0px;
|
||||
}
|
||||
|
||||
/* Knopfleisten unten folgen der Korrektur der Navigation, wenn iOS nach der
|
||||
Tastatur zu kurz rechnet (lib/use-keyboard-nav.ts setzt --kb-shift, 26.11.41). */
|
||||
.kb-shift {
|
||||
translate: 0 var(--kb-shift, 0px);
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: light dark;
|
||||
-webkit-text-size-adjust: 100%;
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { householdForCalendar } from "@/lib/auth/calendar";
|
||||
import { clientIp } from "@/lib/auth/request";
|
||||
import { loadInstance } from "@/lib/auth/webauthn";
|
||||
import { buildCalendar, type CalendarEvent } from "@/lib/calendar";
|
||||
import { withAuth, withHousehold } from "@/lib/db";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Kalender-Abo (26.11.45): öffentlich, aber nur mit gültigem Link. Nur lesend,
|
||||
// nur Titel, Tag, Koch und Portionen — keine Zutaten, keine Wünsche.
|
||||
export async function GET(request: Request, { params }: { params: Promise<{ token: string }> }) {
|
||||
const raw = (await params).token.replace(/\.ics$/, "");
|
||||
const notFound = () => new Response("Not found", { status: 404, headers: { "cache-control": "no-store" } });
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(raw)) return notFound();
|
||||
const found = await householdForCalendar(raw, clientIp(request));
|
||||
if (found === "tooMany") return new Response("Too many requests", { status: 429, headers: { "retry-after": "900" } });
|
||||
if (!found) return notFound();
|
||||
|
||||
const instance = await withAuth(loadInstance);
|
||||
const { household, slots } = await withHousehold(found.id, async (c) => ({
|
||||
household: (
|
||||
await c.query("select name, to_char(meal_time, 'HH24:MI') as time, meal_minutes as minutes, calendar_locale as locale from households where id = $1", [found.id])
|
||||
).rows[0] as { name: string; time: string; minutes: number; locale: string },
|
||||
// Laufende Runde und was in den letzten 60 Tagen einen Tag hatte.
|
||||
slots: (
|
||||
await c.query(
|
||||
`select s.id, to_char(s.planned_day, 'YYYY-MM-DD') as day, s.portions, d.id as "dishId", d.title, m.display_name as cook
|
||||
from slots s join dishes d on d.id = s.dish_id left join members m on m.id = s.cook_member_id
|
||||
where s.planned_day is not null and s.planned_day >= current_date - 60
|
||||
order by s.planned_day, s.position`,
|
||||
)
|
||||
).rows as { id: string; day: string; portions: number; dishId: string; title: string; cook: string | null }[],
|
||||
}));
|
||||
const t = await getTranslations({ locale: household.locale, namespace: "calendar" });
|
||||
const events: CalendarEvent[] = slots.map((s) => ({
|
||||
uid: `${s.id}@foodplanhero`,
|
||||
day: s.day,
|
||||
start: household.time,
|
||||
minutes: household.minutes,
|
||||
summary: s.title,
|
||||
description: [s.cook ? t("cook", { name: s.cook }) : null, t("portions", { n: s.portions }), instance ? t("open", { url: `${instance.origin}/gerichte/${s.dishId}` }) : null]
|
||||
.filter(Boolean)
|
||||
.join("\n"),
|
||||
url: instance ? `${instance.origin}/gerichte/${s.dishId}` : null,
|
||||
}));
|
||||
return new Response(buildCalendar(t("name", { household: household.name }), events), {
|
||||
headers: {
|
||||
"content-type": "text/calendar; charset=utf-8",
|
||||
"content-disposition": 'inline; filename="foodplanhero.ics"',
|
||||
"cache-control": "private, max-age=900",
|
||||
},
|
||||
});
|
||||
}
|
||||
+4
-1
@@ -1,13 +1,14 @@
|
||||
import { ChefHat } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { redirect } from "next/navigation";
|
||||
import { getTranslations } from "next-intl/server";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
import { DishPhoto } from "@/components/dishes/dish-tile";
|
||||
import { AutoRefresh } from "@/components/kitchen/auto-refresh";
|
||||
import { currentKitchenDisplay } from "@/lib/auth/kids";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { kitchenOverview } from "@/lib/kitchen";
|
||||
import { dayLabel } from "@/lib/plan";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
@@ -19,6 +20,7 @@ export default async function KitchenPage() {
|
||||
const t = await getTranslations("kitchen");
|
||||
const { next, dishes } = await withHousehold(device.householdId, kitchenOverview);
|
||||
const [today, ...later] = next;
|
||||
const locale = await getLocale();
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh max-w-6xl flex-col gap-6 px-4 py-6 pt-[max(1.5rem,env(safe-area-inset-top))] landscape:px-8">
|
||||
@@ -41,6 +43,7 @@ export default async function KitchenPage() {
|
||||
<DishPhoto dishId={today.dishId} photo={today.photo} />
|
||||
</div>
|
||||
<div className="flex flex-col justify-center gap-2 p-5">
|
||||
{today.plannedDay ? <p className="font-semibold">{dayLabel(today.plannedDay, locale)}</p> : null}
|
||||
<p className="text-3xl leading-tight">{today.title}</p>
|
||||
<p className="text-muted-foreground">
|
||||
{today.cookName ? t("portionsCook", { n: today.portions, name: today.cookName }) : t("portions", { n: today.portions })}
|
||||
|
||||
+2
-1
@@ -1,3 +1,4 @@
|
||||
import { iconUrl } from "@/lib/icon-version";
|
||||
import type { Metadata, Viewport } from "next";
|
||||
import localFont from "next/font/local";
|
||||
import { NextIntlClientProvider } from "next-intl";
|
||||
@@ -36,7 +37,7 @@ export async function generateMetadata(): Promise<Metadata> {
|
||||
media: `(device-width: ${cw}px) and (device-height: ${ch}px) and (-webkit-device-pixel-ratio: ${dpr}) and (orientation: portrait)`,
|
||||
})),
|
||||
},
|
||||
icons: { icon: "/icon.svg", apple: "/apple-touch-icon.png" },
|
||||
icons: { icon: iconUrl("/icon.svg"), apple: iconUrl("/apple-touch-icon.png") },
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
+7
-6
@@ -1,3 +1,4 @@
|
||||
import { iconUrl } from "@/lib/icon-version";
|
||||
import type { MetadataRoute } from "next";
|
||||
import { getLocale, getTranslations } from "next-intl/server";
|
||||
|
||||
@@ -18,14 +19,14 @@ export default async function manifest(): Promise<MetadataRoute.Manifest> {
|
||||
theme_color: "#fdfcfe",
|
||||
// Lange auf das Symbol drücken: direkt zu Wünschen, Plan und Einkauf.
|
||||
shortcuts: [
|
||||
{ name: nav("wish"), url: "/wuenschen", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("plan"), url: "/plan", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("shopping"), url: "/einkauf", icons: [{ src: "/icon-192.png", sizes: "192x192" }] },
|
||||
{ name: nav("wish"), url: "/wuenschen", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
{ name: nav("plan"), url: "/plan", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
{ name: nav("shopping"), url: "/einkauf", icons: [{ src: iconUrl("/icon-192.png"), sizes: "192x192" }] },
|
||||
],
|
||||
icons: [
|
||||
{ src: "/icon-192.png", sizes: "192x192", type: "image/png" },
|
||||
{ src: "/icon-512.png", sizes: "512x512", type: "image/png" },
|
||||
{ src: "/icon-512-maskable.png", sizes: "512x512", type: "image/png", purpose: "maskable" },
|
||||
{ src: iconUrl("/icon-192.png"), sizes: "192x192", type: "image/png" },
|
||||
{ src: iconUrl("/icon-512.png"), sizes: "512x512", type: "image/png" },
|
||||
{ src: iconUrl("/icon-512-maskable.png"), sizes: "512x512", type: "image/png", purpose: "maskable" },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
|
||||
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.
|
||||
export function MailLink() {
|
||||
const t = useTranslations("auth");
|
||||
const router = useRouter();
|
||||
const [state, setState] = useState<State>({ kind: "loading" });
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
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 Purpose, token: m[2]! } : { kind: "expired" });
|
||||
}, []);
|
||||
|
||||
async function go() {
|
||||
if (state.kind !== "ready") return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/auth/mail/verify", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ token: state.token }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) {
|
||||
const { purpose } = await res.json();
|
||||
if (purpose === "login") router.replace("/");
|
||||
else setState({ kind: "verified", purpose });
|
||||
return;
|
||||
}
|
||||
if (res?.status === 410) return setState({ kind: "expired" });
|
||||
setError(res?.status === 429 ? "tooMany" : "unknown");
|
||||
}
|
||||
|
||||
if (state.kind === "loading") return null;
|
||||
if (state.kind === "expired") {
|
||||
return (
|
||||
<div className="flex flex-col items-center gap-4 text-center">
|
||||
<h1 className="text-balance text-4xl leading-tight">{t("mailLink.expiredTitle")}</h1>
|
||||
<p className="mx-auto max-w-[34ch] text-balance text-muted-foreground">{t("mailLink.expiredIntro")}</p>
|
||||
<Button asChild size="lg" className="self-stretch">
|
||||
<Link href="/anmelden">{t("mailLink.back")}</Link>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
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(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={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(`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(`mailLink.${key}Submit`)}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { Mail } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, 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";
|
||||
|
||||
// Link per Mail anfordern (26.11.40). Die Antwort sagt immer dasselbe — ob es die
|
||||
// Adresse gibt, verrät sie nicht.
|
||||
export function MailLogin() {
|
||||
const t = useTranslations("auth");
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [sent, setSent] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function submit(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/auth/mail/request", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ email }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) return setSent(true);
|
||||
const key = res ? ((await res.json().catch(() => ({}))).error as string | undefined) : undefined;
|
||||
setError(key === "tooMany" || key === "invalid" ? key : "unknown");
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<Button type="button" variant="outline" size="lg" onClick={() => setOpen(true)}>
|
||||
<Mail aria-hidden />
|
||||
{t("login.mailToggle")}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
if (sent) {
|
||||
return (
|
||||
<p role="status" className="mx-auto max-w-[34ch] text-balance rounded-xl border border-border px-4 py-3 text-center text-sm">
|
||||
{t("login.mailSent")}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<form onSubmit={submit} className="flex flex-col gap-3">
|
||||
<Label htmlFor={id}>{t("login.mailLabel")}</Label>
|
||||
<Input id={id} type="email" autoComplete="email" inputMode="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
<Button type="submit" size="lg" disabled={busy || !email.trim()}>
|
||||
<Mail aria-hidden />
|
||||
{busy ? t("working") : t("login.mailSubmit")}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -158,7 +158,7 @@ export function CookingMode({
|
||||
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" size="lg" disabled={index < 0} onClick={() => go(-1)} aria-label={t("back")}>
|
||||
<ChevronLeft aria-hidden />
|
||||
</Button>
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { Pause, Play, Timer as TimerIcon } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import type { Section } from "@/lib/recipe-style";
|
||||
import { timerFromText } from "@/lib/timer";
|
||||
import { formatQuantity, type BaseUnit } from "@/lib/units";
|
||||
import { type BaseUnit, type DisplayUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Gemeinsames von Kochmodus und Präsentation (26.11.28): Display an lassen,
|
||||
// Timer gegen die Uhr, Mengen in der Portionszahl.
|
||||
|
||||
export type Ingredient = { ingredientId: string; name: string; forms: { one: string; other: string } | null; qtyPerPortion: number; unit: BaseUnit; note: string | null };
|
||||
export type Ingredient = {
|
||||
ingredientId: string;
|
||||
name: string;
|
||||
forms: { one: string; other: string } | null;
|
||||
qtyPerPortion: number;
|
||||
unit: BaseUnit;
|
||||
note: string | null;
|
||||
displayUnit?: DisplayUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
export type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
export type Running = { step: number; endsAt: number | null; left: number; done: boolean };
|
||||
|
||||
@@ -98,12 +108,10 @@ export const withTextTimer = (s: Step): Step => ({ ...s, timerSeconds: s.timerSe
|
||||
|
||||
/** „250 g“ in der Portionszahl, und der passende Name (Einzahl/Mehrzahl). */
|
||||
export function useAmount(portions: number) {
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
return {
|
||||
amount: (i: Ingredient) => {
|
||||
const f = formatQuantity(i.qtyPerPortion * portions, i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
},
|
||||
// „2 EL (30 ml)“, „400 g (1 Dose)“ — lib/units.ts formatKitchen (26.11.39).
|
||||
amount: (i: Ingredient) => kitchen.text(i, i.qtyPerPortion * portions),
|
||||
label: (i: Ingredient) => labelFor(i, i.qtyPerPortion * portions),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -85,7 +85,6 @@ export function RateCard({ item }: { item: ToRate }) {
|
||||
ref={file}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
|
||||
@@ -24,19 +24,24 @@ export function PhotoButton({
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<"photo" | "full" | null>(null);
|
||||
|
||||
async function upload(file: File) {
|
||||
// Mehrere aus der Mediathek (26.11.43): nacheinander, bis fünf erreicht sind.
|
||||
async function upload(files: File[]) {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const form = new FormData();
|
||||
form.append("photo", file);
|
||||
const res = await fetch(`/api/dishes/${id}/photos`, {
|
||||
method: "POST",
|
||||
body: form,
|
||||
});
|
||||
let failed: "photo" | "full" | null = null;
|
||||
for (const file of files.slice(0, Math.max(0, 5 - count))) {
|
||||
const form = new FormData();
|
||||
form.append("photo", file);
|
||||
const res = await fetch(`/api/dishes/${id}/photos`, { method: "POST", body: form }).catch(() => null);
|
||||
if (!res?.ok) {
|
||||
failed = res && (await res.json().catch(() => ({}))).error === "full" ? "full" : "photo";
|
||||
break;
|
||||
}
|
||||
}
|
||||
setBusy(false);
|
||||
if (input.current) input.current.value = "";
|
||||
if (res.ok) router.refresh();
|
||||
else setError((await res.json().catch(() => ({}))).error === "full" ? "full" : "photo");
|
||||
setError(failed);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -45,11 +50,12 @@ export function PhotoButton({
|
||||
ref={input}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
// Ohne capture: Das iPhone bietet Fotomediathek, Kamera und Dateien an (Kai, 26.11.43).
|
||||
multiple
|
||||
className="sr-only"
|
||||
tabIndex={-1}
|
||||
aria-hidden
|
||||
onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])}
|
||||
onChange={(e) => e.target.files?.length && upload(Array.from(e.target.files))}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
|
||||
+241
-34
@@ -1,23 +1,25 @@
|
||||
"use client";
|
||||
|
||||
import { ArrowDown, ArrowUp, Plus, Sparkles, X, Package, Wand2 } from "lucide-react";
|
||||
import { ArrowDown, ArrowUp, CircleAlert, Plus, Sparkles, X, Package, Wand2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useEffect, useId, useRef, 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";
|
||||
import { BASES, TAGS } from "@/lib/categories";
|
||||
import { parseNumber, type BaseUnit } from "@/lib/units";
|
||||
import { COUNT_UNITS, FIXED_UNITS, formatQuantity, isMetric, isPackKind, needsSize, niceQty, parseNumber, sizeKey, sizeOf, type BaseUnit, type CountUnit } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
|
||||
import { IngredientPicker, type Picked } from "./ingredient-picker";
|
||||
import { PackSize } from "./pack-size";
|
||||
export { IngredientPicker, type Picked };
|
||||
// Produkt (optional): Name, Packung in der Einheit der Zeile, Kochzeit laut Packung.
|
||||
// inherited: Lieblingsprodukt des Haushalts für diese Zutat (26.11.38); remember: dieses Produkt für alle Gerichte merken.
|
||||
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean; remember?: boolean; inherited?: string | null };
|
||||
// size: Größe eines Zählmaßes, das der Haushalt noch nicht kennt („1 Packung = 500 g“, 26.11.49).
|
||||
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; size?: string; note: string; product: string; pack: string; cook: string; open: boolean; remember?: boolean; inherited?: string | null };
|
||||
type StepRow = { key: number; text: string; timer: string; section: Section | "" };
|
||||
|
||||
export type DishFormValue = {
|
||||
@@ -47,14 +49,27 @@ export type DishFormValue = {
|
||||
styledByAi?: boolean;
|
||||
};
|
||||
|
||||
const UNITS_FOR: Record<BaseUnit, string[]> = {
|
||||
g: ["g", "kg", "tbsp", "tsp", "pinch"],
|
||||
ml: ["ml", "l", "tbsp", "tsp", "pinch"],
|
||||
piece: ["piece"],
|
||||
/**
|
||||
* Maße für eine Zutat in drei Gruppen (26.11.49, Kai: „es fehlen Einheiten“): ihre
|
||||
* Grundeinheit, feste Küchenmaße (nicht bei Stück-Zutaten) und Zählmaße mit Größe.
|
||||
*/
|
||||
const unitGroups = (p: Picked | null): [string[], string[], string[]] => {
|
||||
const base = p?.unit ?? "g";
|
||||
// ml und l überall, auch bei Stück-Zutaten (26.11.50): dann mit Größe je Stück.
|
||||
if (base === "piece") return [["piece", "g", "kg", "ml", "l"], [], COUNT_UNITS.filter((u) => u !== "piece")];
|
||||
return [base === "g" ? ["g", "kg", "ml", "l"] : ["ml", "l", "g", "kg"], [...FIXED_UNITS], [...COUNT_UNITS]];
|
||||
};
|
||||
const unitsFor = (p: Picked | null) => unitGroups(p).flat();
|
||||
/** Bekannte Größe eines Zählmaßes für diese Zutat, sonst null. */
|
||||
const knownSize = (p: Picked | null, unit: string) => (p && needsSize(unit, p.unit) ? sizeOf(unit, p.unit, p) : null);
|
||||
|
||||
/**
|
||||
* Vorgewählte Einheit beim Wählen einer Zutat: ihr Löffelmaß (Olivenöl in EL), sonst
|
||||
* die Basiseinheit. Ein Gebinde wird angeboten, aber nie vorgewählt — wer nach
|
||||
* „Kokosmilch“ gleich „400“ tippt, meint Milliliter, nicht 400 Dosen.
|
||||
*/
|
||||
const preferredUnit = (p: Picked) => (p.kitchenUnit && !isPackKind(p.kitchenUnit) && unitsFor(p).includes(p.kitchenUnit) ? p.kitchenUnit : p.unit);
|
||||
|
||||
let counter = 0;
|
||||
const next = () => ++counter;
|
||||
|
||||
const formatQty = (n: number) => String(Math.round(n * 100) / 100).replace(".", ",");
|
||||
|
||||
@@ -63,7 +78,16 @@ const formatQty = (n: number) => String(Math.round(n * 100) / 100).replace(".",
|
||||
// Portion um (lib/dishes.ts).
|
||||
export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
const t = useTranslations("dishes");
|
||||
const locale = useLocale();
|
||||
const sizeText = (size: number, unit: BaseUnit) => {
|
||||
const f = formatQuantity(size, unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
};
|
||||
const router = useRouter();
|
||||
// Schlüssel der Zeilen je Formular, auf Server und Gerät gleich — sie stecken in den
|
||||
// Feld-Kennungen (qty-…, size-…), an denen die Fehlersätze hängen (26.11.51).
|
||||
const counter = useRef(0);
|
||||
const next = () => ++counter.current;
|
||||
const [title, setTitle] = useState(initial?.title ?? "");
|
||||
const [portions, setPortions] = useState(String(initial?.portions ?? 4));
|
||||
const [base, setBase] = useState(initial?.base ?? "");
|
||||
@@ -76,7 +100,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
key: next(),
|
||||
ingredient: i.ingredient,
|
||||
qty: i.qty !== null ? formatQty(i.qty) : "",
|
||||
unit: i.unit && UNITS_FOR[i.ingredient.unit].includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
unit: i.unit && unitsFor(i.ingredient).includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
note: i.note ?? "",
|
||||
// Ein geerbtes Lieblingsprodukt füllt die Felder nicht — leer heißt: es gilt weiter.
|
||||
product: i.product && !i.product.fromHousehold ? i.product.name : "",
|
||||
@@ -123,8 +147,70 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
}
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [checked, setChecked] = useState(false);
|
||||
// Vom Server abgelehnte Menge (26.11.51): gilt, bis sich Zutat, Menge oder Maß der Zeile ändern.
|
||||
const [rejected, setRejected] = useState<{ key: number; ingredientId: string; qty: string; unit: string } | null>(null);
|
||||
|
||||
// Alles, was vor dem Speichern fehlt — auf einmal, am Feld, und live nach dem ersten Versuch (Kai, 8.11.2026).
|
||||
type Problem = { id: string; rowKey?: number; text: string };
|
||||
function findProblems(): Problem[] {
|
||||
const out: Problem[] = [];
|
||||
if (!title.trim()) out.push({ id: "title", text: t("form.problem.titleMissing") });
|
||||
const n = parseNumber(portions);
|
||||
if (!n || n < 1 || n > 30) out.push({ id: "portions", text: t("form.problem.portions") });
|
||||
for (const r of rows) {
|
||||
if (!r.ingredient) continue;
|
||||
const q = r.qty.trim();
|
||||
if (!q) out.push({ id: `qty-${r.key}`, rowKey: r.key, text: t("form.problem.amountMissing") });
|
||||
else if (!((parseNumber(q) ?? 0) > 0)) out.push({ id: `qty-${r.key}`, rowKey: r.key, text: t("form.problem.amountInvalid") });
|
||||
else if (rejected && rejected.key === r.key && rejected.ingredientId === r.ingredient.id && rejected.qty === r.qty && rejected.unit === r.unit)
|
||||
out.push({ id: `unit-${r.key}`, rowKey: r.key, text: t("form.problem.amountServer") });
|
||||
if (needsSize(r.unit, r.ingredient.unit) && knownSize(r.ingredient, r.unit) === null && !((parseNumber(r.size ?? "") ?? 0) > 0))
|
||||
out.push({ id: `size-${r.key}`, rowKey: r.key, text: t("form.problem.sizeMissing") });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const problems = checked ? findProblems() : [];
|
||||
const problemAt = (id: string) => problems.find((p) => p.id === id);
|
||||
const invalid = (id: string) => (problemAt(id) ? true : undefined);
|
||||
const describedBy = (id: string) => (problemAt(id) ? `${id}-error` : undefined);
|
||||
function goTo(p: Problem | undefined) {
|
||||
const el = p ? document.getElementById(p.id) : null;
|
||||
if (!el) return;
|
||||
shown.current = p!.id;
|
||||
el.scrollIntoView({ block: "center", behavior: "smooth" });
|
||||
el.focus({ preventScroll: true });
|
||||
}
|
||||
// „Zeigen“: zum nächsten fehlenden Feld nach dem, in dem man gerade steht.
|
||||
// Beim Tippen auf den Knopf liegt der Fokus auf ihm — deshalb das zuletzt gezeigte merken.
|
||||
const shown = useRef<string | null>(null);
|
||||
function showNext() {
|
||||
const at = problems.findIndex((p) => p.id === shown.current);
|
||||
goTo(problems[(at + 1) % problems.length]);
|
||||
}
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
// Portionen umstellen rechnet die Mengen mit (Kai, 8.11.2026, 26.11.49) — immer vom
|
||||
// Stand beim Betreten des Feldes aus, damit sich Rundungen nicht aufsummieren.
|
||||
const scaleFrom = useRef<{ portions: number; qty: Map<number, string> } | null>(null);
|
||||
function rememberAmounts() {
|
||||
const n = parseNumber(portions);
|
||||
scaleFrom.current = n && n >= 1 ? { portions: n, qty: new Map(rows.map((r) => [r.key, r.qty])) } : null;
|
||||
}
|
||||
function changePortions(value: string) {
|
||||
setPortions(value);
|
||||
const n = parseNumber(value);
|
||||
const from = scaleFrom.current;
|
||||
if (!from || !n || n < 1 || n > 30) return;
|
||||
setRows((rs) =>
|
||||
rs.map((r) => {
|
||||
const before = from.qty.get(r.key);
|
||||
const q = before !== undefined ? parseNumber(before) : null;
|
||||
if (before === undefined || q === null) return r;
|
||||
return { ...r, qty: n === from.portions ? before : formatQty(niceQty((q * n) / from.portions, r.unit)) };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const update = (key: number, patch: Partial<Row>) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r)));
|
||||
const updateStep = (key: number, patch: Partial<StepRow>) => setSteps((ss) => ss.map((s) => (s.key === key ? { ...s, ...patch } : s)));
|
||||
const move = (index: number, by: number) =>
|
||||
@@ -139,9 +225,12 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
event.preventDefault();
|
||||
const n = parseNumber(portions);
|
||||
setChecked(true);
|
||||
// Eine gewählte Zutat ohne Menge fällt nicht still weg: Die Person ergänzt sie oder entfernt die Zeile.
|
||||
if (rows.some((r) => r.ingredient && !r.qty.trim())) {
|
||||
setError("missingAmount");
|
||||
setError(null);
|
||||
// Eine gewählte Zutat ohne Menge fällt nicht still weg, ein Zählmaß braucht seine Größe:
|
||||
// Alles Fehlende ist am Feld markiert, der Fokus springt zum ersten (26.11.51).
|
||||
const open = findProblems();
|
||||
if (open.length) {
|
||||
goTo(open[0]);
|
||||
return;
|
||||
}
|
||||
const ingredients = rows
|
||||
@@ -150,6 +239,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
ingredientId: r.ingredient!.id,
|
||||
qty: parseNumber(r.qty) ?? -1,
|
||||
unit: r.unit,
|
||||
size: r.ingredient && needsSize(r.unit, r.ingredient.unit) && knownSize(r.ingredient, r.unit) === null ? parseNumber(r.size ?? "") : null,
|
||||
note: r.note.trim() || null,
|
||||
product: r.product.trim()
|
||||
? {
|
||||
@@ -192,7 +282,11 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
if (res.ok) router.push(`/gerichte/${data.id}`);
|
||||
else setError(["invalid", "amount"].includes(data.error) ? data.error : "unknown");
|
||||
else if (data.error === "amount" && rows.some((r) => r.ingredient?.id === data.ingredientId)) {
|
||||
const row = rows.find((r) => r.ingredient?.id === data.ingredientId)!;
|
||||
setRejected({ key: row.key, ingredientId: data.ingredientId, qty: row.qty, unit: row.unit });
|
||||
requestAnimationFrame(() => goTo({ id: `unit-${row.key}`, text: "" }));
|
||||
} else setError(["invalid", "amount"].includes(data.error) ? data.error : "unknown");
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -206,7 +300,16 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
<section className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="title">{t("form.title")}</Label>
|
||||
<Input id="title" value={title} onChange={(e) => setTitle(e.target.value)} maxLength={120} required placeholder={t("form.titlePlaceholder")} />
|
||||
<Input
|
||||
id="title"
|
||||
value={title}
|
||||
onChange={(e) => setTitle(e.target.value)}
|
||||
maxLength={120}
|
||||
aria-invalid={invalid("title")}
|
||||
aria-describedby={describedBy("title")}
|
||||
placeholder={t("form.titlePlaceholder")}
|
||||
/>
|
||||
<FieldProblem id="title" problem={problemAt("title")} />
|
||||
</div>
|
||||
<div className="feldreihe grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-2">
|
||||
@@ -266,8 +369,21 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
<Label htmlFor="portions" className="flex-1">
|
||||
{t("form.portions")}
|
||||
</Label>
|
||||
<Input id="portions" inputMode="numeric" className="w-20 text-center" value={portions} onChange={(e) => setPortions(e.target.value)} />
|
||||
<Input
|
||||
id="portions"
|
||||
inputMode="numeric"
|
||||
aria-describedby={["portions-hint", describedBy("portions")].filter(Boolean).join(" ")}
|
||||
aria-invalid={invalid("portions")}
|
||||
className="w-20 text-center"
|
||||
value={portions}
|
||||
onFocus={rememberAmounts}
|
||||
onChange={(e) => changePortions(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<p id="portions-hint" className="-mt-1 text-sm text-muted-foreground">
|
||||
{t("form.portionsHint")}
|
||||
</p>
|
||||
<FieldProblem id="portions" problem={problemAt("portions")} />
|
||||
{initial?.unmatched?.length ? (
|
||||
<div role="note" className="flex flex-col gap-2 rounded-2xl border border-border p-4 text-sm">
|
||||
<p className="font-medium">{t("form.unmatched")}</p>
|
||||
@@ -280,9 +396,9 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
) : null}
|
||||
<ul className="flex flex-col gap-4">
|
||||
{rows.map((row) => (
|
||||
<li key={row.key} className="flex flex-col gap-2 rounded-2xl bg-muted p-3">
|
||||
<li key={row.key} className={cn("flex flex-col gap-2 rounded-2xl bg-muted p-3", problems.some((p) => p.rowKey === row.key) && "ring-2 ring-over")}>
|
||||
<div className="flex items-start gap-2">
|
||||
<IngredientPicker canCreate value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: p.unit, inherited: row.product ? row.inherited : (p.product ?? null) })} />
|
||||
<IngredientPicker canCreate value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: preferredUnit(p), inherited: row.product ? row.inherited : (p.product ?? null) })} />
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -295,26 +411,92 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
</div>
|
||||
<div className="grid grid-cols-[1fr_auto] gap-2">
|
||||
<Input
|
||||
id={`qty-${row.key}`}
|
||||
aria-label={t("form.amount")}
|
||||
aria-invalid={checked && !!row.ingredient && !row.qty.trim() ? true : undefined}
|
||||
aria-invalid={invalid(`qty-${row.key}`)}
|
||||
aria-describedby={describedBy(`qty-${row.key}`)}
|
||||
inputMode="decimal"
|
||||
placeholder={t("form.amount")}
|
||||
value={row.qty}
|
||||
onChange={(e) => update(row.key, { qty: e.target.value })}
|
||||
/>
|
||||
<select
|
||||
id={`unit-${row.key}`}
|
||||
aria-label={t("form.unit")}
|
||||
aria-invalid={invalid(`unit-${row.key}`)}
|
||||
aria-describedby={describedBy(`unit-${row.key}`)}
|
||||
value={row.unit}
|
||||
onChange={(e) => update(row.key, { unit: e.target.value })}
|
||||
className="min-h-11 rounded-xl border border-border bg-background px-3 text-base"
|
||||
className="min-h-11 rounded-xl border border-border bg-background px-3 text-base aria-[invalid=true]:border-2 aria-[invalid=true]:border-over"
|
||||
>
|
||||
{UNITS_FOR[row.ingredient?.unit ?? "g"].map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{t(`form.units.${u}`)}
|
||||
</option>
|
||||
))}
|
||||
{unitGroups(row.ingredient).map((group, g) =>
|
||||
group.length ? (
|
||||
<optgroup key={g} label={t(`form.unitGroups.${["base", "kitchen", "count"][g]}`)}>
|
||||
{group.map((u) => {
|
||||
const size = knownSize(row.ingredient, u);
|
||||
return (
|
||||
<option key={u} value={u}>
|
||||
{/* Ein Zählmaß nennt seine Größe gleich mit: „Dose (400 g)“. */}
|
||||
{size && row.ingredient && row.ingredient.unit !== "piece"
|
||||
? t("form.unitWithSize", { unit: t(`form.units.${u}`), size: sizeText(size, row.ingredient.unit) })
|
||||
: t(`form.units.${u}`)}
|
||||
</option>
|
||||
);
|
||||
})}
|
||||
</optgroup>
|
||||
) : null,
|
||||
)}
|
||||
</select>
|
||||
</div>
|
||||
<FieldProblem id={`qty-${row.key}`} problem={problemAt(`qty-${row.key}`)} />
|
||||
<FieldProblem id={`unit-${row.key}`} problem={problemAt(`unit-${row.key}`)} />
|
||||
{row.ingredient && needsSize(row.unit, row.ingredient.unit) ? (
|
||||
knownSize(row.ingredient, row.unit) !== null ? (
|
||||
<PackSize
|
||||
ingredient={row.ingredient}
|
||||
kind={sizeKey(row.unit) as CountUnit | "g" | "ml"}
|
||||
perPiece={isMetric(row.unit)}
|
||||
size={knownSize(row.ingredient, row.unit)!}
|
||||
sizeText={sizeText}
|
||||
onSaved={(size) =>
|
||||
setRows((rs) =>
|
||||
rs.map((r) =>
|
||||
r.ingredient?.id === row.ingredient!.id
|
||||
? {
|
||||
...r,
|
||||
ingredient: {
|
||||
...r.ingredient!,
|
||||
sizes: { ...r.ingredient!.sizes, [sizeKey(row.unit)]: size },
|
||||
packSize: r.ingredient!.packKind === row.unit ? size : r.ingredient!.packSize,
|
||||
},
|
||||
}
|
||||
: r,
|
||||
),
|
||||
)
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="flex items-center gap-2">
|
||||
<Label htmlFor={`size-${row.key}`} className="flex-1 text-sm">
|
||||
{isMetric(row.unit)
|
||||
? t("form.sizeAskPerPiece", { base: sizeKey(row.unit) })
|
||||
: t("form.sizeAsk", { unit: t(`form.units.${row.unit}`), base: t(`form.units.${row.ingredient.unit}`) })}
|
||||
</Label>
|
||||
<Input
|
||||
id={`size-${row.key}`}
|
||||
inputMode="decimal"
|
||||
className="w-24 text-center"
|
||||
aria-invalid={invalid(`size-${row.key}`)}
|
||||
aria-describedby={describedBy(`size-${row.key}`)}
|
||||
value={row.size ?? ""}
|
||||
onChange={(e) => update(row.key, { size: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
) : null}
|
||||
{row.ingredient && needsSize(row.unit, row.ingredient.unit) && knownSize(row.ingredient, row.unit) === null ? (
|
||||
<FieldProblem id={`size-${row.key}`} problem={problemAt(`size-${row.key}`)} />
|
||||
) : null}
|
||||
<Input
|
||||
aria-label={t("form.note")}
|
||||
placeholder={t("form.notePlaceholder")}
|
||||
@@ -338,7 +520,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`pack-${row.key}`} className="text-sm">
|
||||
{t("form.productPack", { unit: t(`form.units.${row.unit}`) })}
|
||||
{t("form.productPack", { unit: t(`form.units.${isPackKind(row.unit) ? (row.ingredient?.unit ?? "g") : row.unit}`) })}
|
||||
</Label>
|
||||
<Input id={`pack-${row.key}`} inputMode="decimal" value={row.pack} onChange={(e) => update(row.key, { pack: e.target.value })} />
|
||||
</div>
|
||||
@@ -459,13 +641,27 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
</section>
|
||||
|
||||
{error ? <ErrorNotice>{t(`form.errors.${error}`)}</ErrorNotice> : null}
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
{t("form.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" size="lg" className="flex-1" disabled={busy}>
|
||||
{busy ? t("form.saving") : t("form.save")}
|
||||
</Button>
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex flex-col gap-2 bg-background py-2">
|
||||
{/* Solange etwas fehlt: wie viel, und ein Knopf, der hinführt (26.11.51). */}
|
||||
{problems.length ? (
|
||||
<div role="status" className="flex items-center justify-between gap-2 rounded-xl border-2 border-over px-3">
|
||||
<span className="flex items-center gap-1.5 text-sm font-medium">
|
||||
<CircleAlert aria-hidden className="size-4 shrink-0 text-over" />
|
||||
{t("form.problemsLeft", { n: problems.length })}
|
||||
</span>
|
||||
<Button type="button" variant="ghost" className="min-h-11 px-3" onClick={showNext}>
|
||||
{t("form.problemsShow")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" variant="outline" onClick={() => router.back()}>
|
||||
{t("form.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" size="lg" className="flex-1" disabled={busy}>
|
||||
{busy ? t("form.saving") : t("form.save")}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
@@ -473,3 +669,14 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
|
||||
// Zutat suchen und wählen. Tippen sucht in der Sprache der Person, auch über
|
||||
// Synonyme (lib/ingredient-search.ts); ein Tipp auf einen Treffer wählt ihn.
|
||||
|
||||
/** Satz am Feld, wenn dort etwas fehlt — mit Zeichen, Farbe trägt nie allein (26.11.51). */
|
||||
function FieldProblem({ id, problem }: { id: string; problem?: { text: string } }) {
|
||||
if (!problem) return null;
|
||||
return (
|
||||
<p id={`${id}-error`} className="-mt-1 flex items-center gap-1.5 text-sm font-medium">
|
||||
<CircleAlert aria-hidden className="size-4 shrink-0 text-over" />
|
||||
{problem.text}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -2,8 +2,9 @@ import { UtensilsCrossed } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Kachel eines Gerichts: Foto (oder Illustration, bis eines da ist), Titel in
|
||||
// der Serifenschrift, darunter eine Zeile mit Zeit und Beilage.
|
||||
// Kachel eines Gerichts: Foto (oder Illustration, bis eines da ist), Titel,
|
||||
// darunter eine Zeile mit Zeit und Beilage. Alle Kacheln sind gleich hoch (Kai,
|
||||
// 26.11.44): Titel und Infozeile je höchstens zwei Zeilen, immer Platz für zwei.
|
||||
export function DishPhoto({ dishId, photo, className }: { dishId: string; photo: string | null; className?: string }) {
|
||||
if (photo) {
|
||||
const version = photo.split("-").at(-1)?.replace(".webp", "") ?? "";
|
||||
@@ -19,13 +20,18 @@ export function DishPhoto({ dishId, photo, className }: { dishId: string; photo:
|
||||
|
||||
export function DishTile({ id, title, photo, meta }: { id: string; title: string; photo: string | null; meta: string }) {
|
||||
return (
|
||||
<Link href={`/gerichte/${id}`} className="group flex flex-col overflow-hidden rounded-2xl bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
|
||||
<Link
|
||||
href={`/gerichte/${id}`}
|
||||
title={title}
|
||||
className="group flex h-full flex-col overflow-hidden rounded-2xl bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<div className="aspect-square overflow-hidden">
|
||||
<DishPhoto dishId={id} photo={photo} />
|
||||
</div>
|
||||
<div className="flex min-h-11 flex-col gap-0.5 p-3">
|
||||
<h2 className="text-lg leading-snug">{title}</h2>
|
||||
{meta ? <p className="text-xs text-muted-foreground">{meta}</p> : null}
|
||||
<div className="flex flex-1 flex-col gap-0.5 p-3">
|
||||
<h2 className="line-clamp-2 min-h-[2lh] text-lg leading-snug">{title}</h2>
|
||||
{/* Auch ohne Infozeile die gleiche Höhe: ein leerer Platzhalter. */}
|
||||
<p className="line-clamp-2 min-h-[2lh] text-xs text-muted-foreground">{meta || "\u00a0"}</p>
|
||||
</div>
|
||||
</Link>
|
||||
);
|
||||
|
||||
@@ -9,10 +9,21 @@ import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { CATEGORIES } from "@/lib/categories";
|
||||
import { normalize } from "@/lib/ingredient-search";
|
||||
import type { BaseUnit } from "@/lib/units";
|
||||
import type { BaseUnit, KitchenUnit, PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Picked = { id: string; name: string; unit: BaseUnit; group?: boolean; product?: string | null };
|
||||
export type Picked = {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: BaseUnit;
|
||||
group?: boolean;
|
||||
product?: string | null;
|
||||
kitchenUnit?: KitchenUnit | null;
|
||||
packKind?: PackKind | null;
|
||||
packSize?: number | null;
|
||||
/** Größen des Haushalts je Zählmaß (26.11.49). */
|
||||
sizes?: Partial<Record<string, number>>;
|
||||
};
|
||||
type Hit = Picked & { kinds: number; parentId: string | null; own: boolean };
|
||||
|
||||
// Zutat suchen und wählen (26.11.38): Ein Oberbegriff („Pasta“) steht oben als
|
||||
@@ -26,6 +37,8 @@ export function IngredientPicker({ value, onPick, canCreate = false }: { value:
|
||||
const [hits, setHits] = useState<Hit[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
// Für welche Eingabe die Treffer gelten — „anlegen“ erst, wenn die Suche geantwortet hat.
|
||||
const [answered, setAnswered] = useState("");
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -36,19 +49,22 @@ export function IngredientPicker({ value, onPick, canCreate = false }: { value:
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(async () => {
|
||||
const res = await fetch(`/api/ingredients?q=${encodeURIComponent(query)}`);
|
||||
if (res.ok) setHits(await res.json());
|
||||
if (res.ok) {
|
||||
setHits(await res.json());
|
||||
setAnswered(query);
|
||||
}
|
||||
}, 150);
|
||||
}, [query, open, value?.name]);
|
||||
|
||||
const pick = (h: Picked) => {
|
||||
onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null });
|
||||
onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null, kitchenUnit: h.kitchenUnit, packKind: h.packKind, packSize: h.packSize, sizes: h.sizes });
|
||||
setQuery(h.name);
|
||||
setOpen(false);
|
||||
setCreating(false);
|
||||
};
|
||||
const groupIds = new Set(hits.filter((h) => h.group).map((h) => h.id));
|
||||
const exact = hits.some((h) => normalize(h.name) === normalize(query));
|
||||
const offerCreate = canCreate && query.trim().length >= 2 && !exact;
|
||||
const offerCreate = canCreate && query.trim().length >= 2 && !exact && answered === query;
|
||||
|
||||
return (
|
||||
<div className="relative flex-1">
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, 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";
|
||||
import { parseNumber, type BaseUnit, type CountUnit } from "@/lib/units";
|
||||
|
||||
// Größe eines Zählmaßes (26.11.39, alle Zählmaße seit 26.11.49): „1 Dose = 400 g“,
|
||||
// „1 Zehe = 3 g“ — wer Gerichte pflegt, kann sie für den Haushalt ändern. Gilt für alle Gerichte.
|
||||
export function PackSize({
|
||||
ingredient,
|
||||
kind,
|
||||
perPiece = false,
|
||||
size,
|
||||
sizeText,
|
||||
onSaved,
|
||||
}: {
|
||||
ingredient: { id: string; unit: BaseUnit };
|
||||
/** Zählmaß, oder g/ml je Stück einer Stück-Zutat (perPiece, 26.11.50: „1 Stück = 500 ml“). */
|
||||
kind: CountUnit | "g" | "ml";
|
||||
perPiece?: boolean;
|
||||
size: number;
|
||||
sizeText: (size: number, unit: BaseUnit) => string;
|
||||
onSaved: (size: number) => void;
|
||||
}) {
|
||||
const t = useTranslations("dishes.form");
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [value, setValue] = useState(String(size));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const unit = t(`units.${perPiece ? "piece" : kind}`);
|
||||
const base: BaseUnit = perPiece ? (kind as BaseUnit) : ingredient.unit;
|
||||
|
||||
async function save() {
|
||||
const next = parseNumber(value);
|
||||
if (!next || next <= 0) return setError(true);
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
const res = await fetch(`/api/ingredients/${ingredient.id}/pack`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ size: next, unit: kind }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(true);
|
||||
onSaved((await res.json()).size);
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 text-sm text-muted-foreground">
|
||||
<span>{t("packSize", { unit, size: sizeText(size, base) })}</span>
|
||||
<Button type="button" variant="ghost" className="min-h-11" onClick={() => setOpen(true)}>
|
||||
{t("packChange")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-xl border border-border p-3">
|
||||
<Label htmlFor={id} className="text-sm">
|
||||
{t("packSizeLabel", { unit, base: t(`units.${base}`) })}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input id={id} inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} className="flex-1" />
|
||||
<Button type="button" disabled={busy} onClick={save}>
|
||||
{t("packSave")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t("packHint")}</p>
|
||||
{error ? <ErrorNotice>{t("packError")}</ErrorNotice> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,28 +1,52 @@
|
||||
"use client";
|
||||
|
||||
import { Camera } from "lucide-react";
|
||||
import { Camera, Plus, X } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { DishForm, type DishFormValue } from "./dish-form";
|
||||
|
||||
// Kochbuchfoto → Entwurf. Das Bildmodell liest die Seite (app/api/dishes/photo-import),
|
||||
// die Person prüft und speichert. Das Foto selbst wird nicht aufbewahrt.
|
||||
/** Seiten je Rezept (26.11.48, Kai: „mehrere Seiten“). Der Server prüft dasselbe. */
|
||||
export const MAX_PAGES = 6;
|
||||
|
||||
type Page = { file: File; url: string };
|
||||
|
||||
// Kochbuchfoto → Entwurf. Das Bildmodell liest die Seiten (app/api/dishes/photo-import),
|
||||
// die Person prüft und speichert. Die Fotos selbst werden nicht aufbewahrt.
|
||||
// Seiten sammeln sich: Jede Aufnahme oder Auswahl kommt hinten dazu — am iPhone
|
||||
// liefert „Foto aufnehmen“ immer nur ein Bild.
|
||||
export function PhotoImport() {
|
||||
const t = useTranslations("dishes.photo");
|
||||
const [files, setFiles] = useState<File[]>([]);
|
||||
const [pages, setPages] = useState<Page[]>([]);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [draft, setDraft] = useState<DishFormValue | null>(null);
|
||||
|
||||
// Vorschaubilder freigeben, wenn die Seite verlassen wird.
|
||||
useEffect(() => () => pages.forEach((p) => URL.revokeObjectURL(p.url)), []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
function add(list: FileList | null) {
|
||||
const files = Array.from(list ?? []);
|
||||
setPages((old) => [...old, ...files.slice(0, MAX_PAGES - old.length).map((file) => ({ file, url: URL.createObjectURL(file) }))]);
|
||||
setError(null);
|
||||
}
|
||||
|
||||
function remove(index: number) {
|
||||
setPages((old) => {
|
||||
URL.revokeObjectURL(old[index]!.url);
|
||||
return old.filter((_, i) => i !== index);
|
||||
});
|
||||
}
|
||||
|
||||
async function read(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
if (!files.length) return;
|
||||
if (!pages.length) return;
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const body = new FormData();
|
||||
for (const f of files) body.append("photos", f);
|
||||
for (const p of pages) body.append("photos", p.file);
|
||||
const res = await fetch("/api/dishes/photo-import", { method: "POST", body });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
@@ -34,24 +58,65 @@ export function PhotoImport() {
|
||||
}
|
||||
|
||||
if (draft) return <DishForm initial={draft} />;
|
||||
const full = pages.length >= MAX_PAGES;
|
||||
return (
|
||||
<form onSubmit={read} className="flex flex-col gap-4">
|
||||
<label className="flex min-h-32 cursor-pointer flex-col items-center justify-center gap-2 rounded-2xl border border-dashed border-border p-6 text-center focus-within:ring-2 focus-within:ring-ring">
|
||||
<Camera aria-hidden className="size-8 text-accent" strokeWidth={1.5} />
|
||||
<span className="font-semibold">{files.length ? t("chosen", { n: files.length }) : t("choose")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("chooseHint")}</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/*"
|
||||
capture="environment"
|
||||
multiple
|
||||
className="sr-only"
|
||||
aria-label={t("choose")}
|
||||
onChange={(e) => setFiles(Array.from(e.target.files ?? []).slice(0, 2))}
|
||||
/>
|
||||
</label>
|
||||
<input
|
||||
id="cookbook-pages"
|
||||
type="file"
|
||||
accept="image/*"
|
||||
multiple
|
||||
className="sr-only"
|
||||
aria-label={pages.length ? t("addPage") : t("choose")}
|
||||
disabled={full || busy}
|
||||
onChange={(e) => {
|
||||
add(e.target.files);
|
||||
e.target.value = ""; // dieselbe Datei darf noch einmal kommen
|
||||
}}
|
||||
/>
|
||||
{pages.length ? (
|
||||
<>
|
||||
<ol aria-label={t("chosen", { n: pages.length })} className="grid grid-cols-3 gap-3">
|
||||
{pages.map((p, i) => (
|
||||
<li key={p.url} className="relative overflow-hidden rounded-xl border border-border">
|
||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||
<img src={p.url} alt={t("page", { n: i + 1 })} className="aspect-[3/4] w-full object-cover" />
|
||||
<span className="absolute bottom-1 left-1 rounded-full bg-background/90 px-2 py-0.5 text-xs font-semibold">{t("page", { n: i + 1 })}</span>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={t("removePage", { n: i + 1 })}
|
||||
disabled={busy}
|
||||
onClick={() => remove(i)}
|
||||
className="absolute right-0 top-0 flex size-11 items-center justify-center focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className="flex size-8 items-center justify-center rounded-full bg-background/90">
|
||||
<X aria-hidden className="size-4" />
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
{full ? (
|
||||
<p className="text-sm text-muted-foreground">{t("full", { n: MAX_PAGES })}</p>
|
||||
) : (
|
||||
<label htmlFor="cookbook-pages" className={cn(buttonVariants({ variant: "outline" }), "cursor-pointer")}>
|
||||
<Plus aria-hidden />
|
||||
{t("addPage")}
|
||||
</label>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<label
|
||||
htmlFor="cookbook-pages"
|
||||
className="flex min-h-32 cursor-pointer flex-col items-center justify-center gap-2 rounded-2xl border border-dashed border-border p-6 text-center"
|
||||
>
|
||||
<Camera aria-hidden className="size-8 text-accent" strokeWidth={1.5} />
|
||||
<span className="font-semibold">{t("choose")}</span>
|
||||
<span className="text-sm text-muted-foreground">{t("chooseHint", { n: MAX_PAGES })}</span>
|
||||
</label>
|
||||
)}
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
<Button type="submit" size="lg" disabled={busy || !files.length}>
|
||||
<Button type="submit" size="lg" disabled={busy || !pages.length}>
|
||||
{busy ? t("reading") : t("read")}
|
||||
</Button>
|
||||
{busy ? <p className="text-center text-sm text-muted-foreground">{t("readingHint")}</p> : null}
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { Minus, Plus, Timer } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
import { formatQuantity, scale, type BaseUnit } from "@/lib/units";
|
||||
import { scale, type BaseUnit, type DisplayUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
|
||||
type Ingredient = {
|
||||
ingredientId: string;
|
||||
@@ -17,6 +18,8 @@ type Ingredient = {
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
product?: { name: string } | null;
|
||||
displayUnit?: DisplayUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
|
||||
@@ -24,14 +27,11 @@ type Step = { section: Section; text: string; timerSeconds: number | null; ingre
|
||||
// rechnet lib/units.ts — gespeichert ist immer „pro Portion“.
|
||||
export function PortionScaler({ ingredients, steps, initialPortions }: { ingredients: Ingredient[]; steps: Step[]; initialPortions: number }) {
|
||||
const t = useTranslations("dishes.detail");
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
const [portions, setPortions] = useState(initialPortions);
|
||||
const ts = useTranslations("dishes.sections");
|
||||
const byId = new Map(ingredients.map((i) => [i.ingredientId, i]));
|
||||
const amountOf = (i: Ingredient) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
};
|
||||
const amountOf = (i: Ingredient) => `${kitchen.text(i, scale(i.qtyPerPortion, portions))} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
// Durchgehend nummeriert, gegliedert nach Abschnitten (lib/recipe-style.ts).
|
||||
const numbered = steps.map((s, n) => ({ ...s, n: n + 1 }));
|
||||
|
||||
@@ -54,14 +54,12 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
|
||||
</div>
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{ingredients.map((i) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
const f = kitchen.parts(i, scale(i.qtyPerPortion, portions));
|
||||
return (
|
||||
<li key={i.ingredientId} className="flex min-h-11 items-baseline gap-3 py-2">
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">
|
||||
{f.amount}
|
||||
{f.unit ? ` ${f.unit}` : ""}
|
||||
</span>
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">{f.main}</span>
|
||||
<span className="flex-1">
|
||||
{f.extra ? <span className="text-muted-foreground tabular-nums">({f.extra}) </span> : null}
|
||||
{labelFor(i, scale(i.qtyPerPortion, portions))}
|
||||
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
|
||||
{i.product ? <span className="block text-sm text-muted-foreground">{i.product.name}</span> : null}
|
||||
|
||||
@@ -61,7 +61,7 @@ export function StarterPicker({ starters }: { starters: Starter[] }) {
|
||||
})}
|
||||
</ul>
|
||||
{error ? <ErrorNotice>{t("form.errors.unknown")}</ErrorNotice> : null}
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background/0 pb-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 bg-background/0 pb-2">
|
||||
<Button
|
||||
size="lg"
|
||||
className="w-full shadow-lg"
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
"use client";
|
||||
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
// Ein Gericht unter „Ausprobieren“ sagt das selbst (26.11.41, Kai: „neue Gerichte werden
|
||||
// nicht gespeichert“ — sie standen nur nicht im Pool). Mit einem Tipp in den Pool.
|
||||
export function TrialNote({ id, canWrite }: { id: string; canWrite: boolean }) {
|
||||
const t = useTranslations("dishes.detail");
|
||||
const router = useRouter();
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
async function toPool() {
|
||||
setBusy(true);
|
||||
const res = await fetch(`/api/dishes/${id}/pool`, { method: "POST" }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div role="note" className="flex flex-col gap-3 rounded-xl border border-border px-4 py-3">
|
||||
<p className="text-sm">
|
||||
{t("inTrial")}{" "}
|
||||
<Link href="/gerichte?ansicht=ausprobieren" className="font-semibold underline underline-offset-4">
|
||||
{t("inTrialLink")}
|
||||
</Link>
|
||||
</p>
|
||||
{canWrite ? (
|
||||
<Button type="button" variant="outline" className="self-start" disabled={busy} onClick={toPool}>
|
||||
{t("toPool")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button, buttonVariants } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
async function call(method: string, body?: object) {
|
||||
const res = await fetch("/api/household/calendar", { method, headers: { "content-type": "application/json" }, body: body ? JSON.stringify(body) : undefined });
|
||||
return { ok: res.ok, data: await res.json().catch(() => ({})) };
|
||||
}
|
||||
|
||||
// Kalender abonnieren (26.11.45): Essenszeit, Link erzeugen, ersetzen, beenden.
|
||||
// Der Link steht nur einmal da — gespeichert ist nur sein Hash.
|
||||
export function CalendarSettings({ active, mealTime, mealMinutes, locked }: { active: boolean; mealTime: string; mealMinutes: number; locked: boolean }) {
|
||||
const t = useTranslations("more.calendar");
|
||||
const router = useRouter();
|
||||
const [time, setTime] = useState(mealTime);
|
||||
const [minutes, setMinutes] = useState(String(mealMinutes));
|
||||
const [url, setUrl] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [saved, setSaved] = useState(false);
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [armed, setArmed] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
|
||||
async function run(fn: () => Promise<{ ok: boolean; data: { url?: string } }>) {
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
const r = await fn();
|
||||
setBusy(false);
|
||||
if (!r.ok) setError(true);
|
||||
else router.refresh();
|
||||
return r;
|
||||
}
|
||||
|
||||
if (locked) return <p className="rounded-xl border border-border px-4 py-3 text-sm">{t("locked")}</p>;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-sm text-muted-foreground">{t("hint")}</p>
|
||||
<div className="flex items-end gap-3">
|
||||
<div className="flex flex-1 flex-col gap-2">
|
||||
<Label htmlFor="meal-time">{t("time")}</Label>
|
||||
<Input id="meal-time" type="time" value={time} onChange={(e) => (setTime(e.target.value), setSaved(false))} />
|
||||
</div>
|
||||
<div className="flex w-28 flex-col gap-2">
|
||||
<Label htmlFor="meal-minutes">{t("minutes")}</Label>
|
||||
<Input id="meal-minutes" type="number" inputMode="numeric" min={15} max={240} step={15} value={minutes} onChange={(e) => (setMinutes(e.target.value), setSaved(false))} />
|
||||
</div>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
const r = await run(() => call("PATCH", { mealTime: time, mealMinutes: Number(minutes) }));
|
||||
setSaved(r.ok);
|
||||
}}
|
||||
>
|
||||
{saved ? t("saved") : t("saveTime")}
|
||||
</Button>
|
||||
|
||||
{url ? (
|
||||
<div className="flex flex-col gap-2 rounded-2xl bg-muted p-4">
|
||||
<p className="text-sm font-semibold">{t("linkOnce")}</p>
|
||||
<p data-testid="calendar-url" className="break-all font-mono text-sm">
|
||||
{url}
|
||||
</p>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={async () => {
|
||||
await navigator.clipboard?.writeText(url).catch(() => undefined);
|
||||
setCopied(true);
|
||||
}}
|
||||
>
|
||||
{copied ? t("copied") : t("copy")}
|
||||
</Button>
|
||||
<a href={url.replace(/^https?:/, "webcal:")} className={cn(buttonVariants({ variant: "default" }))}>
|
||||
{t("subscribe")}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<Button
|
||||
type="button"
|
||||
variant={active ? "outline" : "default"}
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
const r = await run(() => call("POST"));
|
||||
if (r.ok && r.data.url) {
|
||||
setUrl(r.data.url);
|
||||
setCopied(false);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{active ? t("renew") : t("create")}
|
||||
</Button>
|
||||
{active ? <p className="text-sm text-muted-foreground">{t("renewHint")}</p> : null}
|
||||
{active ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant={armed ? "default" : "ghost"}
|
||||
disabled={busy}
|
||||
onBlur={() => setArmed(false)}
|
||||
onClick={async () => {
|
||||
if (!armed) return setArmed(true);
|
||||
setArmed(false);
|
||||
const r = await run(() => call("DELETE"));
|
||||
if (r.ok) setUrl(null);
|
||||
}}
|
||||
>
|
||||
{armed ? t("confirmStop") : t("stop")}
|
||||
</Button>
|
||||
) : null}
|
||||
{error ? <ErrorNotice>{t("error")}</ErrorNotice> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
"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 MailCurrent = {
|
||||
host: string;
|
||||
port: number;
|
||||
secure: boolean;
|
||||
username: string;
|
||||
fromAddress: string;
|
||||
fromName: string | null;
|
||||
hasPassword: boolean;
|
||||
} | null;
|
||||
|
||||
// Mails verschicken (nur Admin, 26.11.40). Voreinstellung Resend; der Schlüssel
|
||||
// geht nur hinein und wird nie angezeigt.
|
||||
export function MailSettings({ current, defaults, me }: { current: MailCurrent; defaults: NonNullable<MailCurrent>; me: string | null }) {
|
||||
const t = useTranslations("more.mailSettings");
|
||||
const te = useTranslations("auth.errors");
|
||||
const router = useRouter();
|
||||
const start = current ?? defaults;
|
||||
const [host, setHost] = useState(start.host);
|
||||
const [port, setPort] = useState(String(start.port));
|
||||
const [secure, setSecure] = useState(start.secure);
|
||||
const [username, setUsername] = useState(start.username);
|
||||
const [password, setPassword] = useState("");
|
||||
const [fromAddress, setFromAddress] = useState(start.fromAddress);
|
||||
const [fromName, setFromName] = useState(start.fromName ?? "");
|
||||
const [testTo, setTestTo] = useState(me ?? "");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [note, setNote] = useState<string | null>(null);
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
const res = await fetch("/api/household/mail", {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
host: host.trim(),
|
||||
port: Number(port),
|
||||
secure,
|
||||
username: username.trim(),
|
||||
password: password.trim() ? password.trim() : undefined,
|
||||
fromAddress: fromAddress.trim(),
|
||||
fromName: fromName.trim() || null,
|
||||
}),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(te("invalid"));
|
||||
setPassword("");
|
||||
setNote(t("saved"));
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
async function test() {
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNote(null);
|
||||
const res = await fetch("/api/household/mail/test", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ to: testTo }) }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) return setNote(t("testSent"));
|
||||
const data = res ? await res.json().catch(() => ({})) : {};
|
||||
if (data.error === "mailFailed") return setError(t("testFailed", { detail: data.detail ?? "" }));
|
||||
setError(te(["mailNotConfigured", "tooMany", "invalid"].includes(data.error) ? data.error : "unknown"));
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
await fetch("/api/household/mail", { method: "DELETE" }).catch(() => null);
|
||||
setBusy(false);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-5">
|
||||
<form onSubmit={save} className="flex flex-col gap-3">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-host">{t("host")}</Label>
|
||||
<Input id="mail-host" value={host} onChange={(e) => setHost(e.target.value)} autoComplete="off" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-port">{t("port")}</Label>
|
||||
<Input id="mail-port" inputMode="numeric" value={port} onChange={(e) => setPort(e.target.value)} />
|
||||
</div>
|
||||
<label className="flex min-h-11 items-center gap-3 text-sm">
|
||||
<input type="checkbox" checked={secure} onChange={(e) => setSecure(e.target.checked)} className="size-5 accent-primary" />
|
||||
{t("secure")}
|
||||
</label>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-user">{t("username")}</Label>
|
||||
<Input id="mail-user" value={username} onChange={(e) => setUsername(e.target.value)} autoComplete="off" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-password">{t("password")}</Label>
|
||||
<Input id="mail-password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="new-password" placeholder="re_…" />
|
||||
{current?.hasPassword ? <p className="text-sm text-muted-foreground">{t("passwordSaved")}</p> : null}
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-from">{t("fromAddress")}</Label>
|
||||
<Input id="mail-from" type="email" value={fromAddress} onChange={(e) => setFromAddress(e.target.value)} />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor="mail-from-name">{t("fromName")}</Label>
|
||||
<Input id="mail-from-name" value={fromName} onChange={(e) => setFromName(e.target.value)} maxLength={80} />
|
||||
</div>
|
||||
<Button type="submit" disabled={busy || (!current?.hasPassword && !password.trim())}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</form>
|
||||
|
||||
{current?.hasPassword ? (
|
||||
<div className="flex flex-col gap-2 border-t border-border pt-4">
|
||||
<Label htmlFor="mail-test-to">{t("testTo")}</Label>
|
||||
<Input id="mail-test-to" type="email" value={testTo} onChange={(e) => setTestTo(e.target.value)} />
|
||||
<Button type="button" variant="outline" disabled={busy || !testTo.trim()} onClick={test}>
|
||||
{t("test")}
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
{error ? <ErrorNotice>{error}</ErrorNotice> : null}
|
||||
{note ? (
|
||||
<p role="status" className="rounded-xl border border-border px-4 py-3 text-sm">
|
||||
{note}
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
<section className="flex flex-col gap-2 border-t border-border pt-4">
|
||||
<h2 className="eyebrow">{t("stepsTitle")}</h2>
|
||||
<ol className="flex list-decimal flex-col gap-1 pl-5 text-sm text-muted-foreground">
|
||||
<li>{t("step1")}</li>
|
||||
<li>{t("step2")}</li>
|
||||
<li>{t("step3")}</li>
|
||||
<li>{t("step4")}</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
{current ? (
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={busy} onClick={remove}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, 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";
|
||||
|
||||
// Mehr › Anmelden per Mail (26.11.40): eigene Adresse eintragen, über den Link
|
||||
// bestätigen. Wer per Mail-Link angemeldet ist, ändert hier nichts (E-0006).
|
||||
export function MailSignIn({ verified, pending, locked }: { verified: string | null; pending: string | null; locked: boolean }) {
|
||||
const t = useTranslations("more.mail");
|
||||
const te = useTranslations("auth.errors");
|
||||
const router = useRouter();
|
||||
const id = useId();
|
||||
const [email, setEmail] = useState("");
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [sentTo, setSentTo] = useState<string | null>(pending);
|
||||
|
||||
async function save(event: React.FormEvent) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch("/api/me/email", { method: "PUT", headers: { "content-type": "application/json" }, body: JSON.stringify({ email }) }).catch(() => null);
|
||||
setBusy(false);
|
||||
if (res?.ok) {
|
||||
setSentTo((await res.json()).pending);
|
||||
setEmail("");
|
||||
return;
|
||||
}
|
||||
const key = res ? ((await res.json().catch(() => ({}))).error as string | undefined) : undefined;
|
||||
setError(key && ["mailNotConfigured", "mailFailed", "tooMany", "mailSession"].includes(key) ? key : "unknown");
|
||||
}
|
||||
|
||||
async function remove() {
|
||||
setBusy(true);
|
||||
await fetch("/api/me/email", { method: "DELETE" }).catch(() => null);
|
||||
setBusy(false);
|
||||
setSentTo(null);
|
||||
router.refresh();
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<p className="text-sm text-muted-foreground">{t("intro")}</p>
|
||||
{verified ? <p className="font-medium">{t("verified", { email: verified })}</p> : null}
|
||||
{sentTo && sentTo !== verified ? (
|
||||
<p role="status" className="rounded-xl border border-border px-4 py-3 text-sm">
|
||||
{t("pending", { email: sentTo })}
|
||||
</p>
|
||||
) : null}
|
||||
{locked ? (
|
||||
<p className="rounded-xl border border-border px-4 py-3 text-sm">{t("locked")}</p>
|
||||
) : (
|
||||
<>
|
||||
<form onSubmit={save} className="flex flex-col gap-2">
|
||||
<Label htmlFor={id}>{t("label")}</Label>
|
||||
<Input id={id} type="email" autoComplete="email" inputMode="email" required value={email} onChange={(e) => setEmail(e.target.value)} />
|
||||
{error ? <ErrorNotice>{te(error)}</ErrorNotice> : null}
|
||||
<Button type="submit" disabled={busy || !email.trim()}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
</form>
|
||||
{verified || sentTo ? (
|
||||
<Button type="button" variant="ghost" className="self-start" disabled={busy} onClick={remove}>
|
||||
{t("remove")}
|
||||
</Button>
|
||||
) : null}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export type Slot = {
|
||||
locked: boolean;
|
||||
cookedAt: string | null;
|
||||
reason: Reason | null;
|
||||
plannedDay: string | null;
|
||||
};
|
||||
type Member = { id: string; name: string };
|
||||
export type SlotCost = { perPortion: number | null; confidence: number; cls: "cheap" | "normal" | "expensive" | null };
|
||||
@@ -46,12 +47,14 @@ export function PlanBoard({
|
||||
dishes,
|
||||
status,
|
||||
money,
|
||||
startDay,
|
||||
}: {
|
||||
slots: Slot[];
|
||||
members: Member[];
|
||||
dishes: Dish[];
|
||||
status: string;
|
||||
money: Budget;
|
||||
startDay: string | null;
|
||||
}) {
|
||||
const t = useTranslations("plan");
|
||||
const tc = useTranslations("costs");
|
||||
@@ -150,8 +153,13 @@ export function PlanBoard({
|
||||
busy={busy}
|
||||
reason={reasonText(slot.reason)}
|
||||
cost={costLine(slot)}
|
||||
days={dayOptions(startDay, slot.plannedDay, locale)}
|
||||
onMove={(by) => move(index, by)}
|
||||
onChange={(change) => act("PATCH", "/api/plan/slots", { id: slot.id, ...change })}
|
||||
onChange={(change) => {
|
||||
// Sofort zeigen, was gewählt ist; der Server-Stand folgt mit refresh().
|
||||
setSlots((all) => all.map((s) => (s.id === slot.id ? { ...s, ...change } : s)));
|
||||
return act("PATCH", "/api/plan/slots", { id: slot.id, ...change });
|
||||
}}
|
||||
onRemove={() => act("DELETE", "/api/plan/slots", { id: slot.id })}
|
||||
onReplace={() => openPicker({ mode: "replace", slotId: slot.id })}
|
||||
/>
|
||||
@@ -186,7 +194,7 @@ export function PlanBoard({
|
||||
) : null}
|
||||
|
||||
{status === "open" && slots.length ? (
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 bg-background py-2">
|
||||
<Button type="button" size="lg" className="w-full" disabled={busy} onClick={() => act("POST", "/api/plan/approve")}>
|
||||
{t("approve")}
|
||||
</Button>
|
||||
@@ -226,6 +234,7 @@ function SlotCard({
|
||||
busy,
|
||||
reason,
|
||||
cost,
|
||||
days,
|
||||
onMove,
|
||||
onChange,
|
||||
onRemove,
|
||||
@@ -238,8 +247,9 @@ function SlotCard({
|
||||
busy: boolean;
|
||||
reason: string | null;
|
||||
cost: { text: string; dots: number } | null;
|
||||
days: { value: string; label: string }[];
|
||||
onMove: (by: number) => void;
|
||||
onChange: (change: object) => void;
|
||||
onChange: (change: Partial<Slot>) => void;
|
||||
onRemove: () => void;
|
||||
onReplace: () => void;
|
||||
}) {
|
||||
@@ -277,6 +287,7 @@ function SlotCard({
|
||||
<Confidence dots={cost.dots} label={tc(`confidence.${cost.dots}`)} />
|
||||
</p>
|
||||
) : null}
|
||||
{slot.plannedDay ? <p className="text-sm font-semibold">{days.find((d) => d.value === slot.plannedDay)?.label}</p> : null}
|
||||
{cooked ? <p className="text-sm font-semibold text-accent">{t("cooked")}</p> : null}
|
||||
</div>
|
||||
</div>
|
||||
@@ -305,6 +316,20 @@ function SlotCard({
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label={t("day", { title: slot.title ?? "" })}
|
||||
value={slot.plannedDay ?? ""}
|
||||
disabled={busy}
|
||||
onChange={(e) => onChange({ plannedDay: e.target.value || null })}
|
||||
className="min-h-11 w-full rounded-xl border border-border bg-background px-3 text-base"
|
||||
>
|
||||
<option value="">{t("noDay")}</option>
|
||||
{days.map((d) => (
|
||||
<option key={d.value} value={d.value}>
|
||||
{d.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="flex w-full items-center justify-between gap-1">
|
||||
<div className="flex gap-1">
|
||||
<Button type="button" variant="ghost" size="icon" aria-label={t("up", { title: slot.title ?? "" })} disabled={busy || index === 0} onClick={() => onMove(-1)}>
|
||||
@@ -341,6 +366,23 @@ function SlotCard({
|
||||
);
|
||||
}
|
||||
|
||||
// Tage zur Wahl (26.11.45, nur von Hand): 14 ab dem Einkaufstag, ohne ihn ab heute.
|
||||
// Ein schon gesetzter Tag außerhalb bleibt wählbar.
|
||||
export function dayOptions(start: string | null, current: string | null, locale: string): { value: string; label: string }[] {
|
||||
const fmt = new Intl.DateTimeFormat(locale, { weekday: "short", day: "numeric", month: "short" });
|
||||
const iso = (d: Date) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
|
||||
const first = start ? new Date(`${start}T12:00:00`) : new Date();
|
||||
first.setHours(12, 0, 0, 0);
|
||||
const out: { value: string; label: string }[] = [];
|
||||
for (let i = 0; i < 14; i++) {
|
||||
const d = new Date(first);
|
||||
d.setDate(first.getDate() + i);
|
||||
out.push({ value: iso(d), label: fmt.format(d) });
|
||||
}
|
||||
if (current && !out.some((o) => o.value === current)) out.unshift({ value: current, label: fmt.format(new Date(`${current}T12:00:00`)) });
|
||||
return out;
|
||||
}
|
||||
|
||||
function DishPicker({ title, dishes, onPick, onClose }: { title: string; dishes: Dish[]; onPick: (id: string) => void; onClose: () => void }) {
|
||||
const t = useTranslations("plan");
|
||||
const [query, setQuery] = useState("");
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
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; 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.
|
||||
export function RoundActions({ current, canDelete }: { current: Current; canDelete: boolean }) {
|
||||
const t = useTranslations("plan.round");
|
||||
const router = useRouter();
|
||||
const [editing, setEditing] = useState(false);
|
||||
const [armed, setArmed] = useState<"end" | "delete" | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
async function run(kind: "end" | "delete") {
|
||||
if (armed !== kind) return setArmed(kind);
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
const res = await fetch(`/api/rounds/${kind}`, { method: "POST" });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
setBusy(false);
|
||||
setArmed(null);
|
||||
if (res.ok) {
|
||||
router.push("/plan");
|
||||
router.refresh();
|
||||
} else setError(data.error === "cooked" ? "cooked" : "unknown");
|
||||
}
|
||||
|
||||
return (
|
||||
<section aria-labelledby="round-actions" className="flex flex-col gap-3 rounded-2xl border border-border p-4">
|
||||
<h2 id="round-actions" className="eyebrow">
|
||||
{t("title")}
|
||||
</h2>
|
||||
{editing ? (
|
||||
<RoundForm defaultPortions={current.defaultPortions} current={current} onDone={() => setEditing(false)} />
|
||||
) : (
|
||||
<Button type="button" variant="outline" onClick={() => setEditing(true)}>
|
||||
{t("edit")}
|
||||
</Button>
|
||||
)}
|
||||
{editing ? (
|
||||
<Button type="button" variant="ghost" onClick={() => setEditing(false)}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button type="button" variant={armed === "end" ? "default" : "outline"} disabled={busy} onBlur={() => setArmed(null)} onClick={() => run("end")}>
|
||||
{armed === "end" ? t("confirmEnd") : t("end")}
|
||||
</Button>
|
||||
<p className="text-sm text-muted-foreground">{t("endHint")}</p>
|
||||
{canDelete ? (
|
||||
<Button type="button" variant={armed === "delete" ? "default" : "ghost"} disabled={busy} onBlur={() => setArmed(null)} onClick={() => run("delete")}>
|
||||
{armed === "delete" ? t("confirmDelete") : t("delete")}
|
||||
</Button>
|
||||
) : null}
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -281,7 +281,7 @@ export function ReceiptReview({ receipt }: { receipt: Receipt }) {
|
||||
{done ? (
|
||||
<p className="text-sm text-muted-foreground">{t("doneText")}</p>
|
||||
) : (
|
||||
<div className="sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<div className="kb-shift sticky bottom-[var(--nav-space)] z-10 flex gap-2 bg-background py-2">
|
||||
<Button type="button" variant="outline" disabled={busy} onClick={remove} aria-label={t("delete")}>
|
||||
<Trash2 aria-hidden />
|
||||
</Button>
|
||||
|
||||
@@ -5,7 +5,8 @@ import { useLocale, useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { formatQuantity } from "@/lib/units";
|
||||
import { VoiceAdd } from "@/components/shopping/voice-add";
|
||||
import { formatQuantity, type PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Item = {
|
||||
@@ -16,6 +17,8 @@ export type Item = {
|
||||
unit: "g" | "ml" | "piece" | null;
|
||||
packCount: number | null;
|
||||
packSize: number | null;
|
||||
/** Gebinde („2 Dosen à 400 g“), seit 26.11.39. */
|
||||
packKind?: PackKind | null;
|
||||
dishes: string[];
|
||||
aislePosition: number | null;
|
||||
manual: boolean;
|
||||
@@ -44,8 +47,9 @@ function writeQueue(ops: Op[]) {
|
||||
// Einkaufsliste (Konzept, „Einkaufen“): große Haken, nach Gängen des Hauptladens,
|
||||
// in Echtzeit bei allen (SSE), und ohne Netz bedienbar — Haken landen in einer
|
||||
// Warteschlange im Browser und gehen raus, sobald wieder Netz da ist.
|
||||
export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles: Aisle[]; me: string }) {
|
||||
export function ShoppingList({ initial, aisles, me, canRecord = false }: { initial: Item[]; aisles: Aisle[]; me: string; canRecord?: boolean }) {
|
||||
const t = useTranslations("shopping");
|
||||
const tm = useTranslations("measure");
|
||||
const locale = useLocale();
|
||||
const [items, setItems] = useState(initial);
|
||||
const [queue, setQueue] = useState<Op[]>([]);
|
||||
@@ -128,6 +132,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
|
||||
async function send(method: string, url: string, body: object) {
|
||||
const res = await fetch(url, { method, headers: { "content-type": "application/json" }, body: JSON.stringify(body) }).catch(() => null);
|
||||
if (res?.ok) await reload();
|
||||
return !!res?.ok;
|
||||
}
|
||||
|
||||
const amount = (i: Item) => {
|
||||
@@ -135,6 +140,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
|
||||
if (i.unit === "piece") return t("pieces", { n: i.qty });
|
||||
if (i.packCount && i.packSize) {
|
||||
const f = formatQuantity(i.packSize, i.unit, locale);
|
||||
if (i.packKind) return t("packOf", { count: i.packCount, word: tm(i.packKind, { n: i.packCount }), size: `${f.amount} ${f.unit}` });
|
||||
return i.packCount > 1 ? `${i.packCount} × ${f.amount} ${f.unit}` : `${f.amount} ${f.unit}`;
|
||||
}
|
||||
const f = formatQuantity(i.qty, i.unit, locale);
|
||||
@@ -208,6 +214,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
|
||||
<Plus aria-hidden />
|
||||
</Button>
|
||||
</form>
|
||||
{canRecord ? <VoiceAdd onAdd={(labels) => send("POST", "/api/shopping/items", { labels })} /> : null}
|
||||
|
||||
{done.length ? (
|
||||
<section className="flex flex-col gap-1" aria-labelledby="cart-title">
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"use client";
|
||||
|
||||
import { Mic, Square, X } from "lucide-react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { useRecorder } from "@/lib/use-recorder";
|
||||
|
||||
const mmss = (s: number) => `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
||||
|
||||
// Einkaufsliste einsprechen (Kai, 8.11.2026, 26.11.46): aufnehmen, Abschrift in
|
||||
// Posten zerlegen (lib/spoken-list.ts), prüfen und ändern, dann hinzufügen.
|
||||
export function VoiceAdd({ onAdd }: { onAdd: (labels: string[]) => Promise<boolean> }) {
|
||||
const t = useTranslations("shopping.voice");
|
||||
const [busy, setBusy] = useState<"transcribe" | "add" | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [items, setItems] = useState<string[] | null>(null);
|
||||
const rec = useRecorder(upload);
|
||||
|
||||
async function upload(audio: Blob) {
|
||||
setBusy("transcribe");
|
||||
const form = new FormData();
|
||||
form.append("audio", new File([audio], "aufnahme", { type: audio.type }));
|
||||
const res = await fetch("/api/shopping/voice", { method: "POST", body: form }).catch(() => null);
|
||||
const data = await res?.json().catch(() => ({}));
|
||||
setBusy(null);
|
||||
if (!res?.ok) return setError(["noSpeech", "aiUnavailable", "empty", "audio"].includes(data?.error) ? data.error : "unknown");
|
||||
if (!data.items?.length) return setError("empty");
|
||||
setItems(data.items);
|
||||
}
|
||||
|
||||
async function add() {
|
||||
const labels = (items ?? []).map((i) => i.trim()).filter(Boolean);
|
||||
if (!labels.length) return;
|
||||
setBusy("add");
|
||||
const ok = await onAdd(labels);
|
||||
setBusy(null);
|
||||
if (ok) setItems(null);
|
||||
else setError("unknown");
|
||||
}
|
||||
|
||||
const filled = (items ?? []).filter((i) => i.trim()).length;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-3">
|
||||
<Button
|
||||
type="button"
|
||||
variant={rec.recording ? "default" : "outline"}
|
||||
size="icon"
|
||||
disabled={busy !== null || items !== null}
|
||||
aria-label={rec.recording ? t("stop") : t("record")}
|
||||
onClick={async () => {
|
||||
setError(null);
|
||||
if (rec.recording) rec.stop();
|
||||
else if (!(await rec.start())) setError("mic");
|
||||
}}
|
||||
>
|
||||
{rec.recording ? <Square aria-hidden /> : <Mic aria-hidden />}
|
||||
</Button>
|
||||
<p aria-live="polite" className="text-sm text-muted-foreground">
|
||||
{rec.recording ? t("recording", { time: mmss(rec.seconds) }) : busy === "transcribe" ? t("transcribing") : items ? null : t("hint")}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{items ? (
|
||||
<section aria-labelledby="voice-items" className="flex flex-col gap-2 rounded-2xl bg-muted p-4">
|
||||
<h2 id="voice-items" className="eyebrow">
|
||||
{t("check")}
|
||||
</h2>
|
||||
<ul className="flex flex-col gap-2">
|
||||
{items.map((item, i) => (
|
||||
<li key={i} className="flex items-center gap-2">
|
||||
<Input
|
||||
aria-label={t("item", { n: i + 1 })}
|
||||
value={item}
|
||||
maxLength={80}
|
||||
onChange={(e) => setItems((all) => all!.map((x, j) => (j === i ? e.target.value : x)))}
|
||||
/>
|
||||
<Button type="button" variant="ghost" size="icon" aria-label={t("drop", { name: item })} onClick={() => setItems((all) => all!.filter((_, j) => j !== i))}>
|
||||
<X aria-hidden />
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<Button type="button" disabled={busy !== null || !filled} onClick={add}>
|
||||
{t("add", { n: filled })}
|
||||
</Button>
|
||||
<Button type="button" variant="ghost" disabled={busy !== null} onClick={() => setItems(null)}>
|
||||
{t("discard")}
|
||||
</Button>
|
||||
</section>
|
||||
) : null}
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -8,6 +8,8 @@ export const Input = React.forwardRef<HTMLInputElement, React.InputHTMLAttribute
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"flex min-h-11 w-full rounded-xl border border-border bg-background px-4 py-2 text-base text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
|
||||
// Fehlt etwas, sieht man es (26.11.51): rote, breitere Kante — dazu immer ein Satz am Feld.
|
||||
"aria-[invalid=true]:border-2 aria-[invalid=true]:border-over",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
@@ -36,27 +47,46 @@ function Stepper({ id, value, min, max, onChange, label }: { id: string; value:
|
||||
);
|
||||
}
|
||||
|
||||
export function RoundForm({ defaultPortions }: { defaultPortions: number }) {
|
||||
// Mit `current` ändert das Formular die laufende Runde (26.11.45), sonst eröffnet es eine.
|
||||
export function RoundForm({
|
||||
defaultPortions,
|
||||
current,
|
||||
onDone,
|
||||
}: {
|
||||
defaultPortions: number;
|
||||
current?: { shoppingDate: string | null; slotsCount: number; defaultPortions: number; wishDeadline?: string | null };
|
||||
onDone?: () => void;
|
||||
}) {
|
||||
const t = useTranslations("round");
|
||||
const router = useRouter();
|
||||
const [date, setDate] = useState(nextSaturday);
|
||||
const [slots, setSlots] = useState(5);
|
||||
const [portions, setPortions] = useState(defaultPortions);
|
||||
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: "POST",
|
||||
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);
|
||||
if (res.ok) {
|
||||
if (res.ok && current) {
|
||||
onDone?.();
|
||||
router.refresh();
|
||||
} else if (res.ok) {
|
||||
router.push("/");
|
||||
router.refresh();
|
||||
} else setError(data.error === "roundExists" ? "roundExists" : "unknown");
|
||||
@@ -66,14 +96,38 @@ export function RoundForm({ defaultPortions }: { defaultPortions: number }) {
|
||||
<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} />
|
||||
<p className="text-sm text-muted-foreground">{t("hint")}</p>
|
||||
{current ? null : <p className="text-sm text-muted-foreground">{t("hint")}</p>}
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
<Button type="submit" size="lg" disabled={busy}>
|
||||
{t("submit")}
|
||||
{current ? t("save") : t("submit")}
|
||||
</Button>
|
||||
</form>
|
||||
);
|
||||
|
||||
@@ -97,7 +97,6 @@ export function WishBoard({
|
||||
const mineOf = (id: string) => (byDish.get(id) ?? []).filter((e) => e.isMine);
|
||||
const myDish = entries.find((e) => e.memberId === me && e.isMine);
|
||||
const myDishTitle = myDish ? tiles.find((x) => x.id === myDish.dishId)?.title : null;
|
||||
const wishedSomething = entries.some((e) => e.memberId === me && !e.isVeto);
|
||||
const shown = applyFilter(tiles, filter);
|
||||
|
||||
async function call(method: string, url: string, body?: object, key = "x") {
|
||||
@@ -108,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
|
||||
@@ -174,12 +173,12 @@ export function WishBoard({
|
||||
<Heart aria-hidden className="size-4 shrink-0 fill-accent text-accent" />
|
||||
{t("mineChosen", { title: myDishTitle })}
|
||||
</p>
|
||||
) : wishedSomething ? (
|
||||
) : (
|
||||
<p className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Heart aria-hidden className="size-4 shrink-0" />
|
||||
{t("mineHint")}
|
||||
</p>
|
||||
) : null}
|
||||
)}
|
||||
|
||||
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
|
||||
{message ? (
|
||||
@@ -189,7 +188,7 @@ export function WishBoard({
|
||||
) : null}
|
||||
|
||||
{shown.length ? (
|
||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
<ul className="grid grid-cols-2 gap-3">
|
||||
{shown.map((tile) => {
|
||||
const own = mine(tile.id);
|
||||
const names = wishers(tile.id).map((e) => (e.memberId === me ? t("you") : e.memberName));
|
||||
@@ -218,12 +217,6 @@ export function WishBoard({
|
||||
<Check aria-hidden className="size-5" />
|
||||
</span>
|
||||
) : null}
|
||||
{mineNames.length ? (
|
||||
<span aria-hidden className="absolute right-2 top-2 inline-flex items-center gap-1 rounded-full bg-background/90 px-2 py-1 text-xs font-semibold">
|
||||
<Heart aria-hidden className={cn("size-4 text-accent", isMyDish && "fill-accent")} />
|
||||
{isMyDish ? t("mine") : t("mineOf", { names: mineNames.filter((n) => n !== t("you")).join(", ") })}
|
||||
</span>
|
||||
) : null}
|
||||
{favorite ? (
|
||||
<span aria-hidden className="absolute bottom-2 left-2 inline-flex items-center gap-1 rounded-full bg-background/90 px-2 py-1 text-xs font-semibold">
|
||||
<Crown aria-hidden className="size-4 text-accent" />
|
||||
@@ -234,7 +227,12 @@ export function WishBoard({
|
||||
<span className="flex min-h-11 flex-col gap-0.5 p-3 pr-12">
|
||||
<span className="font-semibold text-lg leading-snug">{tile.title}</span>
|
||||
{favorite ? <span className="sr-only">{t("favorite")}</span> : null}
|
||||
{mineNames.length ? <span className="sr-only">{isMyDish ? t("mine") : t("mineOf", { names: mineNames.join(", ") })}</span> : null}
|
||||
{mineNames.length ? (
|
||||
<span className="inline-flex items-center gap-1 text-xs font-semibold">
|
||||
<Heart aria-hidden className={cn("size-3.5 shrink-0 text-accent", isMyDish && "fill-accent")} />
|
||||
{isMyDish ? t("mine") : t("mineOf", { names: mineNames.filter((n) => n !== t("you")).join(", ") })}
|
||||
</span>
|
||||
) : null}
|
||||
{names.length ? <span className="text-xs text-muted-foreground">{t("wishedBy", { names: names.join(", ") })}</span> : null}
|
||||
{vetoList.length && !mineNames.length ? (
|
||||
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
|
||||
@@ -244,6 +242,22 @@ export function WishBoard({
|
||||
) : null}
|
||||
</span>
|
||||
</button>
|
||||
{/* Herz (Kai, 8.11.2026, 26.11.47): ein Tipp macht das Gericht zu meinem —
|
||||
noch nicht gewünscht, wird es dabei gewünscht (ein Jeton). */}
|
||||
{own?.isVeto || own?.viaVeto ? null : (
|
||||
<button
|
||||
type="button"
|
||||
aria-pressed={isMyDish}
|
||||
aria-label={isMyDish ? t("mineUntoggle", { title: tile.title }) : t("mineToggle", { title: tile.title })}
|
||||
disabled={!!busy}
|
||||
onClick={() => call("POST", "/api/wishes/mine", isMyDish ? { dishId: tile.id, mine: false } : { dishId: tile.id, mine: true, wish: true }, tile.id)}
|
||||
className="absolute right-1 top-1 flex size-11 items-center justify-center rounded-full focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
>
|
||||
<span className="flex size-9 items-center justify-center rounded-full bg-background/90 shadow-sm">
|
||||
<Heart aria-hidden className={cn("size-5", isMyDish ? "fill-accent text-accent" : "text-foreground")} />
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Löffel und Gebinde (Kai, 7.11.2026, 26.11.39).
|
||||
--
|
||||
-- Mengen bleiben in der Basiseinheit pro Portion gespeichert (CLAUDE.md, Regel 2).
|
||||
-- Dazu kommt, in welchem Küchenmaß sie eingegeben wurden (display_unit), damit
|
||||
-- das Rezept „2 EL (30 ml)“ zeigt statt nur „30 ml“, und „400 g (1 Dose)“.
|
||||
--
|
||||
-- An der Zutat: das übliche Küchenmaß (kitchen_unit, vorgewählt im Formular)
|
||||
-- und das übliche Gebinde mit Größe in der Basiseinheit (pack_kind, pack_size).
|
||||
-- Ein Haushalt kann die Größe ändern (household_pack_sizes); ein Produkt mit
|
||||
-- Packungsgröße am Gericht geht vor.
|
||||
|
||||
alter table ingredients add column kitchen_unit text
|
||||
check (kitchen_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_size numeric(12, 3) check (pack_size is null or pack_size > 0);
|
||||
|
||||
alter table dish_ingredients add column display_unit text
|
||||
check (display_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
alter table shopping_items add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
create table household_pack_sizes (
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
ingredient_id uuid not null references ingredients (id) on delete cascade,
|
||||
pack_size numeric(12, 3) not null check (pack_size > 0),
|
||||
updated_at timestamptz not null default now(),
|
||||
primary key (household_id, ingredient_id)
|
||||
);
|
||||
alter table household_pack_sizes enable row level security;
|
||||
alter table household_pack_sizes force row level security;
|
||||
create policy household_pack_sizes_household on household_pack_sizes
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
@@ -0,0 +1,54 @@
|
||||
-- Anmelden per Link aus der Mail (Kai, 7.11.2026, 26.11.40; E-0006, E-0017).
|
||||
--
|
||||
-- Mailweg je Haushalt (Resend über SMTP): Das Passwort (API-Schlüssel) liegt
|
||||
-- nur verschlüsselt hier (lib/vault.ts, tresor.key), wie bei household_ai.
|
||||
--
|
||||
-- Wer sich per Mail anmelden will, trägt seine Adresse selbst ein und bestätigt
|
||||
-- sie über einen ersten Link (email_verified_at). Ohne Bestätigung keine Mail.
|
||||
--
|
||||
-- mail_tokens: Einmal-Links zum Anmelden (15 Minuten) und zum Bestätigen
|
||||
-- (24 Stunden); gespeichert nur der Hash. Eine Sitzung merkt sich, womit sie
|
||||
-- begann (via): Wer per Mail kam, darf nur anmelden — keine Geräte, keine
|
||||
-- Passkeys, keine Einladungen (E-0006).
|
||||
|
||||
create table household_mail (
|
||||
household_id uuid primary key references households (id) on delete cascade,
|
||||
host text not null check (length(host) between 1 and 200),
|
||||
port integer not null check (port between 1 and 65535),
|
||||
secure boolean not null default true,
|
||||
username text not null check (length(username) between 1 and 200),
|
||||
password_enc bytea,
|
||||
from_address text not null check (from_address = lower(from_address) and from_address like '%@%'),
|
||||
from_name text check (length(from_name) <= 80),
|
||||
updated_by uuid references members (id) on delete set null,
|
||||
updated_at timestamptz not null default now()
|
||||
);
|
||||
alter table household_mail enable row level security;
|
||||
alter table household_mail force row level security;
|
||||
create policy household_mail_household on household_mail
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
|
||||
alter table members add column email_verified_at timestamptz;
|
||||
|
||||
create table mail_tokens (
|
||||
id uuid primary key default gen_random_uuid(),
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
member_id uuid not null references members (id) on delete cascade,
|
||||
purpose text not null check (purpose in ('login', 'verify')),
|
||||
email text not null check (email = lower(email)),
|
||||
token_hash bytea not null unique,
|
||||
created_at timestamptz not null default now(),
|
||||
expires_at timestamptz not null,
|
||||
used_at timestamptz
|
||||
);
|
||||
create index mail_tokens_member_idx on mail_tokens (member_id);
|
||||
alter table mail_tokens enable row level security;
|
||||
alter table mail_tokens force row level security;
|
||||
-- Wie invitations: im Haushalt und für die Anmeldung, die den Haushalt erst findet.
|
||||
create policy mail_tokens_household on mail_tokens
|
||||
using (household_id = app_household_id() or app_auth())
|
||||
with check (household_id = app_household_id() or app_auth());
|
||||
|
||||
alter table sessions add column via text not null default 'passkey' check (via in ('passkey', 'mail', 'kid'));
|
||||
update sessions set via = 'kid' where kid_device_id is not null;
|
||||
@@ -0,0 +1,8 @@
|
||||
-- Kalender-Abo (Kai, 8.11.2026, 26.11.45): ein Link je Haushalt, gespeichert nur
|
||||
-- sein Hash. Die Gerichte erscheinen an ihrem Tag (slots.planned_day, von Hand)
|
||||
-- zur Essenszeit des Haushalts.
|
||||
|
||||
alter table households add column calendar_token_hash bytea unique;
|
||||
alter table households add column meal_time time not null default '18:30';
|
||||
alter table households add column meal_minutes integer not null default 60 check (meal_minutes between 15 and 240);
|
||||
alter table households add column calendar_locale text not null default 'de' check (calendar_locale in ('de', 'en', 'fr', 'es'));
|
||||
@@ -0,0 +1,38 @@
|
||||
-- Rezept bearbeiten (Kai, 8.11.2026, 26.11.49).
|
||||
--
|
||||
-- 1. Ein Gericht merkt sich, für wie viele Portionen es eingegeben wurde. Bearbeiten
|
||||
-- zeigt die Mengen dann wieder so („500 g für 6“), statt immer für vier.
|
||||
-- 2. Mehr Maße: Tasse, Schuss, Messerspitze (fest), Becher, Stück, Würfel, Zehe,
|
||||
-- Scheibe (mit Größe je Zutat). Die Größen eines Haushalts gelten jetzt je
|
||||
-- Zutat und Maß: „1 Packung Hackfleisch = 500 g“, „1 Zehe Knoblauch = 3 g“.
|
||||
|
||||
alter table dishes add column recipe_portions integer check (recipe_portions between 1 and 30);
|
||||
|
||||
alter table ingredients drop constraint ingredients_kitchen_unit_check;
|
||||
alter table ingredients add constraint ingredients_kitchen_unit_check check (kitchen_unit in
|
||||
('tbsp', 'tsp', 'pinch', 'cup', 'dash', 'knifepoint', 'can', 'jar', 'pack', 'tub', 'bunch', 'piece', 'cube', 'clove', 'slice'));
|
||||
alter table ingredients drop constraint ingredients_pack_kind_check;
|
||||
alter table ingredients add constraint ingredients_pack_kind_check check (pack_kind in ('can', 'jar', 'pack', 'tub', 'bunch'));
|
||||
|
||||
alter table dish_ingredients drop constraint dish_ingredients_display_unit_check;
|
||||
alter table dish_ingredients add constraint dish_ingredients_display_unit_check check (display_unit in
|
||||
('tbsp', 'tsp', 'pinch', 'cup', 'dash', 'knifepoint', 'can', 'jar', 'pack', 'tub', 'bunch', 'piece', 'cube', 'clove', 'slice'));
|
||||
|
||||
alter table shopping_items drop constraint shopping_items_pack_kind_check;
|
||||
alter table shopping_items add constraint shopping_items_pack_kind_check check (pack_kind in ('can', 'jar', 'pack', 'tub', 'bunch'));
|
||||
|
||||
-- Größen je Zutat und Maß. Bisherige Zeilen galten dem Gebinde der Zutat.
|
||||
-- Unter FORCE sähe dieses Update keine Zeile (kein Haushalt gesetzt) — für die Dauer
|
||||
-- der Migration (eine Transaktion, scripts/migrate.mjs) ohne FORCE, danach wieder mit.
|
||||
alter table household_pack_sizes add column unit text;
|
||||
alter table household_pack_sizes no force row level security;
|
||||
alter table ingredients no force row level security;
|
||||
update household_pack_sizes h set unit = i.pack_kind from ingredients i where i.id = h.ingredient_id;
|
||||
delete from household_pack_sizes where unit is null;
|
||||
alter table ingredients force row level security;
|
||||
alter table household_pack_sizes force row level security;
|
||||
alter table household_pack_sizes alter column unit set not null;
|
||||
alter table household_pack_sizes add constraint household_pack_sizes_unit_check check (unit in
|
||||
('can', 'jar', 'pack', 'tub', 'bunch', 'piece', 'cube', 'clove', 'slice'));
|
||||
alter table household_pack_sizes drop constraint household_pack_sizes_pkey;
|
||||
alter table household_pack_sizes add primary key (household_id, ingredient_id, unit);
|
||||
@@ -0,0 +1,13 @@
|
||||
-- Milliliter und Liter überall (Kai, 8.11.2026, 26.11.50): auch bei Stück-Zutaten
|
||||
-- („750 ml Brühe“ aus Brühwürfeln). Die Größe steht dann als ml bzw. g je Stück
|
||||
-- unter dem Maß „ml“ bzw. „g“; kg und l nutzen sie mit. Das Rezept merkt sich das
|
||||
-- eingegebene Maß auch, wenn es Gewicht oder Volumen ist („200 ml“ Joghurt).
|
||||
|
||||
alter table household_pack_sizes drop constraint household_pack_sizes_unit_check;
|
||||
alter table household_pack_sizes add constraint household_pack_sizes_unit_check check (unit in
|
||||
('can', 'jar', 'pack', 'tub', 'bunch', 'piece', 'cube', 'clove', 'slice', 'g', 'ml'));
|
||||
|
||||
alter table dish_ingredients drop constraint dish_ingredients_display_unit_check;
|
||||
alter table dish_ingredients add constraint dish_ingredients_display_unit_check check (display_unit in
|
||||
('tbsp', 'tsp', 'pinch', 'cup', 'dash', 'knifepoint', 'can', 'jar', 'pack', 'tub', 'bunch', 'piece', 'cube', 'clove', 'slice',
|
||||
'g', 'kg', 'ml', 'l'));
|
||||
@@ -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;
|
||||
+492
-130
File diff suppressed because it is too large.
Load diff
+168
-1
@@ -177,7 +177,7 @@ acht Paletten Variante H gewählt). Löst die Palette aus E-0002 ab; der Rest vo
|
||||
- **Schrift:** ~~Überschriften in Newsreader, Text in Geist~~ — seit 26.11.37 Poppins
|
||||
überall (E-0014).
|
||||
- **Abschnitte** ohne Kasten, getrennt durch feine Linien.
|
||||
- **Symbol:** Teller mit Dampf auf Coral, Blatt in Lavendel (`docs/icon/lunch.svg`).
|
||||
- **Symbol:** Kochmütze mit Herz auf Coral (seit 26.11.42, Kai: Entwurf a; vorher Teller mit Dampf und Lavendel-Blatt), `docs/icon/lunch.svg`.
|
||||
- **Kontrast** jeder Schrift auf ihrer Fläche mindestens 4,5:1, hell und dunkel —
|
||||
`tests/contrast.test.ts` rechnet ihn aus den Token.
|
||||
|
||||
@@ -275,3 +275,170 @@ abgewiesen. Eigene Zutaten gehen in die Sicherung.
|
||||
**Lieblingsprodukt.** Es gilt je Zutat für den ganzen Haushalt (`household_products`) und
|
||||
wird mit dem Haken „Für alle Gerichte mit … merken“ gesetzt. Ein Produkt, das am Gericht
|
||||
selbst steht, geht immer vor.
|
||||
|
||||
## E-0016 · Löffel und Gebinde als Mengeneinheiten
|
||||
|
||||
*7.11.2026 · Kai („Teelöffel, Esslöffel … eine Dose als Einheit … natürlich muss auch die Grammzahl dort stehen“)*
|
||||
|
||||
**Gespeichert** wird weiter in der Basiseinheit pro Portion (Regel 2). Dazu hält
|
||||
`dish_ingredients.display_unit` fest, in welchem Maß die Menge eingegeben wurde:
|
||||
EL, TL, Prise, Dose, Glas, Packung oder Bund. Hochrechnen, Einkaufsliste und
|
||||
Preise rechnen also unverändert.
|
||||
|
||||
**Anzeige** (Kais Wahl):
|
||||
- Löffel stehen vorn, die Gramm in Klammern: „2 EL (30 ml)“. Die Prise hat keine Klammer.
|
||||
- Gebinde zeigen die Gramm zuerst: „400 g (1 Dose)“, hochgerechnet in Küchenbrüchen.
|
||||
- Weniger als eine Viertel Packung zeigt nur Gramm.
|
||||
- Ältere Gerichte und Vorlagen ohne Maß bekommen Löffel, wenn es ½ bis 8 sind, und
|
||||
ein Gebinde ab einer Viertel Packung. Prisen bekommen sie nie von selbst.
|
||||
|
||||
**An der Zutat:**
|
||||
- Das übliche Löffelmaß wird im Formular vorgewählt (Olivenöl in EL, Kreuzkümmel in TL, Salz in Prisen).
|
||||
- Das übliche Gebinde und seine Größe (gehackte Tomaten: Dose, 400 g) werden angeboten, mit der Größe in der Auswahl.
|
||||
- Ein Gebinde wird **nie vorgewählt**: Wer nach „Kokosmilch“ gleich „400“ tippt, meint Milliliter.
|
||||
|
||||
**Größe eines Gebindes:** Es gilt zuerst das Produkt am Gericht, dann das Lieblingsprodukt
|
||||
des Haushalts, dann die Haushaltsgröße (`household_pack_sizes`, ändern darf, wer Gerichte
|
||||
pflegt), zuletzt die Vorgabe. Beim Einlesen von Rezepten kommt die Größe aus der Zutat,
|
||||
nie aus dem Text oder einem Modell.
|
||||
|
||||
## E-0017 · Mail-Link über Resend: nur anmelden
|
||||
|
||||
*7.11.2026 · Kai („Dann lieber resend“). Folgt E-0006.*
|
||||
|
||||
**Mailweg:** Resend über SMTP, Server `smtp.resend.com`, Port 465 mit TLS von
|
||||
Anfang an, Benutzer `resend`, Passwort ist ein API-Schlüssel. Der Absender ist
|
||||
`hallo@foodplanhero.de`.
|
||||
- Je Haushalt in `household_mail`. Der Schlüssel liegt nur verschlüsselt dort
|
||||
(`lib/vault.ts`) und kommt mit `tresor.key` in die Sicherung.
|
||||
- Die Felder bleiben änderbar, falls Resend etwas ändert.
|
||||
- Cloudflare Email Sending wäre möglich gewesen, braucht aber den bezahlten
|
||||
Workers-Tarif. Brevo war für die Domain schon vorbereitet. Kai hat Resend
|
||||
gewählt.
|
||||
|
||||
**Wer:** Nur wer es selbst einschaltet. Die Person trägt ihre Adresse unter Mehr
|
||||
ein und bestätigt sie über einen ersten Link (24 Stunden). Erwachsene und
|
||||
Jugendliche dürfen das, Kinder und Gäste nicht.
|
||||
|
||||
**Der Link:** Er gilt 15 Minuten und einmal; gespeichert ist nur der Hash.
|
||||
- Er steht hinter `#` auf `/anmelden/mail`. Eingelöst wird er erst per POST nach
|
||||
einem Tipp, so verbrauchen Mail-Scanner ihn nicht.
|
||||
- Die Antwort auf eine Anfrage ist immer gleich; der Versand läuft im Hintergrund.
|
||||
|
||||
**Nur anmelden** (Kai): Eine Sitzung mit `via = 'mail'` darf Folgendes nicht:
|
||||
- Passkeys oder Geräte hinzufügen oder entfernen
|
||||
- Einladungen und Kindergeräte erstellen
|
||||
- Personen entfernen
|
||||
- Adresse oder Mailweg ändern
|
||||
|
||||
Das prüft `noMailSession` in `lib/auth/guard.ts`. Mail-Sitzungen gelten 30 Tage
|
||||
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
|
||||
Gerichte auf Wochentage verteilen … und diesen Kalender abonnieren“).*
|
||||
|
||||
**Runde:** Bis 26.11.44 endete eine Runde nur, wenn alles gekocht war; wer
|
||||
etwas ausließ, kam nie zur nächsten. Jetzt steht unter dem Plan der Abschnitt
|
||||
„Runde“:
|
||||
- **Einstellungen ändern:** Einkaufstag, Zahl der Mahlzeiten, Portionen.
|
||||
Vorhandene Gerichte bleiben, die Einkaufsliste rechnet sich neu.
|
||||
- **Runde beenden:** Gekochtes und Bewertungen bleiben Geschichte, Ungekochtes
|
||||
verfällt. Danach „Runde eröffnen“.
|
||||
- **Runde löschen:** nur solange nichts gekocht ist, damit keine Bewertung
|
||||
verloren geht. Wünsche, Plan und Einkaufsliste gehen mit.
|
||||
- Beenden und Löschen fragen im Knopf selbst nach (zweiter Tipp).
|
||||
- Eine beendete Runde wieder öffnen gibt es nicht (Kai).
|
||||
|
||||
**Tage:** nur von Hand, kein Vorschlag (Kai). Je Gericht eine Auswahl mit
|
||||
14 Tagen ab dem Einkaufstag; „Ohne Tag“ bleibt der Normalfall. Der Tag steht auf
|
||||
der Plankarte, auf „Heute“ und im Küchendisplay. Ein Tag darf mehrere Gerichte
|
||||
haben.
|
||||
|
||||
**Kalender:** ein Link je Haushalt (Kai), mit Uhrzeit (Kai): die Essenszeit des
|
||||
Haushalts, Vorgabe 18:30, eine Stunde.
|
||||
- Öffentlich unter `/kalender/<token>.ics`, iCalendar mit `TZID=Europe/Berlin`.
|
||||
- Gespeichert ist nur der Hash des Tokens; den Link sieht die Person einmal.
|
||||
„Neuen Link erzeugen“ macht den alten ungültig, „Abo beenden“ ebenso.
|
||||
- Nur Admins, nie aus einer Mail-Sitzung — der Link zeigt den Plan jedem, der
|
||||
ihn hat.
|
||||
- Inhalt: Titel, Tag, Koch, Portionen und ein Link zum Gericht. Keine Zutaten,
|
||||
keine Wünsche.
|
||||
- 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
|
||||
`lib/spoken-list.ts` ohne Sprachmodell in Posten (Komma, „und“, Satzende;
|
||||
Füllwörter wie „wir brauchen noch“, „bitte“ fallen weg). Die Person prüft und
|
||||
ändert die Posten, erst dann kommen sie unter „Sonstiges“ auf die Liste. Die
|
||||
Aufnahme wird nicht gespeichert.
|
||||
|
||||
**Nachtrag 26.11.47 · „Mein Gericht“ per Herz** (Kai, 8.11.2026, „Jede Karte“):
|
||||
Jede Wunschkarte trägt oben rechts ein Herz — Herz, nicht Stern, weil das Herz
|
||||
schon „Mein Gericht“ heißt und ein Stern nach Bewertung aussähe. Ein Tipp aufs
|
||||
leere Herz wünscht das Gericht (ein Jeton) und macht es zu meinem, in einer
|
||||
Transaktion (`setMine` mit `wishIn`): ohne Jeton entsteht nichts. Gefüllt
|
||||
nimmt ein Tipp es zurück, der Wunsch bleibt. Eins pro Runde, ein neues ersetzt
|
||||
das alte. Kein Herz an eigenen Vetos und an Wünschen aus einem Veto. Der Weg
|
||||
über „…“ bleibt.
|
||||
|
||||
**Nachtrag 26.11.49 · Portionen und mehr Maße** (Kai, 8.11.2026: „Mengen, Einheiten
|
||||
und Portionen kann ich nicht sauber eingeben“):
|
||||
- Ein Gericht merkt sich, für wie viele Portionen es eingegeben wurde
|
||||
(`dishes.recipe_portions`). Bearbeiten zeigt die Mengen wieder so, lesbar gerundet
|
||||
(`niceQty`), statt immer für vier.
|
||||
- Portionen umstellen rechnet die Mengen mit (Kai: „Mengen rechnen mit“), immer vom
|
||||
Stand beim Betreten des Feldes aus.
|
||||
- Feste Maße kommen dazu: Tasse, Schuss, Messerspitze.
|
||||
- Zählmaße gelten für jede Zutat: Dose, Glas, Packung, Becher, Bund, Stück, Würfel,
|
||||
Zehe, Scheibe. Ihre Größe kennt der Haushalt je Zutat und Maß
|
||||
(`household_pack_sizes.unit`), sonst das Gebinde der Zutat. Würfel, Zehe und
|
||||
Scheibe einer Stück-Zutat sind je ein Stück.
|
||||
- Fehlt eine Größe, fragt das Formular („Wie viel ist 1 Packung? (in g)“) und merkt
|
||||
sie sich. Gerechnet wird nie ohne sie.
|
||||
- Die Migration nimmt FORCE für die Dauer des Daten-Updates von
|
||||
`household_pack_sizes` und `ingredients`. Abzüge von vorher bekommen beim
|
||||
Zurückspielen das Maß aus dem Gebinde der Zutat.
|
||||
|
||||
**Nachtrag 26.11.50 · Milliliter und Liter überall** (Kai, 8.11.2026, „auch bei
|
||||
Stück-Zutaten“): Gramm-Zutaten nehmen auch ml und l, Flüssiges auch g und kg (1 zu 1,
|
||||
wie beim Löffel). Stück-Zutaten nehmen g, kg, ml und l mit einer Größe je Stück
|
||||
(„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.
|
||||
+7
-14
@@ -1,15 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
|
||||
<rect width="512" height="512" rx="112" fill="#f39380"/>
|
||||
<!-- Teller -->
|
||||
<circle cx="256" cy="292" r="142" fill="#fefdff"/>
|
||||
<circle cx="256" cy="292" r="98" fill="none" stroke="#e7e1f6" stroke-width="14"/>
|
||||
<!-- Dampf -->
|
||||
<g fill="none" stroke="#fefdff" stroke-width="18" stroke-linecap="round">
|
||||
<path d="M206 78c-16 18 16 30 0 48"/>
|
||||
<path d="M256 64c-16 20 16 34 0 54"/>
|
||||
<path d="M306 78c-16 18 16 30 0 48"/>
|
||||
</g>
|
||||
<!-- Salbeiblatt -->
|
||||
<path d="M206 316c20-62 86-82 116-72-6 52-58 98-116 72z" fill="#7761b0"/>
|
||||
<path d="M214 312c30-24 58-42 96-62" stroke="#fefdff" stroke-width="7" stroke-linecap="round" fill="none"/>
|
||||
</svg>
|
||||
<!-- foodplanhero (Kai, 7.11.2026, 26.11.42): Kochmütze mit Herz, für Maike. Koralle wie bisher. --><rect width="512" height="512" rx="112" fill="#f39380"/><g>
|
||||
<circle cx="178" cy="214" r="70" fill="#fefdff"/>
|
||||
<circle cx="256" cy="176" r="86" fill="#fefdff"/>
|
||||
<circle cx="334" cy="214" r="70" fill="#fefdff"/>
|
||||
<rect x="158" y="210" width="196" height="132" fill="#fefdff"/>
|
||||
<rect x="150" y="350" width="212" height="56" rx="20" fill="#fefdff"/>
|
||||
</g><path d="M256 318 C230 298 202 276 202 250 C202 230 217 218 234 218 C245 218 252 224 256 233 C260 224 267 218 278 218 C295 218 310 230 310 250 C310 276 282 298 256 318 Z" fill="#f39380"/></svg>
|
||||
|
Before Width: | Height: | Size: 719 B After Width: | Height: | Size: 720 B |
@@ -0,0 +1,148 @@
|
||||
# Login-Sicherheit: Lunch (foodplanhero) — Mail-Link
|
||||
|
||||
**Gesamturteil:** 🟢 solide. Der neue Weg „Anmelden per Mail“ hat nach den
|
||||
Korrekturen in diesem PR keine offenen Befunde über „niedrig“.
|
||||
|
||||
**Geprüft am 7.11.2026, vor der Auslieferung von 26.11.40.**
|
||||
- **Auth-Typ:** Passkeys bleiben der Hauptweg. Neu ist ein **Mail-Link als
|
||||
zweiter Weg zum Anmelden**, nur für Personen, die ihre Adresse selbst
|
||||
eingetragen und bestätigt haben.
|
||||
- **Versand:** Resend über SMTP. Der Schlüssel liegt verschlüsselt im Tresor.
|
||||
- **ASVS-Ziel:** L2 (personenbezogene Daten, Kinder).
|
||||
- **Live geprüft** gegen localhost mit dem Mail-Ordner statt echtem Versand
|
||||
(`MAIL_TEST_DIR`, `e2e/mail.spec.ts`):
|
||||
- einrichten und Testmail schicken
|
||||
- Adresse bestätigen
|
||||
- unbekannte Adresse anfragen
|
||||
- per Link anmelden
|
||||
- Rechte der Mail-Sitzung
|
||||
- denselben Link ein zweites Mal öffnen
|
||||
- **Ohne echten Versand:** Gegen Resend wurde nichts geschickt; jeder Versuch
|
||||
kostet Kontingent.
|
||||
- **Geprüfte Dateien:**
|
||||
- `lib/auth/mail-login.ts`
|
||||
- `lib/mail.ts`
|
||||
- `app/api/auth/mail/{request,verify}`
|
||||
- `app/api/me/email`
|
||||
- `app/api/household/mail{,/test}`
|
||||
- `components/auth/mail-link.tsx`
|
||||
- `lib/auth/guard.ts` (`noMailSession`)
|
||||
- `lib/auth/session.ts` (`via`)
|
||||
- `db/migrations/0024_mail_sign_in.sql`
|
||||
|
||||
**Grundannahme, ausgesprochen.** Wer das Postfach hat, kommt in Lunch hinein. Das
|
||||
gilt nur für Personen, die die Anmeldung per Mail selbst einschalten.
|
||||
|
||||
Der Link öffnet nur die Anmeldung. Er schafft keinen Zugang über das hinaus, was
|
||||
eine Sitzung ohnehin kann (Kai, E-0006/E-0017). Aus einer Mail-Sitzung geht
|
||||
Folgendes nicht:
|
||||
- Passkeys oder Geräte hinzufügen oder entfernen
|
||||
- Einladungen und Kindergeräte erstellen
|
||||
- Personen entfernen
|
||||
- die eigene Adresse oder den Mailweg ändern
|
||||
|
||||
Wer sein Postfach verliert, verliert also nicht dauerhaft das Konto. Ein Angreifer
|
||||
mit dem Postfach hat höchstens 30 Tage Zugriff und kann keinen bleibenden
|
||||
Zugang anlegen.
|
||||
|
||||
**Vertrauensgrenzen.**
|
||||
1. **Der Token läuft nur im Browser.** Er steht hinter `#`, geht also nie in
|
||||
Server-Logs, Proxy-Logs oder den `Referer`. Der Server sieht ihn erst im
|
||||
POST nach einem Tipp, und dieser POST muss vom eigenen Ursprung kommen
|
||||
(`sameOrigin`).
|
||||
2. **Datenzugriff vor der Anmeldung:** `withAuth()` darf die Haushaltsgrenze nun
|
||||
auch auf `mail_tokens` überspringen. Das ist bewusst so; der Wachtest
|
||||
`tests/rls.test.ts` hält die Liste fest. `household_mail` gehört nur dem
|
||||
Haushalt.
|
||||
3. **Fehlende Konfiguration:** Ohne Mailweg gibt es keinen Versand. Die Anfrage
|
||||
antwortet trotzdem gleich, es gibt keinen Rückfall auf einen anderen Weg.
|
||||
`MAIL_TEST_DIR` setzt nur die CI. Das Chart setzt es nicht.
|
||||
4. **Wege an der Anmeldung vorbei:** keine neuen.
|
||||
|
||||
**Abdeckung** (Abschnitt 3 „Magic Link“, dazu Bremse, Sitzung und CSRF für den
|
||||
neuen Weg): 14 Anforderungen geprüft.
|
||||
- 13 erfüllt, 0 verletzt. Vorher waren es 4, sie sind in diesem PR behoben.
|
||||
- 1 nicht angestrebt (6.6.2, Bindung des Links an das anfragende Gerät): Der
|
||||
Link soll auch auf einem anderen Gerät gehen.
|
||||
|
||||
## Sofort beheben
|
||||
|
||||
Keine.
|
||||
|
||||
## In diesem PR behoben
|
||||
|
||||
### 1. Mail-Kontingent und Postfach ließen sich fluten — niedrig (ASVS 6.3.1, 6.6.3)
|
||||
**Wo:** `app/api/auth/mail/request/route.ts`
|
||||
**Was passierte:** Mit wechselnden IPs ließen sich an eine bekannte, bestätigte
|
||||
Adresse rund 280 Mails am Tag schicken. Insgesamt waren bis zu 60 Anfragen je
|
||||
Viertelstunde möglich. Das reicht, um das Tageskontingent von Resend zu
|
||||
verbrauchen und die Person zu nerven.
|
||||
**Fix:** Je Adresse 3 Anfragen in 15 Minuten und 10 am Tag; gemeinsamer Topf
|
||||
30 Anfragen je Stunde; je IP wie bisher 10 in 15 Minuten.
|
||||
|
||||
### 2. „Adresse gehört schon jemand anderem“ verriet Konten — niedrig (ASVS 6.3.7)
|
||||
**Wo:** `app/api/me/email/route.ts`
|
||||
**Was passierte:** Wer angemeldet war, konnte durch Eintragen fremder Adressen
|
||||
prüfen, wer auf der Box ein Konto hat, auch in anderen Haushalten.
|
||||
**Fix:** Die Antwort ist immer gleich. Der Link in der Bestätigungsmail greift
|
||||
dann nicht (`consumeMailToken` prüft die Adresse).
|
||||
|
||||
### 3. Mail-Sitzungen überlebten das Entfernen der Adresse — niedrig (ASVS 7.4.x)
|
||||
**Wo:** `app/api/me/email/route.ts`, `lib/auth/mail-login.ts`
|
||||
**Was passierte:** Wer merkt, dass jemand sein Postfach mitliest, und die
|
||||
Adresse entfernt, beendete damit nicht die Sitzung, die über diese Adresse
|
||||
begann.
|
||||
**Fix:** Adresse entfernen oder eine neue bestätigen beendet alle Sitzungen mit
|
||||
`via = 'mail'`.
|
||||
|
||||
### 4. Mail-Sitzungen lebten so lange wie Passkey-Sitzungen — niedrig (ASVS 7.3.x)
|
||||
**Wo:** `lib/auth/session.ts`
|
||||
**Fix:** Mail-Sitzungen gelten 30 Tage gleitend statt 180.
|
||||
|
||||
Dazu als Härtung: Der Absendername wird ohne Steuerzeichen und Anführungszeichen
|
||||
in den Mailkopf gesetzt, damit niemand über das Feld einen eigenen Kopf
|
||||
einschleust. Ein Test wacht darüber.
|
||||
|
||||
## Bald angehen
|
||||
|
||||
Nichts Neues. Aus dem letzten Lauf sind weiter offen:
|
||||
- `kein-anmeldeprotokoll`
|
||||
- `keine-csp-hsts`
|
||||
- `sitzung-ohne-hoechstdauer`
|
||||
|
||||
## Später / Härtung
|
||||
|
||||
- **Antwortzeit:** Für eine bekannte Adresse legt die Anfrage zusätzlich einen
|
||||
Token an, das sind einige Millisekunden. Der Versand selbst läuft im
|
||||
Hintergrund. Über das Netz der Box lässt sich der Unterschied kaum messen.
|
||||
Bewertung: Info.
|
||||
- **Mail-Scanner:** Sie verbrauchen keine Links, weil das Einlösen einen Tipp
|
||||
braucht. Ein Scanner, der Knöpfe drückt, würde die Person in seinem Browser
|
||||
anmelden, nicht im Browser des Angreifers. Bewertung: Info.
|
||||
|
||||
## Offene Fragen
|
||||
|
||||
- **Echter Versand** über Resend. Erst prüfbar, wenn Kai den Schlüssel eingetragen
|
||||
hat: Testmail schicken, SPF, DKIM und DMARC von `foodplanhero.de` für Resend
|
||||
prüfen.
|
||||
- **Öffentlicher Weg auf der Box:** `/anmelden/mail` hinter Envoy und Authelia
|
||||
einmal ausprobieren (CLAUDE.md, Plattform 4).
|
||||
|
||||
## Was gut ist
|
||||
|
||||
- Nur der Hash des Tokens wird gespeichert. Ein Link gilt einmal: 15 Minuten
|
||||
zum Anmelden, 24 Stunden zum Bestätigen. Ein neuer Link macht ältere ungültig.
|
||||
- Die Adresse im Link kommt aus `instance`, nie aus dem Host-Kopf. Damit kann
|
||||
niemand den Link über einen gefälschten Host auf eine fremde Seite umbiegen.
|
||||
- Die Antwort auf „Link schicken“ ist immer gleich und schnell, weil der Versand
|
||||
im Hintergrund läuft.
|
||||
- Nach dem Öffnen nimmt `history.replaceState` den Token aus der Adresszeile.
|
||||
- `noMailSession` sitzt an jedem Weg, der Zugang schafft oder entzieht. Der
|
||||
Browser-Test prüft vier davon mit echter Mail-Sitzung.
|
||||
- **Der Resend-Schlüssel**
|
||||
- geht nur hinein,
|
||||
- liegt verschlüsselt im Tresor,
|
||||
- wird nie zurückgegeben,
|
||||
- steht nicht in der Seite (Test).
|
||||
- Mails kommen ohne Bilder von außen und ohne Tracking. Alle Werte im HTML sind
|
||||
escaped (Test).
|
||||
@@ -108,6 +108,10 @@ test.describe("receipts", () => {
|
||||
req.on("data", (c) => (raw += c));
|
||||
req.on("end", () => {
|
||||
if (req.headers.authorization !== "Bearer sk-test") return res.writeHead(401).end();
|
||||
// Einkaufsliste einsprechen (26.11.46): feste Abschrift.
|
||||
if (req.url === "/v1/audio/transcriptions") {
|
||||
return res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify({ text: "Wir brauchen noch Hafermilch, zwei Gurken und Spülmittel, bitte." }));
|
||||
}
|
||||
if (raw.includes("supermarket receipt photo")) {
|
||||
return res.writeHead(200, { "content-type": "application/json" }).end(
|
||||
reply({
|
||||
@@ -174,6 +178,26 @@ test.describe("receipts", () => {
|
||||
await page.getByRole("link", { name: /Spaghetti Bolognese/ }).click();
|
||||
await expect(page.locator("section", { hasText: "Kosten" }).last().locator("li", { hasText: "Spaghetti" }).first()).toContainText("3,58 € je kg · vom Bon");
|
||||
});
|
||||
|
||||
test("the list can be dictated: items are split, checked, then added", async ({ page }) => {
|
||||
await page.goto("/einkauf");
|
||||
await page.getByRole("button", { name: "Einkaufsliste einsprechen" }).click();
|
||||
await expect(page.getByText(/Aufnahme läuft/)).toBeVisible();
|
||||
await page.waitForTimeout(1200);
|
||||
await page.getByRole("button", { name: "Aufnahme beenden" }).click();
|
||||
const check = page.getByRole("region", { name: "Erkannt — bitte prüfen" });
|
||||
await expect(check.getByRole("textbox")).toHaveCount(3);
|
||||
await expect(check.getByLabel("Posten 1")).toHaveValue("Hafermilch");
|
||||
await expect(check.getByLabel("Posten 2")).toHaveValue("Zwei Gurken");
|
||||
await check.getByRole("button", { name: "Spülmittel weglassen" }).click();
|
||||
await check.getByLabel("Posten 2").fill("2 Gurken");
|
||||
await check.getByRole("button", { name: "2 Posten hinzufügen" }).click();
|
||||
await expect(check).toHaveCount(0);
|
||||
const other = page.getByRole("region", { name: "Sonstiges" });
|
||||
await expect(other).toContainText("Hafermilch");
|
||||
await expect(other).toContainText("2 Gurken");
|
||||
await expect(page.getByText("Spülmittel")).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
/** Nach links wischen wie am Handy (Chromium hat keine Wischgeste). */
|
||||
|
||||
+252
-7
@@ -153,7 +153,7 @@ test.describe("recipe link", () => {
|
||||
recipeYield: "4 Portionen",
|
||||
totalTime: "PT45M",
|
||||
image: "/bild.jpg",
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Handvoll Glück"],
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "2 EL Eier", "1 Handvoll Glück"],
|
||||
recipeInstructions: [{ "@type": "HowToStep", text: "Zwiebeln anschwitzen." }, { "@type": "HowToStep", text: "Linsen dazu und weich kochen." }],
|
||||
},
|
||||
],
|
||||
@@ -195,16 +195,23 @@ test.describe("recipe link", () => {
|
||||
await expect(page.getByRole("note").filter({ hasText: "Nach Regeln in Abschnitte eingeordnet" })).toBeVisible();
|
||||
await expect(page.getByLabel("Abschnitt von Schritt 1")).toHaveValue("cook");
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
await expect(amounts).toHaveCount(3);
|
||||
await expect(amounts).toHaveCount(4);
|
||||
await expect(amounts.nth(0)).toHaveValue("250");
|
||||
await expect(amounts.nth(1)).toHaveValue("2");
|
||||
await expect(amounts.nth(2)).toHaveValue("");
|
||||
// Sahne im Becher: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
// Becher ist das Gebinde der Sahne (26.11.39): 1 Packung zu 200 ml.
|
||||
await expect(amounts.nth(2)).toHaveValue("1");
|
||||
await expect(page.getByRole("combobox", { name: "Einheit" }).nth(2).locator("option:checked")).toHaveText("Packung (200 ml)");
|
||||
await expect(amounts.nth(3)).toHaveValue("");
|
||||
// Eier in Esslöffeln passen nicht: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.locator("main [role=alert]")).toContainText("fehlt die Menge");
|
||||
await amounts.nth(2).fill("200");
|
||||
await expect(page.getByRole("status").filter({ hasText: "1 Angabe fehlt noch" })).toBeVisible();
|
||||
await expect(amounts.nth(3)).toBeFocused();
|
||||
await expect(page.getByText("Menge fehlt.")).toBeVisible();
|
||||
await amounts.nth(3).fill("2");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Linsensuppe vom Blog");
|
||||
// Gespeichert unter „Ausprobieren“ — und die Seite sagt es (26.11.41).
|
||||
await expect(page.getByRole("note").filter({ hasText: "Steht unter „Ausprobieren“" })).toBeVisible();
|
||||
await expect(page.locator("main img").first()).toHaveAttribute("src", /\/api\/fotos\//);
|
||||
await expect(page.locator(`main a[href="${origin}/rezept"]`)).toBeVisible();
|
||||
});
|
||||
@@ -218,6 +225,8 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
const origin = process.env.IMPORT_TEST_ORIGIN ?? "http://127.0.0.1:3021";
|
||||
const reply = (r: object) => JSON.stringify({ choices: [{ message: { content: "```json\n" + JSON.stringify(r) + "\n```" } }] });
|
||||
|
||||
let pagesSeen = 0;
|
||||
|
||||
test.beforeAll(async () => {
|
||||
const { createServer } = await import("node:http");
|
||||
server = createServer((req, res) => {
|
||||
@@ -268,6 +277,7 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
// Andere Hausform-Anfragen: Fehler — dann ordnen die Regeln ein.
|
||||
if (raw.includes("house style")) return res.writeHead(500).end();
|
||||
const withImage = raw.includes("image_url");
|
||||
if (withImage) pagesSeen = (raw.match(/"type":"image_url"/g) ?? []).length;
|
||||
res.writeHead(200, { "content-type": "application/json" }).end(
|
||||
withImage
|
||||
? reply({ title: "Kartoffelsalat aus dem Kochbuch", portions: 4, minutes: 40, ingredients: ["1 kg Kartoffeln", "2 Zwiebeln", "1 Glas Gurken"], steps: ["Kartoffeln kochen.", "Alles mischen."] })
|
||||
@@ -318,9 +328,19 @@ test.describe("cookbook photo and AI setting", () => {
|
||||
test("a cookbook photo becomes a draft marked as read by the AI", async ({ page }) => {
|
||||
await page.goto("/gerichte/foto");
|
||||
const jpg = await sharp({ create: { width: 1000, height: 1400, channels: 3, background: { r: 245, g: 240, b: 230 } } }).jpeg().toBuffer();
|
||||
await page.locator("input[type=file]").setInputFiles({ name: "seite.jpg", mimeType: "image/jpeg", buffer: jpg });
|
||||
// Mehrere Seiten (26.11.48): jede Auswahl kommt hinten dazu, einzelne lassen sich entfernen.
|
||||
const input = page.locator("input[type=file]");
|
||||
await input.setInputFiles({ name: "seite1.jpg", mimeType: "image/jpeg", buffer: jpg });
|
||||
await expect(page.getByRole("img", { name: "Seite 1" })).toBeVisible();
|
||||
await input.setInputFiles({ name: "seite2.jpg", mimeType: "image/jpeg", buffer: jpg });
|
||||
await expect(page.getByRole("img", { name: "Seite 2" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Seite 1 entfernen" }).click();
|
||||
await expect(page.getByRole("img", { name: /^Seite/ })).toHaveCount(1);
|
||||
await input.setInputFiles({ name: "seite3.jpg", mimeType: "image/jpeg", buffer: jpg });
|
||||
await expect(page.getByRole("list", { name: "2 Seiten" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Rezept lesen" }).click();
|
||||
await expect(page.locator("#title")).toHaveValue("Kartoffelsalat aus dem Kochbuch");
|
||||
expect(pagesSeen).toBe(2);
|
||||
await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen");
|
||||
await expect(page.getByRole("note").filter({ hasText: "Von der AI in die foodplanhero-Form gebracht" })).toBeVisible();
|
||||
await expect(page.getByLabel("Schritt 1", { exact: true })).toHaveValue("Kartoffeln waschen.");
|
||||
@@ -403,3 +423,228 @@ test("a group term shows the group with its kinds; an own ingredient and a remem
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
}
|
||||
});
|
||||
|
||||
// Löffel und Gebinde (26.11.39, Kai: „Teelöffel, Esslöffel … eine Dose als Einheit“).
|
||||
test("spoons and cans: the ingredient preselects its measure, the dish shows spoons and grams", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Tomatensoße vom Blech");
|
||||
const search = page.getByRole("combobox", { name: "Zutat suchen" });
|
||||
const unit = page.getByRole("combobox", { name: "Einheit" });
|
||||
await search.first().fill("Olivenöl");
|
||||
await page.getByRole("option", { name: "Olivenöl", exact: true }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("2");
|
||||
|
||||
await page.getByRole("button", { name: "Zutaten" }).click();
|
||||
await search.nth(1).fill("gehackte Tomaten");
|
||||
await page.getByRole("option", { name: /Gehackte Tomaten/ }).first().click();
|
||||
// Die Dose wird angeboten, mit Größe, aber nicht vorgewählt.
|
||||
await expect(unit.nth(1)).toHaveValue("g");
|
||||
await unit.nth(1).selectOption("can");
|
||||
await expect(unit.nth(1).locator("option:checked")).toHaveText("Dose (400 g)");
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
// Unsere Dose hat 500 g.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Wie viel ist 1 Dose? (in g)").fill("500");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 500 g")).toBeVisible();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).nth(1).fill("1");
|
||||
await page.getByLabel("Schritt 1", { exact: true }).fill("Tomaten mit Öl aufs Blech.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Tomatensoße vom Blech");
|
||||
|
||||
// Auf vier Portionen: „2 EL (30 ml) Olivenöl“, „500 g (1 Dose) Gehackte Tomaten“.
|
||||
const list = page.locator("main ul").first();
|
||||
const portions = page.locator("output");
|
||||
for (let i = 0; i < 8 && !(await portions.innerText()).startsWith("4 "); i++) {
|
||||
const n = Number((await portions.innerText()).match(/\d+/)![0]);
|
||||
await page.getByRole("button", { name: n > 4 ? "Eine Portion weniger" : "Eine Portion mehr" }).click();
|
||||
}
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/2 EL\s*\(30 ml\) Olivenöl/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/500 g\s*\(1 Dose\) Gehackte Tomaten/);
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/1 EL\s*\(15 ml\)/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/250 g\s*\(½ Dose\)/);
|
||||
|
||||
// Bearbeiten zeigt die Mengen im eingegebenen Maß.
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).first()).toHaveValue("2");
|
||||
await expect(unit.nth(1)).toHaveValue("can");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).nth(1)).toHaveValue("1");
|
||||
|
||||
// Aufräumen: Größe zurück, Gericht aus dem Pool — damit Plan und Einkauf gleich bleiben.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Wie viel ist 1 Dose? (in g)").fill("400");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: /Tomatensoße vom Blech/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
// Kai: „Neue Gerichte werden nicht gespeichert“ — sie standen unter „Ausprobieren“, ohne dass
|
||||
// die Seite es sagte (26.11.41). Jetzt: Hinweis, Weg dorthin, und mit einem Tipp in den Pool.
|
||||
test("portions are remembered and scale the amounts; a pack and cloves for any ingredient (26.11.49)", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Hackbraten");
|
||||
await page.fill("#portions", "6");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Gemischtes Hack");
|
||||
await page.getByRole("option", { name: "Gemischtes Hackfleisch", exact: true }).click();
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
const units = page.getByRole("combobox", { name: "Einheit" });
|
||||
await amounts.nth(0).fill("1");
|
||||
await units.nth(0).selectOption("pack");
|
||||
// Hackfleisch hat keine Packungsgröße: Speichern fragt danach, statt still zu rechnen.
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByText("Größe fehlt – bitte eintragen.")).toBeVisible();
|
||||
await expect(page.getByLabel("Wie viel ist 1 Packung? (in g)")).toBeFocused();
|
||||
await page.getByLabel("Wie viel ist 1 Packung? (in g)").fill("500");
|
||||
await page.getByRole("button", { name: "Zutaten" }).click();
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).nth(1).fill("Knoblauchz");
|
||||
await page.getByRole("option", { name: "Knoblauchzehe", exact: true }).click();
|
||||
await amounts.nth(1).fill("3");
|
||||
await units.nth(1).selectOption("clove");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Hackbraten");
|
||||
|
||||
// Bearbeiten zeigt das Rezept wieder für 6 Portionen, im eingegebenen Maß.
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(page.locator("#portions")).toHaveValue("6");
|
||||
await expect(amounts.nth(0)).toHaveValue("1");
|
||||
await expect(units.nth(0).locator("option:checked")).toHaveText("Packung (500 g)");
|
||||
await expect(amounts.nth(1)).toHaveValue("3");
|
||||
await expect(units.nth(1)).toHaveValue("clove");
|
||||
// Portionen umstellen rechnet mit.
|
||||
await page.fill("#portions", "3");
|
||||
await expect(amounts.nth(0)).toHaveValue("0,5");
|
||||
await expect(amounts.nth(1)).toHaveValue("1,5");
|
||||
await page.fill("#portions", "6");
|
||||
await expect(amounts.nth(0)).toHaveValue("1");
|
||||
await page.fill("#portions", "3");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Hackbraten");
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(page.locator("#portions")).toHaveValue("3");
|
||||
await expect(amounts.nth(0)).toHaveValue("0,5");
|
||||
// Wieder aus dem Pool, damit der Plan später nicht anders vorschlägt.
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: /Hackbraten/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
test("millilitres for a piece ingredient: stock cubes in ml with the size per piece (26.11.50)", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Brühnudeln");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Brühwürf");
|
||||
await page.getByRole("option", { name: "Brühwürfel", exact: true }).click();
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
const units = page.getByRole("combobox", { name: "Einheit" });
|
||||
await amounts.nth(0).fill("750");
|
||||
await units.nth(0).selectOption("ml");
|
||||
await page.getByLabel("Wie viel ml ist 1 Stück?").fill("500");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Brühnudeln");
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(amounts.nth(0)).toHaveValue("750");
|
||||
await expect(units.nth(0)).toHaveValue("ml");
|
||||
await expect(page.getByText("1 Stück = 500 ml")).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: /Brühnudeln/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
test("what is missing is marked at the field, counted below and shown on tap (26.11.51)", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
const units = page.getByRole("combobox", { name: "Einheit" });
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Zwieb");
|
||||
await page.getByRole("option", { name: "Zwiebeln", exact: true }).click();
|
||||
await page.getByRole("button", { name: "Zutaten" }).click();
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).nth(1).fill("Eier");
|
||||
await page.getByRole("option", { name: "Eier", exact: true }).click();
|
||||
await amounts.nth(1).fill("100");
|
||||
await units.nth(1).selectOption("ml");
|
||||
// Ohne Titel, ohne Menge bei den Zwiebeln, ohne Größe für Eier in ml.
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
const left = page.getByRole("status").filter({ hasText: "fehlen noch" });
|
||||
await expect(left).toHaveText(/3 Angaben fehlen noch/);
|
||||
const title = page.locator("#title");
|
||||
await expect(title).toBeFocused();
|
||||
await expect(title).toHaveAttribute("aria-invalid", "true");
|
||||
expect(await title.evaluate((e) => getComputedStyle(e).borderTopWidth)).toBe("2px");
|
||||
await expect(page.getByText("Titel fehlt.")).toBeVisible();
|
||||
// „Zeigen“ führt zum nächsten.
|
||||
await left.getByRole("button", { name: "Zeigen" }).click();
|
||||
await expect(amounts.nth(0)).toBeFocused();
|
||||
await amounts.nth(0).fill("2");
|
||||
await expect(left).toHaveText(/2 Angaben fehlen noch/);
|
||||
await title.fill("Zwiebelkuchen");
|
||||
await page.getByLabel("Wie viel ml ist 1 Stück?").fill("50");
|
||||
await expect(left).toHaveCount(0);
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Zwiebelkuchen");
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
test("a dish to try says so, links to its tab and moves to the pool with one tap", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Probe-Auflauf");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Zwieb");
|
||||
await page.getByRole("option", { name: "Zwiebeln", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("2");
|
||||
await page.getByLabel("Erst mal ausprobieren").check();
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Probe-Auflauf");
|
||||
const note = page.getByRole("note").filter({ hasText: "Steht unter „Ausprobieren“" });
|
||||
await expect(note).toBeVisible();
|
||||
await expect(page.locator("main").getByRole("link", { name: "Gerichte", exact: true })).toHaveAttribute("href", "/gerichte?ansicht=ausprobieren");
|
||||
await note.getByRole("button", { name: "In den Pool" }).click();
|
||||
await expect(note).toHaveCount(0);
|
||||
// Fotos auch aus der Mediathek, mehrere auf einmal (26.11.43): kein capture, multiple.
|
||||
const picker = page.locator("input[type=file]");
|
||||
expect(await picker.getAttribute("capture")).toBeNull();
|
||||
expect(await picker.getAttribute("multiple")).not.toBeNull();
|
||||
const shots = await Promise.all(
|
||||
[[200, 80, 60], [60, 140, 90]].map(async ([r, g, b], i) => ({
|
||||
name: `mediathek-${i}.png`,
|
||||
mimeType: "image/png",
|
||||
buffer: await sharp({ create: { width: 800, height: 600, channels: 3, background: { r: r!, g: g!, b: b! } } }).png().toBuffer(),
|
||||
})),
|
||||
);
|
||||
await picker.setInputFiles(shots);
|
||||
await expect(page.getByRole("heading", { name: "Fotos · 2 von 5" })).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await expect(page.getByRole("link", { name: /Probe-Auflauf/ })).toBeVisible();
|
||||
// Aufräumen, damit der Plan danach denselben Bestand vorschlägt.
|
||||
await page.getByRole("link", { name: /Probe-Auflauf/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
|
||||
|
||||
// Kai: „Die Karten sollen immer dieselbe Größe haben“ (26.11.44) — auch bei langen Titeln.
|
||||
test("dish cards in the pool all have the same size, long titles end with an ellipsis", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Gyros-Nudelauflauf in Metaxasoße mit extra viel Käse vom Blech");
|
||||
await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Zwieb");
|
||||
await page.getByRole("option", { name: "Zwiebeln", exact: true }).click();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("1");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toContainText("Gyros-Nudelauflauf");
|
||||
await page.goto("/gerichte");
|
||||
const sizes = await page.locator("main ul li a").evaluateAll((els) => els.map((e) => Math.round(e.getBoundingClientRect().height)));
|
||||
expect(sizes.length).toBeGreaterThan(2);
|
||||
expect(new Set(sizes).size).toBe(1);
|
||||
// Der volle Titel bleibt erreichbar.
|
||||
await expect(page.getByRole("link", { name: /Gyros-Nudelauflauf/ })).toHaveAttribute("title", /extra viel Käse vom Blech/);
|
||||
// Aufräumen, damit der Plan danach denselben Bestand vorschlägt.
|
||||
await page.getByRole("link", { name: /Gyros-Nudelauflauf/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
+3
-4
@@ -72,10 +72,9 @@ test("a child wishes, makes a favourite, and has no veto", async () => {
|
||||
|
||||
test("a child makes a wish their own dish, sure to be in the plan", async () => {
|
||||
await tablet.goto("/wuenschen");
|
||||
await expect(tablet.getByText("Mach einen Wunsch zu deinem Gericht")).toBeVisible();
|
||||
await tablet.getByRole("button", { name: "Optionen für Spaghetti Bolognese" }).click();
|
||||
await tablet.getByRole("dialog").getByRole("button", { name: "Als mein Gericht" }).click();
|
||||
await expect(tablet.getByRole("dialog")).toBeHidden();
|
||||
await expect(tablet.getByText("Tipp aufs Herz")).toBeVisible();
|
||||
await tablet.getByRole("button", { name: "Spaghetti Bolognese als mein Gericht" }).click();
|
||||
await expect(tablet.getByRole("button", { name: "Spaghetti Bolognese nicht mehr mein Gericht" })).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(tablet.getByText("Dein Gericht: Spaghetti Bolognese — kommt sicher in den Plan.")).toBeVisible();
|
||||
await expect(tablet.getByRole("button", { name: /^Wunsch zurücknehmen: Spaghetti Bolognese/ })).toContainText("Mein Gericht");
|
||||
});
|
||||
|
||||
+34
-12
@@ -73,29 +73,51 @@ test("scrolling never moves the bar, even while the address bar comes and goes",
|
||||
}
|
||||
});
|
||||
|
||||
test("after typing, a stale gap is bridged briefly and dropped at the first touch", async ({ page }) => {
|
||||
const shiftOf = (page: Page) => page.getByRole("navigation", { name: "Navigation" }).evaluate((el) => (el as HTMLElement).style.transform);
|
||||
const kbShift = (page: Page) => page.evaluate(() => document.documentElement.style.getPropertyValue("--kb-shift"));
|
||||
|
||||
// 26.11.41 (Kai, Bild: Leiste und „Speichern“ mitten im Bild): iOS rechnet nach der
|
||||
// Tastatur in der Web-App manchmal lange zu kurz — auch nach Berührung und Scrollen.
|
||||
test("after typing, a stuck keyboard gap stays bridged through touch and scroll until iOS recovers", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const field = page.locator("#kid-name");
|
||||
await field.focus();
|
||||
await expect(page.getByRole("navigation", { name: "Navigation" })).toBeHidden(); // beim Tippen weg
|
||||
// iOS lässt das Layout nach dem Schließen der Tastatur 300 px zu kurz stehen.
|
||||
await moveViewport(page, 300);
|
||||
await moveViewport(page, 300); // iOS lässt das Layout 300 px zu kurz stehen
|
||||
await field.blur();
|
||||
const nav = page.getByRole("navigation", { name: "Navigation" });
|
||||
await expect(nav).toBeVisible();
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
|
||||
await expect.poll(() => shiftOf(page)).toBe("translateY(300px)");
|
||||
await expect.poll(() => kbShift(page)).toBe("300px");
|
||||
// Berühren, scrollen, über die erste Sekunde hinaus: bleibt unten.
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("touchstart")));
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
|
||||
await page.evaluate(() => window.dispatchEvent(new Event("touchend")));
|
||||
await page.mouse.wheel(0, 400);
|
||||
await page.waitForTimeout(1300);
|
||||
await moveViewport(page, 300);
|
||||
await expect.poll(() => shiftOf(page)).toBe("translateY(300px)");
|
||||
// iOS rechnet wieder richtig: Korrektur weg, Leiste unten.
|
||||
await moveViewport(page, 0);
|
||||
await expect.poll(() => shiftOf(page)).toBe("");
|
||||
await expect.poll(() => kbShift(page)).toBe("");
|
||||
await navAtBottom(page);
|
||||
// Danach ist nichts mehr scharf: eine neue Lücke ohne Tippen bleibt unberührt.
|
||||
await moveViewport(page, 300);
|
||||
await page.waitForTimeout(100);
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
});
|
||||
|
||||
test("the bridge ends by itself after a second, and never starts without typing", async ({ page }) => {
|
||||
test("never without typing; after the first second only a keyboard-sized gap counts", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const nav = page.getByRole("navigation", { name: "Navigation" });
|
||||
await moveViewport(page, 300); // ohne Tastatur: nichts tun
|
||||
await page.waitForTimeout(100);
|
||||
expect(await nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("");
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
await moveViewport(page, 0);
|
||||
await page.locator("#kid-name").focus();
|
||||
await page.locator("#kid-name").blur();
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform)).toBe("translateY(300px)");
|
||||
await expect.poll(() => nav.evaluate((el) => (el as HTMLElement).style.transform), { timeout: 3000 }).toBe("");
|
||||
await page.waitForTimeout(1300);
|
||||
// Gummiband oder Rundung (unter STUCK_MIN): Lunch fasst die Leiste nicht an.
|
||||
await moveViewport(page, 80);
|
||||
await page.waitForTimeout(100);
|
||||
expect(await shiftOf(page)).toBe("");
|
||||
await moveViewport(page, 0);
|
||||
await navAtBottom(page);
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { readdir, readFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Browser, type Page } from "@playwright/test";
|
||||
|
||||
// Anmelden per Link aus der Mail (26.11.40, Kai: Resend). Der Server schreibt jede
|
||||
// Mail nach $LUNCH_DATA/mails (MAIL_TEST_DIR) statt sie zu senden.
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
const DIR = path.join(process.env.LUNCH_DATA ?? "", "mails");
|
||||
const KAI = "kai@test.example";
|
||||
|
||||
async function mails(to: string): Promise<{ to: string; text: string; subject: string }[]> {
|
||||
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"))));
|
||||
return all.filter((m) => m.to === to);
|
||||
}
|
||||
const linkIn = (text: string) => text.match(/https?:\/\/\S+\/anmelden\/mail#\S+/)![0];
|
||||
|
||||
async function fresh(browser: Browser): Promise<Page> {
|
||||
const context = await browser.newContext({ ...test.info().project.use, storageState: undefined });
|
||||
return context.newPage();
|
||||
}
|
||||
|
||||
test("the admin sets up sending with Resend and sends a test mail", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByRole("link", { name: /Noch nicht eingerichtet/ })).toBeVisible();
|
||||
await page.goto("/mehr/mail");
|
||||
await expect(page.getByLabel("Server")).toHaveValue("smtp.resend.com");
|
||||
await expect(page.getByLabel("Port", { exact: true })).toHaveValue("465");
|
||||
await expect(page.getByLabel("Benutzer")).toHaveValue("resend");
|
||||
await expect(page.getByLabel("Absender", { exact: true })).toHaveValue("hallo@foodplanhero.de");
|
||||
await page.getByLabel("API-Schlüssel").fill("re_test_not_a_real_key");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByText("Ein Schlüssel ist gespeichert.")).toBeVisible();
|
||||
// Der Schlüssel kommt nie zurück in die Seite.
|
||||
expect(await page.content()).not.toContain("re_test_not_a_real_key");
|
||||
await page.getByLabel("Testmail an").fill(KAI);
|
||||
await page.getByRole("button", { name: "Testmail schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText("Die Testmail ist unterwegs.");
|
||||
expect((await mails(KAI)).at(-1)?.subject).toBe("Testmail von foodplanhero");
|
||||
});
|
||||
|
||||
test("a person confirms the address through the first link", async ({ page }) => {
|
||||
await page.goto("/mehr");
|
||||
const section = page.locator("#mail");
|
||||
await section.getByLabel("Deine Mailadresse").fill(KAI);
|
||||
await section.getByRole("button", { name: "Bestätigung schicken" }).click();
|
||||
await expect(section.getByRole("status")).toContainText(`Wartet auf Bestätigung: ${KAI}`);
|
||||
const verify = (await mails(KAI)).at(-1)!;
|
||||
expect(verify.subject).toBe("Bitte bestätige deine Adresse");
|
||||
await page.goto(linkIn(verify.text));
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Adresse bestätigen");
|
||||
// Der Token verschwindet aus der Adresszeile.
|
||||
expect(page.url()).not.toContain("#");
|
||||
await page.getByRole("button", { name: "Bestätigen" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Deine Adresse ist bestätigt.");
|
||||
await page.goto("/mehr");
|
||||
await expect(page.locator("#mail")).toContainText(`Bestätigt: ${KAI}`);
|
||||
});
|
||||
|
||||
test("signed out: a link by mail signs in once; unknown addresses get the same answer and no mail", async ({ browser }) => {
|
||||
const page = await fresh(browser);
|
||||
const sent = "Wenn die Adresse bei uns bestätigt ist, kommt gleich eine Mail.";
|
||||
await page.goto("/anmelden");
|
||||
await page.getByRole("button", { name: "Lieber einen Link per Mail?" }).click();
|
||||
await page.getByLabel("Deine Mailadresse").fill("niemand@test.example");
|
||||
await page.getByRole("button", { name: "Link schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText(sent);
|
||||
expect(await mails("niemand@test.example")).toHaveLength(0);
|
||||
|
||||
const before = (await mails(KAI)).length;
|
||||
await page.goto("/anmelden");
|
||||
await page.getByRole("button", { name: "Lieber einen Link per Mail?" }).click();
|
||||
await page.getByLabel("Deine Mailadresse").fill(KAI.toUpperCase());
|
||||
await page.getByRole("button", { name: "Link schicken" }).click();
|
||||
await expect(page.getByRole("status")).toContainText(sent);
|
||||
await expect.poll(async () => (await mails(KAI)).length).toBe(before + 1);
|
||||
const link = linkIn((await mails(KAI)).at(-1)!.text);
|
||||
|
||||
await page.goto(link);
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Bei foodplanhero anmelden");
|
||||
await page.getByRole("button", { name: "Anmelden" }).click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
|
||||
// Per Mail angemeldet: nur anmelden — kein Gerätelink, keine Einladung, keine Adresse ändern.
|
||||
await page.goto("/mehr");
|
||||
await expect(page.getByText("Du bist per Mail-Link angemeldet.").first()).toBeVisible();
|
||||
const status = await page.evaluate(async () =>
|
||||
Promise.all(
|
||||
[
|
||||
["/api/household/invitations", "POST", { kind: "device" }],
|
||||
["/api/household/invitations", "POST", { kind: "person", name: "Gast" }],
|
||||
["/api/me/email", "PUT", { email: "neu@test.example" }],
|
||||
["/api/household/kid-devices", "POST", { label: "Tablet", kind: "kids" }],
|
||||
].map(async ([url, method, body]) => {
|
||||
const res = await fetch(url as string, { method: method as string, headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||
return `${res.status} ${(await res.json()).error}`;
|
||||
}),
|
||||
),
|
||||
);
|
||||
expect(status).toEqual(["403 mailSession", "403 mailSession", "403 mailSession", "403 mailSession"]);
|
||||
|
||||
// Derselbe Link ein zweites Mal: verbraucht.
|
||||
const again = await fresh(browser);
|
||||
await again.goto(link);
|
||||
await again.getByRole("button", { name: "Anmelden" }).click();
|
||||
await expect(again.getByRole("heading", { level: 1 })).toHaveText("Dieser Link gilt nicht mehr");
|
||||
});
|
||||
+2
-2
@@ -16,7 +16,7 @@ test("the suggestion starts with the wishes and says why", async ({ page }) => {
|
||||
await expect(items(page)).toHaveCount(4);
|
||||
await expect(items(page).first()).toContainText("Spaghetti Bolognese");
|
||||
await expect(items(page).first()).toContainText("Gericht von Ben (sicher)"); // Bens Gericht (kinder.spec)
|
||||
await expect(items(page).first().getByRole("combobox")).toHaveValue(/.+/); // Kai kocht („Ich koche das“)
|
||||
await expect(items(page).first().getByRole("combobox", { name: /^Wer kocht/ })).toHaveValue(/.+/); // Kai kocht („Ich koche das“)
|
||||
await expect(titles(page)).not.toContainText(["Flammkuchen"]);
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ test("a locked slot survives a new suggestion; portions and cook change", async
|
||||
|
||||
const lentils = items(page).filter({ hasText: "Linseneintopf" });
|
||||
await lentils.getByRole("combobox", { name: "Wer kocht Linseneintopf?" }).selectOption({ label: "Koch: Ben" });
|
||||
await expect(lentils.getByRole("combobox")).toHaveValue(/.+/);
|
||||
await expect(lentils.getByRole("combobox", { name: /^Wer kocht/ })).toHaveValue(/.+/);
|
||||
});
|
||||
|
||||
test("a dish can be replaced, moved by keyboard and removed", async ({ page }) => {
|
||||
|
||||
+2
-1
@@ -65,7 +65,8 @@ test("buttons pinned to the bottom sit on the keyboard while typing, above the b
|
||||
const height = page.viewportSize()!.height;
|
||||
const nav = page.getByRole("navigation", { name: "Navigation" });
|
||||
const bottomOf = async () => {
|
||||
const box = (await save.locator("xpath=..").boundingBox())!;
|
||||
// Die feste Leiste: seit 26.11.51 mit Zeile „… fehlen noch“ über den Knöpfen, deshalb zwei Ebenen.
|
||||
const box = (await save.locator("xpath=../..").boundingBox())!;
|
||||
return Math.round(box.y + box.height);
|
||||
};
|
||||
await page.locator("#title").focus();
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import { expect, test } from "@playwright/test";
|
||||
|
||||
// 26.11.45 (Kai, 8.11.2026): Tag je Gericht von Hand, Runde ändern, Kalender-Abo,
|
||||
// Runde beenden und löschen. Läuft nach „mail“ — die Runde aus plan/kochen hat
|
||||
// schon Gekochtes, also nur „Beenden“.
|
||||
test.describe.configure({ mode: "serial" });
|
||||
|
||||
const cards = (page: import("@playwright/test").Page) => page.locator("main ol > li");
|
||||
|
||||
test("a dish gets a day by hand and shows it on the plan and today", async ({ page }) => {
|
||||
await page.goto("/plan");
|
||||
const card = cards(page).filter({ has: page.getByRole("combobox", { name: /^Tag für/ }) }).first();
|
||||
const title = (await card.locator("h2").textContent())!;
|
||||
const day = card.getByRole("combobox", { name: `Tag für ${title}` });
|
||||
await expect(day).toHaveValue("");
|
||||
const label = (await day.locator("option").nth(2).textContent())!;
|
||||
await day.selectOption({ label });
|
||||
await expect(day).not.toHaveValue("");
|
||||
await expect(card.locator("p", { hasText: label })).toBeVisible();
|
||||
await page.goto("/");
|
||||
await expect(page.locator("main li").filter({ hasText: title })).toContainText(label);
|
||||
});
|
||||
|
||||
test("the round's settings can change", async ({ page }) => {
|
||||
await page.goto("/plan");
|
||||
const before = await page.locator("header p.text-muted-foreground").textContent();
|
||||
await page.getByRole("button", { name: "Einstellungen ändern" }).click();
|
||||
await page.getByRole("button", { name: "Warme Mahlzeiten: mehr" }).click();
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("button", { name: "Einstellungen ändern" })).toBeVisible();
|
||||
await expect(page.locator("header p.text-muted-foreground")).not.toHaveText(before!);
|
||||
});
|
||||
|
||||
test("the household calendar link serves the plan, and a new link kills the old", async ({ page, playwright }) => {
|
||||
await page.goto("/mehr#kalender");
|
||||
await page.getByLabel("Essenszeit").fill("19:00");
|
||||
await page.getByRole("button", { name: "Essenszeit speichern" }).click();
|
||||
await expect(page.getByRole("button", { name: "Gespeichert" })).toBeVisible();
|
||||
await page.getByRole("button", { name: "Kalender-Abo starten" }).click();
|
||||
const first = (await page.getByTestId("calendar-url").textContent())!;
|
||||
expect(first).toMatch(/\/kalender\/[A-Za-z0-9_-]{43}\.ics$/);
|
||||
await expect(page.getByRole("link", { name: "Im Kalender öffnen" })).toHaveAttribute("href", /^webcal:\/\//);
|
||||
|
||||
// Ohne Sitzung: Der Link allein reicht.
|
||||
const anon = await playwright.request.newContext();
|
||||
const res = await anon.get(first);
|
||||
expect(res.status()).toBe(200);
|
||||
expect(res.headers()["content-type"]).toContain("text/calendar");
|
||||
const ics = await res.text();
|
||||
expect(ics).toContain("BEGIN:VEVENT");
|
||||
expect(ics).toMatch(/DTSTART;TZID=Europe\/Berlin:\d{8}T190000/);
|
||||
|
||||
await page.getByRole("button", { name: "Neuen Link erzeugen" }).click();
|
||||
await expect(page.getByTestId("calendar-url")).not.toHaveText(first);
|
||||
const second = (await page.getByTestId("calendar-url").textContent())!;
|
||||
expect((await anon.get(first)).status()).toBe(404);
|
||||
expect((await anon.get(second)).status()).toBe(200);
|
||||
await anon.dispose();
|
||||
});
|
||||
|
||||
test("a round with cooked dishes can only end; then the next one opens and an empty one can go", async ({ page }) => {
|
||||
await page.goto("/plan");
|
||||
await expect(page.getByRole("button", { name: "Runde löschen" })).toHaveCount(0);
|
||||
const end = page.getByRole("button", { name: "Runde beenden" });
|
||||
await end.click();
|
||||
await page.getByRole("button", { name: /Wirklich beenden/ }).click();
|
||||
await expect(page.getByRole("link", { name: "Runde eröffnen" })).toBeVisible();
|
||||
|
||||
await page.getByRole("link", { name: "Runde eröffnen" }).click();
|
||||
await page.getByRole("button", { name: "Runde eröffnen" }).click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
await page.goto("/plan");
|
||||
await page.getByRole("button", { name: "Runde löschen" }).click();
|
||||
await page.getByRole("button", { name: /Wirklich löschen/ }).click();
|
||||
await expect(page.getByRole("link", { name: "Runde eröffnen" })).toBeVisible();
|
||||
|
||||
// Für den Rundgang danach wieder eine Runde.
|
||||
await page.getByRole("link", { name: "Runde eröffnen" }).click();
|
||||
await page.getByRole("button", { name: "Runde eröffnen" }).click();
|
||||
await expect(page).toHaveURL(/\/$/);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -19,6 +19,8 @@ const SIGNED_IN = [
|
||||
{ path: "/gerichte/foto", heading: "Kochbuch fotografieren" },
|
||||
{ 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" },
|
||||
@@ -27,6 +29,8 @@ const SIGNED_IN = [
|
||||
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" },
|
||||
];
|
||||
@@ -160,3 +164,22 @@ test("signed out: the sign-in page is centred and its intro has no orphan line",
|
||||
if (widths.length > 1) expect(widths.at(-1)!).toBeGreaterThan(widths[0]! / 4);
|
||||
await context.close();
|
||||
});
|
||||
|
||||
// Am Desktop dieselbe Ansicht wie am Handy (Kai, 9.11.2026): eine Spalte, zwei Karten
|
||||
// je Reihe, „Gericht hinzufügen“ an der Spalte statt am Bildschirmrand.
|
||||
test("the desktop shows the phone column", async ({ page }) => {
|
||||
test.skip(test.info().project.name !== "desktop", "nur am Desktop");
|
||||
for (const path of ["/gerichte", "/wuenschen", "/plan", "/mehr"]) {
|
||||
await page.goto(path);
|
||||
const width = (await page.locator("main").boundingBox())!.width;
|
||||
expect(width, path).toBeLessThanOrEqual(448);
|
||||
}
|
||||
await page.goto("/gerichte");
|
||||
const main = (await page.locator("main").boundingBox())!;
|
||||
const cards = page.locator("main ul > li");
|
||||
const tops = await cards.evaluateAll((els) => els.slice(0, 3).map((e) => Math.round(e.getBoundingClientRect().top)));
|
||||
expect(tops[0]).toBe(tops[1]);
|
||||
expect(tops[2]).toBeGreaterThan(tops[0]!);
|
||||
const add = (await page.getByRole("link", { name: "Gericht hinzufügen" }).boundingBox())!;
|
||||
expect(add.x + add.width).toBeLessThanOrEqual(main.x + main.width + 1);
|
||||
});
|
||||
@@ -28,6 +28,30 @@ test("tokens, veto and the joker share one line, even on the iPhone", async ({ p
|
||||
await expect(page.getByText("1 Veto frei")).toBeVisible();
|
||||
});
|
||||
|
||||
test("the heart makes a dish my dish in one tap, and takes it back (26.11.47)", async ({ page }) => {
|
||||
await page.goto("/wuenschen");
|
||||
await expect(page.getByText("Tipp aufs Herz")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Linseneintopf als mein Gericht" }).click();
|
||||
const heart = page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" });
|
||||
await expect(heart).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByRole("button", { name: /^Wunsch zurücknehmen: Linseneintopf/ })).toHaveAttribute("aria-pressed", "true");
|
||||
await expect(page.getByText("1 Jeton frei")).toBeVisible();
|
||||
await expect(page.getByText("Dein Gericht: Linseneintopf — kommt sicher in den Plan.")).toBeVisible();
|
||||
// Zurück: das Herz ist leer, der Wunsch bleibt.
|
||||
await heart.click();
|
||||
await expect(page.getByRole("button", { name: "Linseneintopf als mein Gericht" })).toHaveAttribute("aria-pressed", "false");
|
||||
await expect(page.getByText("1 Jeton frei")).toBeVisible();
|
||||
// Der Weg über das Blatt geht weiter.
|
||||
await page.getByRole("button", { name: "Optionen für Linseneintopf" }).click();
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Als mein Gericht" }).click();
|
||||
await expect(page.getByRole("dialog")).toBeHidden();
|
||||
await expect(page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" })).toHaveAttribute("aria-pressed", "true");
|
||||
await page.getByRole("button", { name: "Linseneintopf nicht mehr mein Gericht" }).click();
|
||||
await expect(page.getByRole("button", { name: "Linseneintopf als mein Gericht" })).toBeVisible();
|
||||
await page.getByRole("button", { name: /^Wunsch zurücknehmen: Linseneintopf/ }).click();
|
||||
await expect(page.getByText("2 Jetons frei")).toBeVisible();
|
||||
});
|
||||
|
||||
test("each tap spends a token, and the server says when they are gone", async ({ page }) => {
|
||||
await page.goto("/");
|
||||
await page.getByRole("link", { name: "Wünschen" }).click();
|
||||
|
||||
Loaded 100 of 175 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user