Compare commits

...
1 Commits
Author SHA1 Message Date
kai 9dcd02dffe Dishes: pool, classics, portions, own dishes, photos, recipe link (26.11.6) (#7)
release / which version (push) Successful in 2s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 57s
release / tag and release (push) Successful in 3s
2026-11-06 21:42:10 +00:00
52 changed files with 3038 additions and 23 deletions

No files matched your search

+2 -1
View File
@@ -158,7 +158,7 @@ jobs:
mkdir -p "$RUNNER_TEMP/lunchdaten"
echo "LUNCH_DATA=$RUNNER_TEMP/lunchdaten" >> "$GITHUB_ENV"
# HOSTNAME: Next bindet sich daran; im Container ist es die Kennung des Containers.
(cd .next/standalone && HOSTNAME=0.0.0.0 PORT=3020 BACKUP_DISABLED=1 APP_DATA_DIR="$RUNNER_TEMP/lunchdaten" \
(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" \
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
@@ -203,6 +203,7 @@ jobs:
run: npx playwright test
env:
LUNCH_URL: http://localhost:3020
IMPORT_TEST_ORIGIN: http://127.0.0.1:3021
- name: server log on failure
if: failure()
+22 -1
View File
@@ -7,7 +7,7 @@
> **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase,
> kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002).
> Verteilung über den Markt, Repo öffentlich (E-0005).
> **Status:** 26.11.5 (Seed) — Arbeitspakete 1 und 2 fertig: Anmeldung mit Passkeys,
> **Status:** 26.11.6 (Gerichte 4a) — Arbeitspakete 1 und 2 fertig: Anmeldung mit Passkeys,
> Datenmodell (24 Tabellen, E-0007/E-0008), Test mit zwei Haushalten, Sicherung nach
> `/app/data`. Als Nächstes Arbeitspaket 3, Seed (`docs/PROJEKTSTART.md`).
> **Letzte Aktualisierung:** 6. November 2026
@@ -181,6 +181,27 @@ Migration ein — Zutaten mit fester Kennung aus dem Schlüssel, nie gelöscht;
Vorlagen ersetzt. `tests/seed.test.ts` prüft die Dateien. Ein Haushalt
übernimmt Kopien (`lib/starter.ts`, `lib/stores.ts`).
## Gerichte (Arbeitspaket 4)
- Seiten unter `app/(app)/gerichte/`: Pool (Kacheln, „Ausprobieren“), Hinzufügen,
Vorlagen übernehmen, Ansicht mit Portionen, Anlegen/Bearbeiten.
- Daten in `lib/dishes.ts`: Mengen kommen für das ganze Rezept und werden **pro
Portion in Basiseinheiten** gespeichert (`lib/units.ts`, `toBase`). Anzeige immer
über `formatQuantity`.
- Schreibende Routen über `guardWrite(request)` (`lib/auth/guard.ts`: Sitzung,
Ursprung, Rolle Admin/Mitglied). Entfernen archiviert, Rückgängig holt zurück.
- Fotos: `lib/photos.ts` (sharp, 1600 px, WebP, ohne Metadaten) nach
`/app/data/fotos/<haushalt>/`, ausgeliefert nur über `/api/fotos/<gericht>`.
- Rezept-Link (4b): `POST /api/dishes/import` holt die Seite über
`lib/fetch-safe.ts` (nur öffentliche Adressen, jede Weiterleitung neu geprüft,
10 s, 3 MB) und liest schema.org/Recipe aus JSON-LD (`lib/recipe-import.ts`,
ohne KI). Gespeichert wird nichts: Der Entwurf landet im Formular, eine Menge,
die nicht zur Zutat passt, bleibt leer, nicht zugeordnete Zeilen stehen als
Hinweis darüber. Das Bild der Seite wird erst beim Speichern geholt und wie ein
eigenes Foto verkleinert. `IMPORT_TEST_ORIGIN` erlaubt genau eine lokale Quelle
für den Browser-Test — nie im Chart setzen.
- 4c (KI-Einstellung, Kochbuchfoto) folgt.
## Lokal entwickeln
```bash
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: 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.5
version: 26.11.6
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.5'
versionName: '26.11.6'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
@@ -0,0 +1,48 @@
import { notFound, redirect } from "next/navigation";
import { getLocale, getTranslations } from "next-intl/server";
import { DishForm } from "@/components/dishes/dish-form";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { getDish } from "@/lib/dishes";
export const dynamic = "force-dynamic";
// Bearbeiten zeigt die Mengen für vier Portionen (oder was man dort einträgt).
const PORTIONS = 4;
export default async function EditDishPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
const session = await requireSession();
if (session.role !== "admin" && session.role !== "member") redirect(`/gerichte/${id}`);
const locale = await getLocale();
const t = await getTranslations("dishes");
const dish = await withHousehold(session.householdId, (c) => getDish(c, id, locale));
if (!dish) notFound();
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">{dish.title}</p>
<h1 className="text-4xl leading-tight">{t("form.editTitle")}</h1>
</header>
<DishForm
initial={{
id: dish.id,
title: dish.title,
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,
note: i.note,
})),
steps: dish.steps.map((s) => ({ text: s.text, timerMinutes: s.timerSeconds ? Math.round(s.timerSeconds / 60) : null })),
}}
/>
</main>
);
}
+64
View File
@@ -0,0 +1,64 @@
import { ChevronLeft } from "lucide-react";
import Link from "next/link";
import { notFound } from "next/navigation";
import { getLocale, getTranslations } from "next-intl/server";
import { DishActions, PhotoButton } from "@/components/dishes/dish-actions";
import { DishPhoto } from "@/components/dishes/dish-tile";
import { PortionScaler } from "@/components/dishes/portion-scaler";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { getDish } from "@/lib/dishes";
export const dynamic = "force-dynamic";
// Ein Gericht: Foto oben, Titel, Eigenschaften, Zutaten in der gewählten
// Portionszahl (Vorgabe: so viele, wie der Haushalt Köpfe hat), Schritte.
export default async function DishPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
const session = await requireSession();
const locale = await getLocale();
const t = await getTranslations("dishes");
const { dish, people } = await withHousehold(session.householdId, async (c) => ({
dish: await getDish(c, id, locale),
people: (await c.query("select count(*)::int as n from members where role <> 'guest'")).rows[0].n as number,
}));
if (!dish) notFound();
const canWrite = session.role === "admin" || session.role === "member";
const meta = [dish.effortMinutes ? t("minutes", { n: dish.effortMinutes }) : null, dish.base ? t(`bases.${dish.base}`) : null]
.filter(Boolean)
.join(" · ");
return (
<main className="mx-auto flex max-w-2xl 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"
aria-label={t("title")}
className="absolute left-3 top-3 flex size-11 items-center justify-center rounded-full bg-background/90 text-foreground"
>
<ChevronLeft aria-hidden className="size-6" />
</Link>
{canWrite ? <PhotoButton id={dish.id} hasPhoto={Boolean(dish.photo)} /> : null}
</div>
<div className="flex flex-col gap-5 px-4">
<header className="flex flex-col gap-1">
{dish.tags.length ? <p className="eyebrow">{dish.tags.map((tag) => t(`tags.${tag}`)).join(" · ")}</p> : null}
<h1 className="text-4xl leading-tight">{dish.title}</h1>
{meta ? <p className="text-muted-foreground">{meta}</p> : null}
</header>
{canWrite ? <DishActions id={dish.id} /> : null}
<PortionScaler ingredients={dish.ingredients} steps={dish.steps} initialPortions={Math.min(8, Math.max(2, people))} />
{dish.sourceUrl ? (
<p className="text-sm text-muted-foreground">
{t("detail.source")}:{" "}
<a href={dish.sourceUrl} rel="noreferrer noopener" target="_blank" className="inline-flex min-h-11 items-center underline">
{new URL(dish.sourceUrl).hostname}
</a>
</p>
) : null}
</div>
</main>
);
}
+47
View File
@@ -0,0 +1,47 @@
import { Camera, ChevronRight, Link2, PenLine, Sparkles } from "lucide-react";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { requireSession } from "@/lib/auth/session";
// Wege in den Pool. Das Foto aus dem Kochbuch folgt mit Arbeitspaket 4c.
export default async function AddDishPage() {
await requireSession();
const t = await getTranslations("dishes");
const options = [
{ href: "/gerichte/vorlagen", icon: Sparkles, title: t("addStarters"), text: t("addStartersText") },
{ href: "/gerichte/link", icon: Link2, title: t("addLink"), text: t("addLinkText") },
{ href: "/gerichte/neu", icon: PenLine, title: t("addManual"), text: t("addManualText") },
];
const soon = [
{ icon: Camera, title: t("addPhoto") },
];
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">{t("addEyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("addTitle")}</h1>
</header>
<ul className="flex flex-col gap-3">
{options.map(({ href, icon: Icon, title, text }) => (
<li key={href}>
<Link href={href} className="flex min-h-11 items-center gap-4 rounded-2xl bg-muted p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
<Icon aria-hidden className="size-6 shrink-0 text-accent" strokeWidth={1.5} />
<span className="flex flex-1 flex-col">
<span className="font-semibold">{title}</span>
<span className="text-sm text-muted-foreground">{text}</span>
</span>
<ChevronRight aria-hidden className="size-5 text-muted-foreground" />
</Link>
</li>
))}
{soon.map(({ icon: Icon, title }) => (
<li key={title} className="flex min-h-11 items-center gap-4 rounded-2xl border border-dashed border-border p-4 text-muted-foreground">
<Icon aria-hidden className="size-6 shrink-0" strokeWidth={1.5} />
<span className="flex-1">{title}</span>
<span className="text-xs">{t("soon")}</span>
</li>
))}
</ul>
</main>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { LinkImport } from "@/components/dishes/link-import";
import { requireSession } from "@/lib/auth/session";
export default async function LinkDishPage() {
const session = await requireSession();
if (session.role !== "admin" && session.role !== "member") redirect("/gerichte");
const t = await getTranslations("dishes");
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">{t("addEyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("link.title")}</h1>
</header>
<LinkImport />
</main>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { redirect } from "next/navigation";
import { getTranslations } from "next-intl/server";
import { DishForm } from "@/components/dishes/dish-form";
import { requireSession } from "@/lib/auth/session";
export default async function NewDishPage() {
const session = await requireSession();
if (session.role !== "admin" && session.role !== "member") redirect("/gerichte");
const t = await getTranslations("dishes");
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">{t("addEyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("form.newTitle")}</h1>
</header>
<DishForm />
</main>
);
}
+97
View File
@@ -0,0 +1,97 @@
import { Plus } from "lucide-react";
import Link from "next/link";
import { getTranslations } from "next-intl/server";
import { DishTile } from "@/components/dishes/dish-tile";
import { UndoArchive } from "@/components/dishes/undo-archive";
import { buttonVariants } from "@/components/ui/button";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
import { listDishes } from "@/lib/dishes";
import { cn } from "@/lib/utils";
export const dynamic = "force-dynamic";
// Der Pool: Stammgerichte als Bildkacheln, daneben „Ausprobieren“.
// Die Hauptaktion („Gericht hinzufügen“) sitzt unten rechts unter dem Daumen.
export default async function DishesPage({ searchParams }: { searchParams: Promise<{ ansicht?: string; entfernt?: string }> }) {
const session = await requireSession();
const { ansicht, entfernt } = await searchParams;
const trial = ansicht === "ausprobieren";
const t = await getTranslations("dishes");
const { all, removed } = await withHousehold(session.householdId, async (c) => ({
all: await listDishes(c),
removed:
entfernt && /^[0-9a-f-]{36}$/.test(entfernt)
? ((await c.query("select id, title from dishes where id = $1 and archived_at is not null", [entfernt])).rows[0] as
| { id: string; title: string }
| undefined)
: undefined,
}));
const dishes = all.filter((d) => d.isTrial === trial);
const canWrite = session.role === "admin" || session.role === "member";
const meta = (d: (typeof all)[number]) =>
[d.effortMinutes ? t("minutes", { n: d.effortMinutes }) : null, d.base ? t(`bases.${d.base}`) : null].filter(Boolean).join(" · ");
return (
<main className="mx-auto flex max-w-2xl flex-col gap-5 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>
{removed ? <UndoArchive id={removed.id} title={removed.title} /> : null}
<nav aria-label={t("title")} className="flex gap-2">
{[
{ href: "/gerichte", label: `${t("pool")} · ${all.filter((d) => !d.isTrial).length}`, active: !trial },
{ href: "/gerichte?ansicht=ausprobieren", label: `${t("trial")} · ${all.filter((d) => d.isTrial).length}`, active: trial },
].map((tab) => (
<Link
key={tab.href}
href={tab.href}
aria-current={tab.active ? "page" : undefined}
className={cn(
"inline-flex min-h-11 items-center rounded-full px-4 text-sm font-semibold",
tab.active ? "bg-foreground text-background" : "bg-muted text-foreground",
)}
>
{tab.label}
</Link>
))}
</nav>
{dishes.length ? (
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3">
{dishes.map((d) => (
<li key={d.id}>
<DishTile id={d.id} title={d.title} photo={d.photo} meta={meta(d)} />
</li>
))}
</ul>
) : (
<section className="flex flex-col items-start gap-3 rounded-2xl bg-muted p-5">
<h2 className="text-2xl">{trial ? t("trial") : t("emptyTitle")}</h2>
<p className="text-muted-foreground">{trial ? t("emptyTrial") : t("emptyText")}</p>
{!trial && canWrite ? (
<Link href="/gerichte/vorlagen" className={buttonVariants({ variant: "secondary" })}>
{t("addStarters")}
</Link>
) : null}
</section>
)}
{canWrite ? (
<Link
href="/gerichte/hinzufuegen"
className={cn(
buttonVariants({ size: "lg" }),
"fixed bottom-[calc(4.5rem+env(safe-area-inset-bottom))] right-4 z-10 shadow-lg",
)}
>
<Plus aria-hidden />
{t("add")}
</Link>
) : null}
</main>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { getLocale, getTranslations } from "next-intl/server";
import { StarterPicker } from "@/components/dishes/starter-picker";
import { requireSession } from "@/lib/auth/session";
import { withHousehold } from "@/lib/db";
export const dynamic = "force-dynamic";
// Startergerichte in der Sprache der Person (FR und ES bekommen vorerst die englischen).
export default async function StartersPage() {
const session = await requireSession();
const locale = await getLocale();
const t = await getTranslations("dishes");
const starterLocale = locale === "de" ? "de" : "en";
const rows = await withHousehold(session.householdId, async (c) =>
(
await c.query(
`select s.key, s.title, s.base, s.effort_minutes,
exists (select 1 from dishes d where d.starter_key = s.key and d.archived_at is null) as in_pool
from starter_dishes s where s.locale = $1 order by s.position`,
[starterLocale],
)
).rows,
);
const starters = rows.map((r) => ({
key: r.key,
title: r.title,
inPool: r.in_pool,
meta: [r.effort_minutes ? t("minutes", { n: r.effort_minutes }) : null, r.base ? t(`bases.${r.base}`) : null].filter(Boolean).join(" · "),
}));
return (
<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("starters.eyebrow")}</p>
<h1 className="text-4xl leading-tight">{t("starters.title")}</h1>
<p className="text-muted-foreground">{t("starters.intro")}</p>
</header>
<StarterPicker starters={starters} />
</main>
);
}
+18
View File
@@ -0,0 +1,18 @@
import { z } from "zod";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, readJson } from "@/lib/auth/http";
import { setArchived } from "@/lib/dishes";
import { withHousehold } from "@/lib/db";
export const dynamic = "force-dynamic";
// Entfernen ohne Rückfrage, dafür mit Rückgängig (Leitprinzip 4): archived true/false.
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;
const body = z.object({ archived: z.boolean() }).safeParse(await readJson(request));
if (!body.success || !/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
const ok = await withHousehold(session.householdId, (c) => setArchived(c, id, body.data.archived));
return ok ? new Response(null, { status: 204 }) : fail("notFound", 404);
}
+29
View File
@@ -0,0 +1,29 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json } from "@/lib/auth/http";
import { withHousehold } from "@/lib/db";
import { PhotoRejected, removePhoto, storePhoto } from "@/lib/photos";
export const dynamic = "force-dynamic";
// Eigenes Foto am Gericht (Konzept: „Die Fotos der eigenen Gerichte tragen die Oberfläche“).
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 form = await request.formData().catch(() => null);
const file = form?.get("photo");
if (!(file instanceof File)) return fail("invalid", 400);
const old = await withHousehold(session.householdId, async (c) => (await c.query("select photo_path from dishes where id = $1", [id])).rows[0]);
if (!old) return fail("notFound", 404);
let relative: string;
try {
relative = await storePhoto(session.householdId, id, file);
} catch (error) {
if (error instanceof PhotoRejected) return fail("photo", 400);
throw error;
}
await withHousehold(session.householdId, (c) => c.query("update dishes set photo_path = $2, updated_at = now() where id = $1", [id, relative]));
if (old.photo_path && old.photo_path !== relative) await removePhoto(old.photo_path);
return json({ photo: relative });
}
+23
View File
@@ -0,0 +1,23 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { dishInput, InvalidAmount, saveDish } from "@/lib/dishes";
import { withHousehold } from "@/lib/db";
export const dynamic = "force-dynamic";
// Gericht ändern: Inhalt, Zutaten und Schritte werden ersetzt.
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardWrite(request);
if (isResponse(session)) return session;
const body = dishInput.safeParse(await readJson(request));
if (!body.success || !/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
try {
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);
if (error instanceof Error && error.message === "not found") return fail("notFound", 404);
throw error;
}
}
+21
View File
@@ -0,0 +1,21 @@
import { z } from "zod";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { withHousehold } from "@/lib/db";
import { adoptStarterDish } from "@/lib/starter";
export const dynamic = "force-dynamic";
// Startergerichte in den eigenen Pool übernehmen (Onboarding, Schritt 4).
export async function POST(request: Request) {
const session = await guardWrite(request);
if (isResponse(session)) return session;
const body = z.object({ keys: z.array(z.string().regex(/^[a-z]{2}_[a-z0-9_]+$/)).min(1).max(30) }).safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
const ids = await withHousehold(session.householdId, async (c) => {
const out = [];
for (const key of body.data.keys) out.push((await adoptStarterDish(c, session.householdId, session.memberId, key)).dishId);
return out;
});
return json({ ids });
}
+49
View File
@@ -0,0 +1,49 @@
import { getLocale } from "next-intl/server";
import { z } from "zod";
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { FetchRefused, fetchPublic } from "@/lib/fetch-safe";
import { allIngredients } from "@/lib/ingredients";
import { INPUT_UNITS } from "@/lib/dishes";
import { extractRecipe, matchLines } from "@/lib/recipe-import";
import { toBase } from "@/lib/units";
export const dynamic = "force-dynamic";
// Rezept-Link → Entwurf. Gespeichert wird nichts: Die Person sieht den
// Entwurf im Formular, prüft die Mengen und speichert selbst.
export async function POST(request: Request) {
const session = await guardWrite(request);
if (isResponse(session)) return session;
const body = z.object({ url: z.string().url().max(2000) }).safeParse(await readJson(request));
if (!body.success) return fail("url", 400);
let page;
try {
page = await fetchPublic(body.data.url);
} catch (error) {
if (error instanceof FetchRefused) return fail(error.message === "url" || error.message === "host" || error.message === "port" ? "url" : "unreachable", 422);
throw error;
}
const recipe = extractRecipe(page.body.toString("utf8"));
if (!recipe || !recipe.title) return fail("noRecipe", 422);
const locale = await getLocale();
const lines = matchLines(recipe.ingredients, await allIngredients(), locale);
return json({
title: recipe.title,
portions: recipe.yield ?? 4,
effortMinutes: recipe.totalMinutes,
sourceUrl: page.url,
imageUrl: recipe.image ? new URL(recipe.image, page.url).toString() : null,
ingredients: lines
.filter((l) => l.ingredient)
.map((l) => {
// Maße, die das Formular nicht anbietet (cl, Tasse), gleich in die Basiseinheit.
if (l.qty !== null && l.unit && !(INPUT_UNITS as readonly string[]).includes(l.unit)) {
return { ingredient: l.ingredient, qty: toBase(l.qty, l.unit, l.ingredient!.unit), unit: l.ingredient!.unit, note: l.note };
}
return { ingredient: l.ingredient, qty: l.qty, unit: l.unit, note: l.note };
}),
unmatched: lines.filter((l) => !l.ingredient).map((l) => l.raw),
steps: recipe.steps.map((text) => ({ text, timerMinutes: null })),
});
}
+36
View File
@@ -0,0 +1,36 @@
import { guardWrite, isResponse } from "@/lib/auth/guard";
import { fail, json, readJson } from "@/lib/auth/http";
import { dishInput, InvalidAmount, saveDish } from "@/lib/dishes";
import { withHousehold } from "@/lib/db";
import { fetchPublic } from "@/lib/fetch-safe";
import { storePhotoBytes } from "@/lib/photos";
export const dynamic = "force-dynamic";
// Das Bild einer importierten Seite: holen wie die Seite (lib/fetch-safe.ts),
// verkleinern wie ein eigenes Foto. Klappt es nicht, bleibt das Gericht ohne Bild.
async function attachImage(householdId: string, dishId: string, url: string) {
try {
const { body } = await fetchPublic(url, "image");
const relative = await storePhotoBytes(householdId, dishId, body);
await withHousehold(householdId, (c) => c.query("update dishes set photo_path = $2 where id = $1", [dishId, relative]));
} catch {
// ohne Bild weiter
}
}
// Gericht anlegen (Erwachsene: Admins und Mitglieder).
export async function POST(request: Request) {
const session = await guardWrite(request);
if (isResponse(session)) return session;
const body = dishInput.safeParse(await readJson(request));
if (!body.success) return fail("invalid", 400);
try {
const id = await withHousehold(session.householdId, (c) => saveDish(c, session.householdId, session.memberId, body.data));
if (body.data.imageUrl) await attachImage(session.householdId, id, body.data.imageUrl);
return json({ id }, 201);
} catch (error) {
if (error instanceof InvalidAmount) return fail("amount", 400);
throw error;
}
}
+22
View File
@@ -0,0 +1,22 @@
import { guardRead, isResponse } from "@/lib/auth/guard";
import { fail } from "@/lib/auth/http";
import { withHousehold } from "@/lib/db";
import { readPhoto } from "@/lib/photos";
export const dynamic = "force-dynamic";
// Foto eines Gerichts — nur für den eigenen Haushalt (Zeilensicherheit). Die
// Adresse trägt die Prüfsumme (?v=…), also darf der Browser es lange behalten.
export async function GET(_: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const session = await guardRead();
if (isResponse(session)) return session;
if (!/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
const row = await withHousehold(session.householdId, async (c) => (await c.query("select photo_path from dishes where id = $1", [id])).rows[0]);
if (!row?.photo_path) return fail("notFound", 404);
const body = await readPhoto(row.photo_path).catch(() => null);
if (!body) return fail("notFound", 404);
return new Response(new Uint8Array(body), {
headers: { "content-type": "image/webp", "cache-control": "private, max-age=31536000, immutable" },
});
}
+17
View File
@@ -0,0 +1,17 @@
import { getLocale } from "next-intl/server";
import { guardRead, isResponse } from "@/lib/auth/guard";
import { json } from "@/lib/auth/http";
import { searchIngredients } from "@/lib/ingredient-search";
import { allIngredients } from "@/lib/ingredients";
export const dynamic = "force-dynamic";
// Zutaten-Suche beim Tippen, in der Sprache der Person.
export async function GET(request: Request) {
const session = await guardRead();
if (isResponse(session)) return session;
const q = new URL(request.url).searchParams.get("q") ?? "";
const locale = await getLocale();
const hits = searchIngredients(await allIngredients(), q.slice(0, 60), locale);
return json(hits.map((i) => ({ id: i.id, name: i.names[locale] ?? i.names.en, unit: i.unit })));
}
+4 -3
View File
@@ -1,15 +1,16 @@
"use client";
import { Ellipsis, Sun } from "lucide-react";
import { Ellipsis, Sun, UtensilsCrossed } from "lucide-react";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useTranslations } from "next-intl";
import { cn } from "@/lib/utils";
// Untere Leiste unter dem Daumen (Leitprinzip 8). Plan, Einkauf und Gerichte
// kommen mit ihren Arbeitspaketen dazu.
// Untere Leiste unter dem Daumen (Leitprinzip 8). Plan und Einkauf kommen
// mit ihren Arbeitspaketen dazu.
const ITEMS = [
{ href: "/", key: "today", icon: Sun },
{ href: "/gerichte", key: "dishes", icon: UtensilsCrossed },
{ href: "/mehr", key: "more", icon: Ellipsis },
] as const;
+102
View File
@@ -0,0 +1,102 @@
"use client";
import { Camera, Pencil, Trash2 } from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useRef, useState } from "react";
import { Button, buttonVariants } from "@/components/ui/button";
import { ErrorNotice } from "@/components/ui/notice";
// Foto aufnehmen: sitzt auf dem Bild selbst; die Kamera des Handys öffnet sich direkt.
export function PhotoButton({
id,
hasPhoto,
}: {
id: string;
hasPhoto: boolean;
}) {
const t = useTranslations("dishes.detail");
const router = useRouter();
const input = useRef<HTMLInputElement>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
async function upload(file: File) {
setBusy(true);
setError(false);
const form = new FormData();
form.append("photo", file);
const res = await fetch(`/api/dishes/${id}/photo`, {
method: "POST",
body: form,
});
setBusy(false);
if (res.ok) router.refresh();
else setError(true);
}
return (
<>
<input
ref={input}
type="file"
accept="image/*"
capture="environment"
className="sr-only"
tabIndex={-1}
aria-hidden
onChange={(e) => e.target.files?.[0] && upload(e.target.files[0])}
/>
<Button
variant="secondary"
disabled={busy}
onClick={() => input.current?.click()}
className="absolute bottom-3 right-3 bg-background/90 hover:bg-background"
>
<Camera aria-hidden />
{hasPhoto ? t("photoChange") : t("photo")}
</Button>
{error ? (
<div className="absolute inset-x-3 top-16">
<ErrorNotice className="bg-background">{t("photoError")}</ErrorNotice>
</div>
) : null}
</>
);
}
// Bearbeiten und Entfernen (mit Rückgängig auf der nächsten Seite).
export function DishActions({ id }: { id: string }) {
const t = useTranslations("dishes.detail");
const router = useRouter();
const [busy, setBusy] = useState(false);
return (
<div className="flex gap-2">
<Link
href={`/gerichte/${id}/bearbeiten`}
className={buttonVariants({ variant: "secondary" })}
>
<Pencil aria-hidden />
{t("edit")}
</Link>
<Button
variant="ghost"
disabled={busy}
onClick={async () => {
setBusy(true);
const res = await fetch(`/api/dishes/${id}/archive`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ archived: true }),
});
if (res.ok) router.replace(`/gerichte?entfernt=${id}`);
else setBusy(false);
}}
>
<Trash2 aria-hidden />
{t("remove")}
</Button>
</div>
);
}
+396
View File
@@ -0,0 +1,396 @@
"use client";
import { ArrowDown, ArrowUp, Plus, X } from "lucide-react";
import { useRouter } from "next/navigation";
import { 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 { cn } from "@/lib/utils";
type Picked = { id: string; name: string; unit: BaseUnit };
type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string };
type StepRow = { key: number; text: string; timer: string };
export type DishFormValue = {
id?: string;
title: string;
portions: number;
base: string | null;
tags: string[];
effortMinutes: number | null;
isTrial: boolean;
// Beim Import kann die Menge fehlen (passt nicht zur Zutat) — dann trägt die Person sie ein.
ingredients: { ingredient: Picked; qty: number | null; unit?: string | null; note: string | null }[];
steps: { text: string; timerMinutes: number | null }[];
sourceUrl?: string | null;
imageUrl?: string | null;
/** Zeilen einer Rezeptseite, die keiner Zutat zugeordnet werden konnten. */
unmatched?: string[];
};
const UNITS_FOR: Record<BaseUnit, string[]> = {
g: ["g", "kg", "tbsp", "tsp", "pinch"],
ml: ["ml", "l", "tbsp", "tsp", "pinch"],
piece: ["piece"],
};
let counter = 0;
const next = () => ++counter;
const formatQty = (n: number) => String(Math.round(n * 100) / 100).replace(".", ",");
// Ein Gericht von Hand anlegen oder ändern. Mengen gibt man für das ganze
// Rezept ein („500 g für 4 Portionen“); der Server rechnet sie auf eine
// Portion um (lib/dishes.ts).
export function DishForm({ initial }: { initial?: DishFormValue }) {
const t = useTranslations("dishes");
const router = useRouter();
const [title, setTitle] = useState(initial?.title ?? "");
const [portions, setPortions] = useState(String(initial?.portions ?? 4));
const [base, setBase] = useState(initial?.base ?? "");
const [effort, setEffort] = useState(initial?.effortMinutes ? String(initial.effortMinutes) : "");
const [tags, setTags] = useState<Set<string>>(new Set(initial?.tags ?? []));
const [isTrial, setIsTrial] = useState(initial?.isTrial ?? false);
const [rows, setRows] = useState<Row[]>(
initial?.ingredients.length
? initial.ingredients.map((i) => ({
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,
note: i.note ?? "",
}))
: [{ key: next(), ingredient: null, qty: "", unit: "g", note: "" }],
);
const [steps, setSteps] = useState<StepRow[]>(
initial?.steps.length
? initial.steps.map((s) => ({ key: next(), text: s.text, timer: s.timerMinutes ? String(s.timerMinutes) : "" }))
: [{ key: next(), text: "", timer: "" }],
);
const [error, setError] = useState<string | null>(null);
const [checked, setChecked] = useState(false);
const [busy, setBusy] = useState(false);
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) =>
setSteps((ss) => {
const copy = [...ss];
const [item] = copy.splice(index, 1);
copy.splice(index + by, 0, item!);
return copy;
});
async function submit(event: React.FormEvent) {
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");
return;
}
const ingredients = rows
.filter((r) => r.ingredient && r.qty.trim())
.map((r) => ({ ingredientId: r.ingredient!.id, qty: parseNumber(r.qty) ?? -1, unit: r.unit, note: r.note.trim() || null }));
if (!title.trim() || !n || n < 1 || ingredients.some((i) => !(i.qty > 0))) {
setError("invalid");
return;
}
const body = {
title: title.trim(),
portions: Math.round(n),
base: base || null,
tags: [...tags],
effortMinutes: effort ? Math.round(parseNumber(effort) ?? 0) || null : null,
isTrial,
sourceUrl: initial?.sourceUrl ?? null,
imageUrl: initial?.id ? null : (initial?.imageUrl ?? null),
ingredients,
steps: steps
.filter((s) => s.text.trim())
.map((s) => ({ text: s.text.trim(), timerMinutes: s.timer ? Math.round(parseNumber(s.timer) ?? 0) || null : null })),
};
setBusy(true);
setError(null);
const res = await fetch(initial?.id ? `/api/dishes/${initial.id}` : "/api/dishes", {
method: initial?.id ? "PUT" : "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
});
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");
}
return (
<form onSubmit={submit} className="flex flex-col gap-6">
<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")} />
</div>
<div className="feldreihe grid grid-cols-2 gap-3">
<div className="flex flex-col gap-2">
<Label htmlFor="effort">{t("form.effort")}</Label>
<Input id="effort" inputMode="numeric" value={effort} onChange={(e) => setEffort(e.target.value)} />
</div>
<div className="flex flex-col gap-2">
<Label htmlFor="base">{t("form.base")}</Label>
<select id="base" value={base} onChange={(e) => setBase(e.target.value)} className="min-h-11 rounded-xl border border-border bg-background px-3 text-base">
<option value="">{t("form.baseNone")}</option>
{BASES.map((b) => (
<option key={b} value={b}>
{t(`bases.${b}`)}
</option>
))}
</select>
</div>
</div>
<fieldset className="flex flex-col gap-2">
<legend className="mb-2 text-sm font-medium">{t("form.tags")}</legend>
<div className="flex flex-wrap gap-2">
{TAGS.map((tag) => {
const on = tags.has(tag);
return (
<button
key={tag}
type="button"
aria-pressed={on}
onClick={() =>
setTags((prev) => {
const s = new Set(prev);
if (s.has(tag)) s.delete(tag);
else s.add(tag);
return s;
})
}
className={cn("min-h-11 rounded-full border px-4 text-sm", on ? "border-accent bg-accent text-background" : "border-border")}
>
{t(`tags.${tag}`)}
</button>
);
})}
</div>
</fieldset>
<label className="flex min-h-11 items-start gap-3">
<input type="checkbox" checked={isTrial} onChange={(e) => setIsTrial(e.target.checked)} className="mt-1 size-5 shrink-0 accent-primary" />
<span>
<span className="block">{t("form.trial")}</span>
<span className="block text-sm text-muted-foreground">{t("form.trialHint")}</span>
</span>
</label>
</section>
<section className="flex flex-col gap-3 border-t border-border pt-5">
<h2 className="eyebrow">{t("form.ingredients")}</h2>
<div className="flex items-center gap-3">
<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)} />
</div>
{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>
<ul className="list-disc pl-5 text-muted-foreground">
{initial.unmatched.map((line) => (
<li key={line}>{line}</li>
))}
</ul>
</div>
) : 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">
<div className="flex items-start gap-2">
<IngredientPicker value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: p.unit })} />
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t("form.removeIngredient")}
onClick={() => setRows((rs) => (rs.length > 1 ? rs.filter((r) => r.key !== row.key) : rs))}
>
<X aria-hidden />
</Button>
</div>
<div className="grid grid-cols-[1fr_auto] gap-2">
<Input
aria-label={t("form.amount")}
aria-invalid={checked && !!row.ingredient && !row.qty.trim() ? true : undefined}
inputMode="decimal"
placeholder={t("form.amount")}
value={row.qty}
onChange={(e) => update(row.key, { qty: e.target.value })}
/>
<select
aria-label={t("form.unit")}
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"
>
{UNITS_FOR[row.ingredient?.unit ?? "g"].map((u) => (
<option key={u} value={u}>
{t(`form.units.${u}`)}
</option>
))}
</select>
</div>
<Input
aria-label={t("form.note")}
placeholder={t("form.notePlaceholder")}
value={row.note}
maxLength={120}
onChange={(e) => update(row.key, { note: e.target.value })}
/>
</li>
))}
</ul>
<Button type="button" variant="outline" onClick={() => setRows((rs) => [...rs, { key: next(), ingredient: null, qty: "", unit: "g", note: "" }])}>
<Plus aria-hidden />
{t("form.ingredients")}
</Button>
</section>
<section className="flex flex-col gap-3 border-t border-border pt-5">
<h2 className="eyebrow">{t("form.steps")}</h2>
<ol className="flex flex-col gap-4">
{steps.map((s, index) => (
<li key={s.key} className="flex flex-col gap-2">
<Label htmlFor={`step-${s.key}`}>{t("form.step", { n: index + 1 })}</Label>
<textarea
id={`step-${s.key}`}
value={s.text}
rows={3}
maxLength={2000}
onChange={(e) => updateStep(s.key, { text: e.target.value })}
className="rounded-xl border border-border bg-background px-4 py-2 text-base"
/>
<div className="flex items-center gap-2">
<Input
aria-label={t("form.timer")}
placeholder={t("form.timer")}
inputMode="numeric"
className="w-36"
value={s.timer}
onChange={(e) => updateStep(s.key, { timer: e.target.value })}
/>
<span className="flex-1" />
<Button type="button" variant="ghost" size="icon" aria-label={t("form.moveUp")} disabled={index === 0} onClick={() => move(index, -1)}>
<ArrowUp aria-hidden />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t("form.moveDown")}
disabled={index === steps.length - 1}
onClick={() => move(index, 1)}
>
<ArrowDown aria-hidden />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t("form.removeStep")}
onClick={() => setSteps((ss) => (ss.length > 1 ? ss.filter((x) => x.key !== s.key) : ss))}
>
<X aria-hidden />
</Button>
</div>
</li>
))}
</ol>
<Button type="button" variant="outline" onClick={() => setSteps((ss) => [...ss, { key: next(), text: "", timer: "" }])}>
<Plus aria-hidden />
{t("form.addStep")}
</Button>
</section>
{error ? <ErrorNotice>{t(`form.errors.${error}`)}</ErrorNotice> : null}
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] 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>
</form>
);
}
// 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.
function IngredientPicker({ value, onPick }: { value: Picked | null; onPick: (p: Picked) => void }) {
const t = useTranslations("dishes.form");
const id = useId();
const [query, setQuery] = useState(value?.name ?? "");
const [hits, setHits] = useState<Picked[]>([]);
const [open, setOpen] = useState(false);
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(() => {
if (!open || !query.trim() || query === value?.name) {
setHits([]);
return;
}
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());
}, 150);
}, [query, open, value?.name]);
return (
<div className="relative flex-1">
<Input
id={id}
role="combobox"
aria-expanded={open && hits.length > 0}
aria-controls={`${id}-list`}
aria-autocomplete="list"
aria-label={t("searchIngredient")}
placeholder={t("searchIngredient")}
value={query}
autoComplete="off"
onFocus={() => setOpen(true)}
onChange={(e) => {
setQuery(e.target.value);
setOpen(true);
}}
/>
{open && query.trim() && query !== value?.name ? (
<ul id={`${id}-list`} role="listbox" className="absolute inset-x-0 top-full z-20 mt-1 overflow-hidden rounded-xl border border-border bg-card shadow-lg">
{hits.length ? (
hits.map((h) => (
<li key={h.id} role="option" aria-selected={value?.id === h.id}>
<button
type="button"
className="flex min-h-11 w-full items-center px-4 text-left hover:bg-muted"
onClick={() => {
onPick(h);
setQuery(h.name);
setOpen(false);
}}
>
{h.name}
</button>
</li>
))
) : (
<li className="px-4 py-3 text-sm text-muted-foreground">{t("noHits")}</li>
)}
</ul>
) : null}
</div>
);
}
+32
View File
@@ -0,0 +1,32 @@
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.
export function DishPhoto({ dishId, photo, className }: { dishId: string; photo: string | null; className?: string }) {
if (photo) {
const version = photo.split("-").at(-1)?.replace(".webp", "") ?? "";
// eslint-disable-next-line @next/next/no-img-element -- eigene Fotos, schon verkleinert; next/image bräuchte die Sitzung im Optimierer
return <img src={`/api/fotos/${dishId}?v=${version}`} alt="" className={cn("size-full object-cover", className)} loading="lazy" />;
}
return (
<div className={cn("flex size-full items-center justify-center bg-secondary", className)}>
<UtensilsCrossed aria-hidden className="size-1/4 text-accent/60" strokeWidth={1} />
</div>
);
}
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">
<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>
</Link>
);
}
+68
View File
@@ -0,0 +1,68 @@
"use client";
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";
import { DishForm, type DishFormValue } from "./dish-form";
// Rezept-Link → Entwurf im Formular. Die Seite wird auf dem Server gelesen
// (app/api/dishes/import); gespeichert wird erst, wenn die Person es will.
export function LinkImport() {
const t = useTranslations("dishes.link");
const [url, setUrl] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [draft, setDraft] = useState<DishFormValue | null>(null);
async function load(event: React.FormEvent) {
event.preventDefault();
setBusy(true);
setError(null);
const res = await fetch("/api/dishes/import", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ url: url.trim() }),
});
const data = await res.json().catch(() => ({}));
setBusy(false);
if (!res.ok) {
setError(["url", "unreachable", "noRecipe"].includes(data.error) ? data.error : "unknown");
return;
}
setDraft({ ...data, base: null, tags: [], isTrial: true });
}
if (draft) {
return (
<div className="flex flex-col gap-4">
<p className="text-sm text-muted-foreground">{t("check")}</p>
<DishForm initial={draft} />
</div>
);
}
return (
<form onSubmit={load} className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label htmlFor="recipe-url">{t("label")}</Label>
<Input
id="recipe-url"
type="url"
inputMode="url"
autoComplete="off"
required
placeholder="https://"
value={url}
onChange={(e) => setUrl(e.target.value)}
/>
<p className="text-sm text-muted-foreground">{t("hint")}</p>
</div>
{error ? <ErrorNotice>{t(`errors.${error}`)}</ErrorNotice> : null}
<Button type="submit" size="lg" disabled={busy || !url.trim()}>
{busy ? t("loading") : t("load")}
</Button>
</form>
);
}
+79
View File
@@ -0,0 +1,79 @@
"use client";
import { Minus, Plus, Timer } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import { useState } from "react";
import { Button } from "@/components/ui/button";
import { formatQuantity, scale, type BaseUnit } from "@/lib/units";
type Ingredient = { ingredientId: string; name: string; qtyPerPortion: number; unit: BaseUnit; note: string | null; isStaple: boolean };
type Step = { text: string; timerSeconds: number | null };
// Zutaten in der gewählten Portionszahl, darunter die Schritte. Die Mengen
// 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 [portions, setPortions] = useState(initialPortions);
return (
<>
<section className="flex flex-col gap-3 border-t border-border pt-5">
<div className="flex items-center justify-between gap-3">
<h2 className="eyebrow">{t("ingredients")}</h2>
<div className="flex items-center gap-1" role="group" aria-label={t("portions")}>
<Button variant="outline" size="icon" aria-label={t("fewer")} disabled={portions <= 1} onClick={() => setPortions((p) => p - 1)}>
<Minus aria-hidden />
</Button>
<output aria-live="polite" className="min-w-24 text-center text-sm font-semibold">
{portions} {t("portions")}
</output>
<Button variant="outline" size="icon" aria-label={t("more")} disabled={portions >= 30} onClick={() => setPortions((p) => p + 1)}>
<Plus aria-hidden />
</Button>
</div>
</div>
<ul className="flex flex-col divide-y divide-border">
{ingredients.map((i) => {
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
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="flex-1">
{i.name}
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
</span>
{i.isStaple ? <span className="text-xs text-muted-foreground">{t("staple")}</span> : null}
</li>
);
})}
</ul>
</section>
<section className="flex flex-col gap-3 border-t border-border pt-5">
<h2 className="eyebrow">{t("steps")}</h2>
<ol className="flex flex-col gap-4">
{steps.map((s, n) => (
<li key={n} className="flex gap-3">
<span aria-hidden className="flex size-8 shrink-0 items-center justify-center rounded-full bg-secondary font-serif text-lg">
{n + 1}
</span>
<div className="flex flex-col gap-1 pt-1">
<p>{s.text}</p>
{s.timerSeconds ? (
<p className="flex items-center gap-1 text-sm text-accent">
<Timer aria-hidden className="size-4" />
{t("stepTimer", { n: Math.round(s.timerSeconds / 60) })}
</p>
) : null}
</div>
</li>
))}
</ol>
</section>
</>
);
}
+87
View File
@@ -0,0 +1,87 @@
"use client";
import { Check } from "lucide-react";
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 { cn } from "@/lib/utils";
type Starter = { key: string; title: string; meta: string; inPool: boolean };
// Klassiker antippen, dann mit einem Knopf übernehmen. Was schon im Pool ist,
// steht da, ist aber nicht mehr wählbar.
export function StarterPicker({ starters }: { starters: Starter[] }) {
const t = useTranslations("dishes");
const router = useRouter();
const [chosen, setChosen] = useState<Set<string>>(new Set());
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
function toggle(key: string) {
setChosen((prev) => {
const next = new Set(prev);
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}
return (
<>
<ul className="flex flex-col divide-y divide-border">
{starters.map((s) => {
const on = chosen.has(s.key);
return (
<li key={s.key}>
<button
type="button"
disabled={s.inPool}
aria-pressed={s.inPool ? undefined : on}
onClick={() => toggle(s.key)}
className="flex min-h-14 w-full items-center gap-3 py-2 text-left disabled:opacity-70"
>
<span
aria-hidden
className={cn(
"flex size-7 shrink-0 items-center justify-center rounded-full border-2",
on || s.inPool ? "border-primary bg-primary text-primary-foreground" : "border-border",
)}
>
{on || s.inPool ? <Check className="size-4" strokeWidth={2.5} /> : null}
</span>
<span className="flex flex-1 flex-col">
<span className="font-serif text-lg leading-snug">{s.title}</span>
<span className="text-xs text-muted-foreground">{s.inPool ? t("starters.inPool") : s.meta}</span>
</span>
</button>
</li>
);
})}
</ul>
{error ? <ErrorNotice>{t("form.errors.unknown")}</ErrorNotice> : null}
<div className="sticky bottom-[calc(4rem+env(safe-area-inset-bottom))] z-10 bg-background/0 pb-2">
<Button
size="lg"
className="w-full shadow-lg"
disabled={!chosen.size || busy}
onClick={async () => {
setBusy(true);
setError(false);
const res = await fetch("/api/dishes/adopt", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ keys: [...chosen] }),
});
setBusy(false);
if (res.ok) router.push("/gerichte");
else setError(true);
}}
>
{t("starters.adopt", { n: chosen.size })}
</Button>
</div>
</>
);
}
+34
View File
@@ -0,0 +1,34 @@
"use client";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";
import { useState } from "react";
import { Button } from "@/components/ui/button";
// Nach dem Entfernen: ein Hinweis mit „Rückgängig“ statt einer Rückfrage vorher.
export function UndoArchive({ id, title }: { id: string; title: string }) {
const t = useTranslations("dishes.detail");
const router = useRouter();
const [busy, setBusy] = useState(false);
return (
<div role="status" className="flex items-center justify-between gap-3 rounded-2xl bg-foreground px-4 py-2 text-background">
<span className="text-sm">{t("removed", { title })}</span>
<Button
variant="ghost"
className="shrink-0 text-background hover:bg-background/10"
disabled={busy}
onClick={async () => {
setBusy(true);
await fetch(`/api/dishes/${id}/archive`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ archived: false }),
});
router.replace(`/gerichte/${id}`);
}}
>
{t("undo")}
</Button>
</div>
);
}
+1
View File
@@ -51,6 +51,7 @@ Das Repo erbt sie, weil es in der Organisation liegt.
3. **Seed:** etwa 300 kanonische Zutaten in vier Sprachen, Starter-Pool DE und EN, Gangfolgen REWE, Edeka, Lidl, Aldi.
**Erledigt** in 26.11.5 (340 Zutaten, je 15 Starter, fünf Gangfolgen; Einspielen bei jedem Start).
4. **Gerichte:** von Hand, Import per JSON-LD, Foto-Import über LiteLLM.
**4a und 4b erledigt** in 26.11.6 (Pool, Klassiker, Ansicht mit Portionen, Anlegen/Bearbeiten, Fotos, Rezept-Link über JSON-LD); 4c KI folgt.
5. **Wünschen:** Jetons, Kacheln, Kinder-Login mit Haushaltscode und PIN.
6. **Runde und Slots:** `lib/suggest.ts` mit Tests, Drag and Drop, Freigabe.
7. **Einkaufsliste:** `lib/aggregate.ts` mit Tests, Gangsortierung, Echtzeit (SSE), Offline-Warteschlange.
+161
View File
@@ -0,0 +1,161 @@
import { expect, test } from "@playwright/test";
import sharp from "sharp";
// Gerichte am iPhone: Pool leer, Klassiker übernehmen, Portionen hochrechnen,
// eigenes Gericht anlegen und ändern, Foto, entfernen mit Rückgängig.
// Läuft nach dem Ablauf mit Kais Sitzung.
test.describe.configure({ mode: "serial" });
test("an empty pool says what to do and offers the main action", async ({ page }) => {
await page.goto("/gerichte");
await expect(page.getByRole("heading", { level: 2, name: "Noch keine Gerichte" })).toBeVisible();
await page.getByRole("link", { name: "Gericht hinzufügen" }).click();
await expect(page).toHaveURL(/\/gerichte\/hinzufuegen$/);
});
test("adopting three classics fills the pool", async ({ page }) => {
await page.goto("/gerichte/vorlagen");
for (const title of ["Spaghetti Bolognese", "Linseneintopf", "Flammkuchen"]) await page.getByRole("button", { name: new RegExp(title) }).click();
await page.getByRole("button", { name: "3 Gerichte übernehmen" }).click();
await expect(page).toHaveURL(/\/gerichte$/);
await expect(page.getByRole("link", { name: /Spaghetti Bolognese/ })).toBeVisible();
await expect(page.locator("main li")).toHaveCount(3);
await page.goto("/gerichte/vorlagen");
await expect(page.getByRole("button", { name: /Linseneintopf/ })).toBeDisabled();
});
test("a dish scales its ingredients with the portions", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Spaghetti Bolognese/ }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Spaghetti Bolognese");
const spaghetti = page.locator("li", { hasText: "Spaghetti" }).first();
await expect(spaghetti).toContainText("250 g");
await page.getByRole("button", { name: "Eine Portion mehr" }).click();
await page.getByRole("button", { name: "Eine Portion mehr" }).click();
await expect(page.locator("output")).toHaveText("4 Portionen");
await expect(spaghetti).toContainText("500 g");
});
test("an own dish is created with searched ingredients, then edited", async ({ page }) => {
await page.goto("/gerichte/neu");
await page.fill("#title", "Gemüsecurry");
await page.fill("#effort", "35");
await page.getByRole("button", { name: "vegetarisch" }).click();
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.getByRole("button", { name: "Zutaten" }).click();
await page.getByRole("combobox", { name: "Zutat suchen" }).nth(1).fill("kokos");
await page.getByRole("option", { name: "Kokosmilch", exact: true }).click();
await page.getByRole("textbox", { name: "Menge", exact: true }).nth(1).fill("400");
await page.getByLabel("Schritt 1").fill("Zwiebeln würfeln und anschwitzen.");
await page.getByRole("button", { name: "Speichern" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gemüsecurry");
await expect(page.locator("main")).toContainText("vegetarisch");
// 2 Zwiebeln für 4 Portionen → 1 für 2 Portionen.
await expect(page.locator("ul li", { hasText: "Zwiebeln" })).toContainText("1");
await expect(page.locator("ul li", { hasText: "Kokosmilch" })).toContainText("200 ml");
await page.getByRole("link", { name: "Bearbeiten" }).click();
await expect(page.locator("#title")).toHaveValue("Gemüsecurry");
await page.fill("#title", "Gemüsecurry mit Reis");
await page.getByRole("button", { name: "Speichern" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gemüsecurry mit Reis");
});
test("a photo from the phone becomes the dish photo", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Gemüsecurry/ }).click();
const png = await sharp({ create: { width: 1200, height: 900, channels: 3, background: { r: 230, g: 120, b: 90 } } }).png().toBuffer();
await page.locator("input[type=file]").setInputFiles({ name: "curry.png", mimeType: "image/png", buffer: png });
const img = page.locator("main img").first();
await expect(img).toHaveAttribute("src", /\/api\/fotos\//);
const res = await page.request.get((await img.getAttribute("src"))!);
expect(res.status()).toBe(200);
expect(res.headers()["content-type"]).toBe("image/webp");
});
test("removing a dish offers undo instead of asking first", async ({ page }) => {
await page.goto("/gerichte");
await page.getByRole("link", { name: /Flammkuchen/ }).click();
await page.getByRole("button", { name: "Entfernen" }).click();
await expect(page).toHaveURL(/entfernt=/);
await expect(page.getByRole("status")).toContainText("Flammkuchen");
await expect(page.getByRole("link", { name: /Flammkuchen/ })).toHaveCount(0);
await page.getByRole("button", { name: "Rückgängig" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Flammkuchen");
});
// Rezept-Link: eine Rezeptseite wie bei den Portalen, ausgeliefert von einem
// kleinen Server im Test. Die App darf ihn nur, weil IMPORT_TEST_ORIGIN genau
// diese Adresse nennt (lib/fetch-safe.ts); jede andere lokale Adresse lehnt sie ab.
test.describe("recipe link", () => {
let server: import("node:http").Server;
const origin = process.env.IMPORT_TEST_ORIGIN ?? "http://127.0.0.1:3021";
test.beforeAll(async () => {
const { createServer } = await import("node:http");
const jpg = await sharp({ create: { width: 800, height: 600, channels: 3, background: { r: 200, g: 160, b: 90 } } }).jpeg().toBuffer();
const recipe = {
"@context": "https://schema.org",
"@graph": [
{ "@type": "WebSite", name: "Testküche" },
{
"@type": "Recipe",
name: "Linsensuppe vom Blog",
recipeYield: "4 Portionen",
totalTime: "PT45M",
image: "/bild.jpg",
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Handvoll Glück"],
recipeInstructions: [{ "@type": "HowToStep", text: "Zwiebeln anschwitzen." }, { "@type": "HowToStep", text: "Linsen dazu und weich kochen." }],
},
],
};
server = createServer((req, res) => {
if (req.url === "/bild.jpg") {
res.writeHead(200, { "content-type": "image/jpeg" }).end(jpg);
} else if (req.url === "/rezept") {
res.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(
`<html><head><script type="application/ld+json">${JSON.stringify(recipe)}</script></head><body>Rezept</body></html>`,
);
} else {
res.writeHead(200, { "content-type": "text/html" }).end("<html><body>Kein Rezept</body></html>");
}
});
await new Promise<void>((done) => server.listen(Number(new URL(origin).port), "127.0.0.1", done));
});
test.afterAll(() => new Promise<void>((done) => server.close(() => done())));
test("a page without a recipe says so, a local address is refused", async ({ page }) => {
await page.goto("/gerichte/hinzufuegen");
await page.getByRole("link", { name: /Rezept-Link einfügen/ }).click();
await page.fill("#recipe-url", `${origin}/leer`);
await page.getByRole("button", { name: "Rezept holen" }).click();
await expect(page.locator("main [role=alert]")).toContainText("kein Rezept");
await page.fill("#recipe-url", "http://127.0.0.1:3020/gerichte");
await page.getByRole("button", { name: "Rezept holen" }).click();
await expect(page.locator("main [role=alert]")).toContainText("öffentlichen Link");
});
test("a recipe link becomes a draft, the person fills the gaps and saves", async ({ page }) => {
await page.goto("/gerichte/link");
await page.fill("#recipe-url", `${origin}/rezept`);
await page.getByRole("button", { name: "Rezept holen" }).click();
await expect(page.locator("#title")).toHaveValue("Linsensuppe vom Blog");
await expect(page.locator("#effort")).toHaveValue("45");
await expect(page.getByRole("note")).toContainText("1 Handvoll Glück");
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
await expect(amounts).toHaveCount(3);
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.
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 page.getByRole("button", { name: "Speichern" }).click();
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Linsensuppe vom Blog");
await expect(page.locator("main img").first()).toHaveAttribute("src", /\/api\/fotos\//);
await expect(page.locator(`main a[href="${origin}/rezept"]`)).toBeVisible();
});
});
+16 -2
View File
@@ -10,6 +10,12 @@ import { expect, test, type Page } from "@playwright/test";
const SIGNED_IN = [
{ path: "/", heading: "Hallo Kai" },
{ path: "/mehr", heading: "Familie Böhm" },
{ path: "/gerichte", heading: "Gerichte" },
{ path: "/gerichte?ansicht=ausprobieren", heading: "Gerichte" },
{ path: "/gerichte/hinzufuegen", heading: "Gericht hinzufügen" },
{ path: "/gerichte/vorlagen", heading: "Gerichte übernehmen" },
{ path: "/gerichte/neu", heading: "Neues Gericht" },
{ path: "/gerichte/link", heading: "Rezept-Link einfügen" },
];
const SIGNED_OUT = [
{ path: "/anmelden", heading: "Anmelden" },
@@ -28,9 +34,10 @@ async function check(page: Page, path: string, heading: string) {
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
expect(overflow, "horizontal overflow").toBeLessThanOrEqual(0);
// Jedes Bedienelement mindestens 44 px hoch.
// Jedes Bedienelement mindestens 44 px hoch. Radio und Checkbox zählen über
// ihr Label, das die ganze Zeile umfasst; das Dateifeld über seinen Knopf.
const small = await page.evaluate(() =>
[...document.querySelectorAll<HTMLElement>("main button, main a, main input:not([type=radio]), main select, nav a")]
[...document.querySelectorAll<HTMLElement>("main button, main a, main input:not([type=radio]):not([type=checkbox]):not([type=file]), main select, nav a")]
.filter((el) => el.offsetParent !== null)
.map((el) => ({ text: (el.innerText || el.getAttribute("aria-label") || el.id || el.tagName).slice(0, 40), h: el.getBoundingClientRect().height }))
.filter((x) => x.h < 44),
@@ -61,6 +68,13 @@ for (const { path, heading } of SIGNED_OUT) {
});
}
test("signed in: a dish and its edit form", async ({ page }) => {
await page.goto("/gerichte");
const href = await page.getByRole("link", { name: /Spaghetti Bolognese/ }).getAttribute("href");
await check(page, href!, "Spaghetti Bolognese");
await check(page, `${href}/bearbeiten`, "Gericht bearbeiten");
});
test("the bottom bar never covers the last element", async ({ page }) => {
await page.goto("/mehr");
await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
+28
View File
@@ -0,0 +1,28 @@
import "server-only";
import { withAuth } from "@/lib/db";
import { fail, sameOrigin } from "./http";
import { getSession, type Session } from "./session";
import { loadInstance } from "./webauthn";
type Role = Session["role"];
const WRITERS: Role[] = ["admin", "member"];
/**
* Für jede Route, die etwas ändert: Sitzung, Ursprung (CSRF) und Rolle prüfen.
* Gibt die Sitzung zurück oder die fertige Fehlerantwort.
*/
export async function guardWrite(request: Request, roles: Role[] = WRITERS): Promise<Session | Response> {
const session = await getSession();
if (!session) return fail("signedOut", 401);
const instance = await withAuth(loadInstance);
if (!instance || !sameOrigin(request, instance.origin)) return fail("origin", 403);
if (!roles.includes(session.role)) return fail("forbidden", 403);
return session;
}
/** Für lesende Routen: nur die Sitzung. */
export async function guardRead(): Promise<Session | Response> {
return (await getSession()) ?? fail("signedOut", 401);
}
export const isResponse = (x: unknown): x is Response => x instanceof Response;
+152
View File
@@ -0,0 +1,152 @@
import "server-only";
import type { PoolClient } from "pg";
import { z } from "zod";
import { BASES, TAGS } from "./categories";
import { allIngredients } from "./ingredients";
import { toBase, type BaseUnit, type InputUnit } from "./units";
// Gerichte des Haushalts lesen und schreiben. Mengen kommen so, wie man sie
// für das ganze Rezept eintippt (z. B. „500 g für 4 Portionen“), und werden
// hier in Basiseinheiten pro Portion umgerechnet (CLAUDE.md, Regel 2).
// Alle Funktionen laufen in withHousehold(…).
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch"] as const;
export const dishInput = z.object({
title: z.string().trim().min(1).max(120),
portions: z.number().int().min(1).max(30),
base: z.enum(BASES).nullable(),
tags: z.array(z.enum(TAGS)).max(TAGS.length),
effortMinutes: z.number().int().min(1).max(1440).nullable(),
isTrial: z.boolean(),
sourceUrl: z.string().url().max(2000).nullable().optional(),
// Bild der importierten Rezeptseite; wird beim Anlegen geholt und als Foto gespeichert.
imageUrl: z.string().url().max(2000).nullable().optional(),
ingredients: z
.array(
z.object({
ingredientId: z.string().uuid(),
qty: z.number().positive().max(100000),
unit: z.enum(INPUT_UNITS),
note: z.string().trim().max(120).nullable().optional(),
}),
)
.max(60),
steps: z
.array(z.object({ text: z.string().trim().min(1).max(2000), timerMinutes: z.number().int().min(1).max(1440).nullable().optional() }))
.max(40),
});
export type DishInput = z.infer<typeof dishInput>;
export type DishSummary = {
id: string;
title: string;
base: string | null;
tags: string[];
effortMinutes: number | null;
isTrial: boolean;
photo: string | null;
starterKey: string | null;
};
export type DishDetail = DishSummary & {
sourceUrl: string | null;
ingredients: { ingredientId: string; name: string; qtyPerPortion: number; unit: BaseUnit; note: string | null; isStaple: boolean }[];
steps: { text: string; timerSeconds: number | null }[];
};
const summaryColumns = `id, title, base, tags, effort_minutes as "effortMinutes", is_trial as "isTrial",
photo_path as photo, starter_key as "starterKey"`;
export async function listDishes(client: PoolClient): Promise<DishSummary[]> {
const { rows } = await client.query(`select ${summaryColumns} from dishes where archived_at is null order by lower(title)`);
return rows;
}
export async function getDish(client: PoolClient, id: string, locale: string): Promise<DishDetail | null> {
const dish = (await client.query(`select ${summaryColumns}, source_url as "sourceUrl" from dishes where id = $1 and archived_at is null`, [id]))
.rows[0];
if (!dish) return null;
const names = new Map((await allIngredients()).map((i) => [i.id, i.names[locale] ?? i.names.en ?? ""]));
const ingredients = (
await client.query(
"select ingredient_id, qty_per_portion, unit, note, is_staple from dish_ingredients where dish_id = $1 order by position",
[id],
)
).rows.map((r) => ({
ingredientId: r.ingredient_id,
name: names.get(r.ingredient_id) ?? "",
qtyPerPortion: Number(r.qty_per_portion),
unit: r.unit,
note: r.note,
isStaple: r.is_staple,
}));
const steps = (await client.query("select text, timer_seconds from dish_steps where dish_id = $1 order by position", [id])).rows.map(
(r) => ({ text: r.text, timerSeconds: r.timer_seconds }),
);
return { ...dish, ingredients, steps };
}
export class InvalidAmount extends Error {}
/** Legt an (id leer) oder ersetzt Inhalt, Zutaten und Schritte. Gibt die Kennung zurück. */
export async function saveDish(client: PoolClient, householdId: string, memberId: string, input: DishInput, id?: string): Promise<string> {
const units = new Map((await allIngredients()).map((i) => [i.id, i.unit]));
const rows = input.ingredients.map((i, position) => {
const base = units.get(i.ingredientId);
if (!base) throw new InvalidAmount(i.ingredientId);
const total = toBase(i.qty, i.unit as InputUnit, base);
if (total === null) throw new InvalidAmount(i.ingredientId);
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position };
});
const values = [
input.title,
input.base,
input.tags,
input.effortMinutes,
input.isTrial,
input.sourceUrl ?? null,
];
let dishId = id;
if (dishId) {
const updated = await client.query(
`update dishes set title = $2, base = $3, tags = $4, effort_minutes = $5, is_trial = $6, source_url = $7, updated_at = now()
where id = $1 and archived_at is null`,
[dishId, ...values],
);
if (updated.rowCount !== 1) throw new Error("not found");
await client.query("delete from dish_ingredients where dish_id = $1", [dishId]);
await client.query("delete from dish_steps where dish_id = $1", [dishId]);
} else {
dishId = (
await client.query(
`insert into dishes (household_id, title, base, tags, effort_minutes, is_trial, source_url, created_by)
values ($1, $2, $3, $4, $5, $6, $7, $8) returning id`,
[householdId, ...values, memberId],
)
).rows[0].id as string;
}
for (const r of rows) {
await client.query(
`insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, note, position)
values ($1, $2, $3, $4, $5, $6, $7)`,
[householdId, dishId, r.ingredientId, r.perPortion, r.base, r.note ?? null, r.position],
);
}
for (const [position, s] of input.steps.entries()) {
await client.query("insert into dish_steps (household_id, dish_id, position, text, timer_seconds) values ($1, $2, $3, $4, $5)", [
householdId,
dishId,
position,
s.text,
s.timerMinutes ? s.timerMinutes * 60 : null,
]);
}
return dishId;
}
/** Nachsichtig statt vorsichtig (Leitprinzip 4): Entfernen archiviert, Rückgängig holt zurück. */
export async function setArchived(client: PoolClient, id: string, archived: boolean): Promise<boolean> {
const r = await client.query(`update dishes set archived_at = ${archived ? "now()" : "null"} where id = $1`, [id]);
return r.rowCount === 1;
}
+89
View File
@@ -0,0 +1,89 @@
import "server-only";
import { lookup } from "node:dns/promises";
import { isIP } from "node:net";
// Eine fremde Seite holen, ohne die Box zum Werkzeug zu machen: nur http(s),
// keine Adressen im eigenen Netz (Router, Olares-Dienste, Cluster), höchstens
// drei Weiterleitungen, zehn Sekunden, drei Megabyte. Jede Weiterleitung wird
// neu geprüft. (Ein DNS-Rebinding zwischen Prüfung und Abruf bleibt
// theoretisch möglich; der Abruf läuft ohne Sitzung und ohne Antwort-Durchreiche.)
const MAX_BYTES = 3 * 1024 * 1024;
const MAX_REDIRECTS = 3;
export class FetchRefused extends Error {}
function privateV4(ip: string): boolean {
const [a, b] = ip.split(".").map(Number) as [number, number];
return (
a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) ||
(a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || a >= 224
);
}
export function isPrivateAddress(ip: string): boolean {
if (isIP(ip) === 4) return privateV4(ip);
const v6 = ip.toLowerCase();
const mapped = v6.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
if (mapped) return privateV4(mapped[1]!);
return v6 === "::" || v6 === "::1" || v6.startsWith("fc") || v6.startsWith("fd") || v6.startsWith("fe8") || v6.startsWith("fe9") ||
v6.startsWith("fea") || v6.startsWith("feb") || v6.startsWith("ff");
}
async function checkUrl(raw: string): Promise<URL> {
let url: URL;
try {
url = new URL(raw);
} catch {
throw new FetchRefused("url");
}
if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new FetchRefused("url");
// Nur für den Browser-Test (e2e/gerichte.spec.ts): eine einzige, genau benannte
// lokale Quelle. Das Chart setzt die Variable nie.
if (process.env.IMPORT_TEST_ORIGIN && url.origin === process.env.IMPORT_TEST_ORIGIN) return url;
if (url.port && !["80", "443"].includes(url.port)) throw new FetchRefused("port");
const host = url.hostname.replace(/^\[|\]$/g, "");
if (/(^|\.)(local|localhost|internal|svc|cluster\.local)$/i.test(host)) throw new FetchRefused("host");
const addresses = isIP(host) ? [{ address: host }] : await lookup(host, { all: true }).catch(() => []);
if (!addresses.length || addresses.some((a) => isPrivateAddress(a.address))) throw new FetchRefused("host");
return url;
}
/** Holt eine HTML-Seite (oder ein Bild, wenn `accept` es sagt) und gibt Text bzw. Bytes zurück. */
export async function fetchPublic(raw: string, accept: "html" | "image" = "html"): Promise<{ url: string; body: Buffer; type: string }> {
let url = await checkUrl(raw);
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
const res = await fetch(url, {
redirect: "manual",
signal: AbortSignal.timeout(10_000),
headers: {
"user-agent": "Mozilla/5.0 (compatible; Lunch/1.0; recipe import)",
accept: accept === "html" ? "text/html,application/xhtml+xml" : "image/*",
},
}).catch(() => {
throw new FetchRefused("network");
});
if (res.status >= 300 && res.status < 400 && res.headers.get("location")) {
url = await checkUrl(new URL(res.headers.get("location")!, url).toString());
continue;
}
if (!res.ok || !res.body) throw new FetchRefused(`status ${res.status}`);
const type = res.headers.get("content-type") ?? "";
if (accept === "html" ? !/html|xml/.test(type) : !/^image\//.test(type)) throw new FetchRefused("type");
const chunks: Uint8Array[] = [];
let size = 0;
const reader = res.body.getReader();
for (;;) {
const { done, value } = await reader.read();
if (done) break;
size += value.byteLength;
if (size > (accept === "html" ? MAX_BYTES : 15 * 1024 * 1024)) {
await reader.cancel();
throw new FetchRefused("size");
}
chunks.push(value);
}
return { url: url.toString(), body: Buffer.concat(chunks), type };
}
throw new FetchRefused("redirects");
}
+42
View File
@@ -0,0 +1,42 @@
// Zutaten finden, während man tippt: in der eigenen Sprache, mit Synonymen,
// ohne Rücksicht auf Groß-/Kleinschreibung und Akzente („creme“ findet
// „Crème fraîche“). Rein, ohne Datenbank — lib/ingredients.ts lädt die Liste.
export type IngredientEntry = {
id: string;
key: string;
unit: "g" | "ml" | "piece";
category: string;
names: Record<string, string>;
synonyms: string[];
};
export function normalize(text: string): string {
return text
.toLowerCase()
.normalize("NFD")
.replace(/[̀-ͯ]/g, "")
.replace(/ß/g, "ss")
.replace(/[^a-z0-9]+/g, " ")
.trim();
}
/** Beste Treffer zuerst: Name beginnt mit … > Wort im Namen beginnt mit … > Name enthält … > Synonym. */
export function searchIngredients(list: IngredientEntry[], query: string, locale: string, limit = 8): IngredientEntry[] {
const q = normalize(query);
if (!q) return [];
const scored: { entry: IngredientEntry; score: number }[] = [];
for (const entry of list) {
const name = normalize(entry.names[locale] ?? entry.names.en ?? "");
let score = 0;
if (name === q) score = 100;
else if (name.startsWith(q)) score = 80;
else if (name.split(" ").some((w) => w.startsWith(q))) score = 60;
else if (name.includes(q)) score = 40;
else if (entry.synonyms.some((s) => normalize(s).startsWith(q))) score = 30;
else if (entry.synonyms.some((s) => normalize(s).includes(q))) score = 20;
else if (Object.values(entry.names).some((n) => normalize(n).startsWith(q))) score = 10;
if (score) scored.push({ entry, score: score - name.length / 100 });
}
return scored.sort((a, b) => b.score - a.score).slice(0, limit).map((s) => s.entry);
}
+23
View File
@@ -0,0 +1,23 @@
import "server-only";
import { pool } from "@/lib/db";
import type { IngredientEntry } from "./ingredient-search";
// Die kanonischen Zutaten sind global und ändern sich nur beim Einspielen
// (Neustart). Einmal laden, im Speicher halten.
let cache: Promise<IngredientEntry[]> | null = null;
export function allIngredients(): Promise<IngredientEntry[]> {
cache ??= pool
.query("select id, key, default_unit as unit, category, names, synonyms from ingredients order by key")
.then((r) => r.rows as IngredientEntry[])
.catch((error) => {
cache = null;
throw error;
});
return cache;
}
export async function ingredientName(id: string, locale: string): Promise<string> {
const entry = (await allIngredients()).find((i) => i.id === id);
return entry?.names[locale] ?? entry?.names.en ?? "";
}
+54
View File
@@ -0,0 +1,54 @@
import "server-only";
import { createHash } from "node:crypto";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import sharp from "sharp";
// Fotos der Gerichte liegen unter /app/data/fotos/<haushalt>/ — dort
// überleben sie eine Deinstallation (die Datenbank nicht). Ausgeliefert nur
// über /api/fotos/<gericht> mit Sitzung und Zeilensicherheit. Jedes Foto wird
// auf höchstens 1600 px verkleinert und als WebP gespeichert; Metadaten (GPS
// des Handys) fallen dabei weg.
const MAX_BYTES = 15 * 1024 * 1024;
const ACCEPTED = ["image/jpeg", "image/png", "image/webp", "image/heic", "image/heif"];
function root(): string {
return path.join(process.env.APP_DATA_DIR ?? path.join(process.cwd(), ".data"), "fotos");
}
export class PhotoRejected extends Error {}
/** Speichert ein Foto und gibt den relativen Pfad zurück (Teil der Adresse, mit Prüfsumme). */
export async function storePhoto(householdId: string, dishId: string, file: File): Promise<string> {
if (!ACCEPTED.includes(file.type) || file.size > MAX_BYTES || file.size === 0) throw new PhotoRejected(file.type);
return storePhotoBytes(householdId, dishId, Buffer.from(await file.arrayBuffer()));
}
/** Dasselbe für Bytes, etwa das Bild einer importierten Rezeptseite. */
export async function storePhotoBytes(householdId: string, dishId: string, input: Buffer): Promise<string> {
if (input.byteLength === 0 || input.byteLength > MAX_BYTES) throw new PhotoRejected("size");
let output: Buffer;
try {
output = await sharp(input).rotate().resize({ width: 1600, height: 1600, fit: "inside", withoutEnlargement: true }).webp({ quality: 80 }).toBuffer();
} catch {
throw new PhotoRejected("decode");
}
const hash = createHash("sha256").update(output).digest("hex").slice(0, 16);
const relative = path.join(householdId, `${dishId}-${hash}.webp`);
await mkdir(path.join(root(), householdId), { recursive: true, mode: 0o700 });
await writeFile(path.join(root(), relative), output, { mode: 0o600 });
return relative;
}
export async function readPhoto(relative: string): Promise<Buffer> {
const full = path.join(root(), relative);
if (!full.startsWith(root() + path.sep)) throw new Error("bad path");
return readFile(full);
}
export async function removePhoto(relative: string | null): Promise<void> {
if (!relative) return;
const full = path.join(root(), relative);
if (full.startsWith(root() + path.sep)) await rm(full, { force: true });
}
+195
View File
@@ -0,0 +1,195 @@
// Rezept aus einer Webseite lesen — ohne KI, wo es geht (Konzept, „Technik“):
// Die meisten Rezeptseiten tragen schema.org/Recipe als JSON-LD. Hier steht
// nur das Lesen und Zerlegen, rein und testbar; das Holen der Seite macht
// lib/fetch-safe.ts, das Zuordnen der Zutaten lib/ingredient-search.ts.
import { searchIngredients, type IngredientEntry } from "./ingredient-search";
import { parseNumber, toBase, type InputUnit } from "./units";
export type RawRecipe = {
title: string;
yield: number | null;
totalMinutes: number | null;
ingredients: string[];
steps: string[];
image: string | null;
};
type Json = Record<string, unknown>;
function decodeEntities(text: string): string {
return text
.replace(/&nbsp;/g, " ")
.replace(/&amp;/g, "&")
.replace(/&quot;/g, '"')
.replace(/&#0?39;|&apos;/g, "'")
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">")
.replace(/&#(\d+);/g, (_, n) => String.fromCodePoint(Number(n)));
}
const clean = (text: unknown) =>
typeof text === "string" ? decodeEntities(text.replace(/<[^>]*>/g, " ")).replace(/\s+/g, " ").trim() : "";
function isRecipe(node: unknown): node is Json {
if (!node || typeof node !== "object") return false;
const type = (node as Json)["@type"];
return type === "Recipe" || (Array.isArray(type) && type.includes("Recipe"));
}
function findRecipe(node: unknown): Json | null {
if (Array.isArray(node)) {
for (const n of node) {
const r = findRecipe(n);
if (r) return r;
}
return null;
}
if (!node || typeof node !== "object") return null;
if (isRecipe(node)) return node;
const graph = (node as Json)["@graph"];
return graph ? findRecipe(graph) : null;
}
/** ISO-8601-Dauer („PT1H30M“) in Minuten. */
export function durationMinutes(value: unknown): number | null {
if (typeof value !== "string") return null;
const m = value.match(/^P(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:\d+S)?)?$/i);
if (!m) return null;
const total = Number(m[1] ?? 0) * 1440 + Number(m[2] ?? 0) * 60 + Number(m[3] ?? 0);
return total > 0 ? total : null;
}
function yieldNumber(value: unknown): number | null {
const first = Array.isArray(value) ? value[0] : value;
if (typeof first === "number") return first > 0 ? Math.round(first) : null;
const m = typeof first === "string" ? first.match(/\d+/) : null;
return m ? Math.min(30, Number(m[0])) || null : null;
}
function instructionTexts(value: unknown): string[] {
if (typeof value === "string") {
return value
.split(/\n+|(?<=\.)\s+(?=[A-ZÄÖÜ])/)
.map(clean)
.filter(Boolean);
}
if (Array.isArray(value)) return value.flatMap(instructionTexts);
if (value && typeof value === "object") {
const node = value as Json;
if (node.itemListElement) return instructionTexts(node.itemListElement); // HowToSection
return [clean(node.text ?? node.name)].filter(Boolean);
}
return [];
}
function imageUrl(value: unknown): string | null {
if (typeof value === "string") return value;
if (Array.isArray(value)) return imageUrl(value[0]);
if (value && typeof value === "object") return imageUrl((value as Json).url);
return null;
}
/** Das erste Recipe aus den JSON-LD-Blöcken einer Seite, oder null. */
export function extractRecipe(html: string): RawRecipe | null {
const blocks = [...html.matchAll(/<script[^>]*type=["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi)];
for (const [, body] of blocks) {
let data: unknown;
try {
data = JSON.parse(body!.trim());
} catch {
continue;
}
const recipe = findRecipe(data);
if (!recipe) continue;
const ingredients = (Array.isArray(recipe.recipeIngredient) ? recipe.recipeIngredient : []).map(clean).filter(Boolean);
return {
title: clean(recipe.name).slice(0, 120),
yield: yieldNumber(recipe.recipeYield),
totalMinutes: durationMinutes(recipe.totalTime) ?? durationMinutes(recipe.cookTime),
ingredients,
steps: instructionTexts(recipe.recipeInstructions).slice(0, 40),
image: imageUrl(recipe.image),
};
}
return null;
}
// Mengenwörter in vier Sprachen → Eingabeeinheit (lib/units.ts).
const UNIT_WORDS: [RegExp, InputUnit, number?][] = [
[/^(kg|kilo(gramm)?s?)$/i, "kg"],
[/^(g|gr|gramm|grams?|gramos?|grammes?)$/i, "g"],
[/^(l|liter|litres?|liters?|litros?)$/i, "l"],
[/^(ml|milliliter|millilitres?)$/i, "ml"],
[/^(cl)$/i, "cl"],
[/^(el|essl[öo]ffel|tbsp|tablespoons?|cs|c\.\s?à\s?s\.?|cucharadas?)$/i, "tbsp"],
[/^(tl|teel[öo]ffel|tsp|teaspoons?|cc|c\.\s?à\s?c\.?|cucharaditas?)$/i, "tsp"],
[/^(prisen?|pinch(es)?|pinc[ée]es?|pizcas?)$/i, "pinch"],
[/^(cups?|tassen?|tazas?)$/i, "cup"],
[/^(oz|ounces?)$/i, "g", 28.35],
[/^(lbs?|pounds?)$/i, "g", 453.6],
[/^(st(ü|ue)ck|stk\.?|pieces?|pi[eè]ces?|unidad(es)?|zehen?|cloves?|gousses?|dientes?|bund|bunch(es)?|bouquets?|manojos?|dosen?|cans?|tins?|bo[iî]tes?|latas?|scheiben?|slices?|tranches?|rebanadas?)$/i, "piece"],
];
export type ParsedLine = { raw: string; qty: number | null; unit: InputUnit | null; factor: number; name: string };
/** „500 g Rinderhackfleisch“ → Menge, Einheit, Name. „Salz und Pfeffer“ → nur Name. */
export function parseIngredientLine(raw: string): ParsedLine {
let rest = raw.replace(/\(.*?\)/g, " ").replace(/\s+/g, " ").trim();
let qty: number | null = null;
const num = rest.match(
/^(\d+\s+\d+\/\d+|\d+\s*[¼½¾⅓⅔]|\d+(?:[.,]\d+)?|\d+\/\d+|[¼½¾⅓⅔])(?:\s*(?:-|–|bis)\s*\d+(?:[.,]\d+)?)?\s*/,
);
if (num) {
qty = parseNumber(num[1]!.replace(/(\d)\s+([¼½¾⅓⅔])/, "$1$2"));
rest = rest.slice(num[0].length);
}
let unit: InputUnit | null = null;
let factor = 1;
const word = rest.match(/^([^\s\d]+\.?)\s+/);
if (word) {
const w = word[1]!.replace(/\.$/, "");
const hit = UNIT_WORDS.find(([re]) => re.test(w));
if (hit) {
unit = hit[1];
factor = hit[2] ?? 1;
rest = rest.slice(word[0].length);
}
} else {
const glued = rest.match(/^(kg|g|ml|l|cl)\b\s*/i); // „500g Mehl“ nach der Zahl
if (glued) {
unit = glued[1]!.toLowerCase() as InputUnit;
rest = rest.slice(glued[0].length);
}
}
const name = rest.replace(/^(of|de|d'|von)\s+/i, "").replace(/,.*$/, "").trim();
return { raw, qty, unit: qty !== null && !unit ? "piece" : unit, factor, name };
}
export type MatchedLine = {
raw: string;
ingredient: { id: string; name: string; unit: "g" | "ml" | "piece" } | null;
qty: number | null;
unit: InputUnit | null;
note: string | null;
};
/**
* Zeilen den kanonischen Zutaten zuordnen. Passt die Einheit nicht zur Zutat
* (z. B. „1 Becher Sahne“), bleibt die Menge leer — die Person trägt sie ein.
*/
export function matchLines(lines: string[], list: IngredientEntry[], locale: string): MatchedLine[] {
return lines.map((raw) => {
const p = parseIngredientLine(raw);
const hit = p.name ? searchIngredients(list, p.name, locale, 1)[0] ?? searchIngredients(list, p.name.split(" ").at(-1) ?? "", locale, 1)[0] : undefined;
if (!hit) return { raw, ingredient: null, qty: null, unit: null, note: null };
const ingredient = { id: hit.id, name: hit.names[locale] ?? hit.names.en ?? "", unit: hit.unit };
let qty = p.qty !== null ? p.qty * p.factor : null;
let unit = p.unit;
if (qty !== null && unit && toBase(qty, unit, hit.unit) === null) {
qty = null;
unit = null;
}
return { raw, ingredient, qty, unit: unit ?? hit.unit, note: qty === null ? raw : null };
});
}
+97
View File
@@ -0,0 +1,97 @@
// Mengen: gespeichert immer in Basiseinheiten pro Portion (g, ml, Stück —
// CLAUDE.md, Regel 2). Hier und nur hier wird umgerechnet: hochrechnen,
// lesbar anzeigen, Eingaben aus Küchenmaßen in Basiseinheiten bringen.
export type BaseUnit = "g" | "ml" | "piece";
/** Maße, die man tippt oder in Rezepten liest. */
export type InputUnit = BaseUnit | "kg" | "l" | "cl" | "tbsp" | "tsp" | "pinch" | "cup";
/** Hochrechnen: Menge pro Portion × Portionen. */
export function scale(qtyPerPortion: number, portions: number): number {
return qtyPerPortion * portions;
}
// Küchenmaße in Basiseinheiten. Löffel und Tassen sind Volumen; für feste
// Zutaten (Einheit g) gilt eine mittlere Dichte — genau genug für ein
// Familienrezept, und die Planerin sieht und korrigiert die Menge.
const VOLUME_ML: Partial<Record<InputUnit, number>> = { ml: 1, cl: 10, l: 1000, tbsp: 15, tsp: 5, cup: 240, pinch: 0.5 };
const SOLID_G: Partial<Record<InputUnit, number>> = { g: 1, kg: 1000, tbsp: 12, tsp: 4, cup: 150, pinch: 0.5 };
/**
* Eingabe in die Basiseinheit der Zutat bringen. Gibt null zurück, wenn die
* Maße nicht zusammenpassen (z. B. „200 g“ Eier) — dann fragt die Oberfläche nach.
*/
export function toBase(qty: number, unit: InputUnit, base: BaseUnit): number | null {
if (!Number.isFinite(qty) || qty < 0) return null;
if (base === "piece") return unit === "piece" ? qty : null;
if (unit === "piece") return null;
if (base === "ml") {
const f = VOLUME_ML[unit] ?? (unit === "g" ? 1 : unit === "kg" ? 1000 : undefined); // g ≈ ml bei Flüssigem
return f === undefined ? null : qty * f;
}
const f = SOLID_G[unit] ?? (unit === "ml" ? 1 : unit === "l" ? 1000 : unit === "cl" ? 10 : undefined);
return f === undefined ? null : qty * f;
}
const FRACTIONS: [number, string][] = [
[0.25, "¼"],
[1 / 3, "⅓"],
[0.5, "½"],
[2 / 3, "⅔"],
[0.75, "¾"],
];
/** Stückzahlen in Küchenbrüchen: 0,5 → ½, 1,25 → 1¼; sonst auf eine Stelle. */
function pieces(qty: number, locale: string): string {
const whole = Math.floor(qty + 1e-9);
const rest = qty - whole;
if (rest < 0.05) return String(whole || (qty > 0 ? "<1" : "0"));
if (rest > 0.95) return String(whole + 1);
for (const [value, glyph] of FRACTIONS) {
if (Math.abs(rest - value) < 0.05) return whole ? `${whole}${glyph}` : glyph;
}
return new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).format(qty);
}
/** Auf eine Größe runden, die man in der Küche abwiegt. */
function roundMeasure(value: number): number {
if (value < 5) return Math.round(value * 2) / 2;
if (value < 50) return Math.round(value);
if (value < 250) return Math.round(value / 5) * 5;
return Math.round(value / 10) * 10;
}
export type Formatted = { amount: string; unit: string };
/**
* Für die Anzeige: 1500 g → 1,5 kg, 250 ml → 250 ml, 0,5 Stück → ½.
* `unit` ist ein kurzes Zeichen ("g", "kg", "ml", "l") oder leer bei Stück —
* das Wort für Stück liefert die Oberfläche selbst (Plural je Sprache).
*/
export function formatQuantity(qty: number, unit: BaseUnit, locale = "de"): Formatted {
const nf = (v: number, digits: number) => new Intl.NumberFormat(locale, { maximumFractionDigits: digits }).format(v);
if (unit === "piece") return { amount: pieces(qty, locale), unit: "" };
const rounded = roundMeasure(qty);
if (rounded >= 1000) return { amount: nf(Math.round(rounded / 100) / 10, 1), unit: unit === "g" ? "kg" : "l" };
return { amount: nf(rounded, 1), unit };
}
/** Für die Einkaufsliste: Stück immer aufrunden (½ Zwiebel kauft man nicht). */
export function shoppingQuantity(qty: number, unit: BaseUnit): number {
return unit === "piece" ? Math.ceil(qty - 1e-9) : qty;
}
/** Deutsche und englische Zahlen lesen: „1,5“, „1.5“, „1 1/2“, „½“. */
export function parseNumber(text: string): number | null {
const t = text.trim().replace(/\s+/g, " ");
const glyph: Record<string, number> = { "¼": 0.25, "½": 0.5, "¾": 0.75, "⅓": 1 / 3, "⅔": 2 / 3 };
const m = t.match(/^(\d+)?\s*([¼½¾⅓⅔])$/);
if (m) return Number(m[1] ?? 0) + glyph[m[2]!]!;
const mixed = t.match(/^(\d+) (\d+)\/(\d+)$/);
if (mixed) return Number(mixed[1]) + Number(mixed[2]) / Number(mixed[3]);
const frac = t.match(/^(\d+)\/(\d+)$/);
if (frac) return Number(frac[1]) / Number(frac[2]);
const n = Number(t.replace(",", "."));
return Number.isFinite(n) && t !== "" ? n : null;
}
+130 -1
View File
@@ -106,6 +106,135 @@
},
"nav": {
"today": "Heute",
"more": "Mehr"
"more": "Mehr",
"dishes": "Gerichte"
},
"dishes": {
"eyebrow": "Euer Pool",
"title": "Gerichte",
"pool": "Pool",
"trial": "Ausprobieren",
"emptyTitle": "Noch keine Gerichte",
"emptyText": "Übernimm ein paar Klassiker oder leg dein erstes eigenes Gericht an. Nach fünf Gerichten kann die Familie wünschen.",
"emptyTrial": "Noch nichts zum Ausprobieren. Markiere ein neues Gericht als „Ausprobieren“, dann taucht es hier auf.",
"add": "Gericht hinzufügen",
"addTitle": "Gericht hinzufügen",
"addEyebrow": "Neu im Pool",
"addStarters": "Klassiker übernehmen",
"addStartersText": "15 Familiengerichte mit Zutaten und Schritten, fertig zum Wünschen.",
"addManual": "Selbst anlegen",
"addManualText": "Titel, Zutaten und Schritte von Hand.",
"addLink": "Rezept-Link einfügen",
"addPhoto": "Kochbuch fotografieren",
"soon": "kommt bald",
"minutes": "{n} Min.",
"bases": {
"pasta": "Nudeln",
"rice": "Reis",
"potato": "Kartoffeln",
"bread": "Brot",
"grain": "Getreide",
"none": "ohne Beilage"
},
"tags": {
"quick": "schnell",
"vegetarian": "vegetarisch",
"vegan": "vegan",
"kids_favorite": "Kinderliebling",
"fish": "Fisch",
"oven": "Ofen",
"one_pot": "ein Topf",
"soup": "Suppe",
"sweet": "süß"
},
"starters": {
"eyebrow": "Klassiker",
"title": "Gerichte übernehmen",
"intro": "Tippe an, was ihr gern esst. Alles lässt sich danach ändern.",
"adopt": "{n, plural, =0 {Gerichte auswählen} one {Ein Gericht übernehmen} other {# Gerichte übernehmen}}",
"inPool": "im Pool",
"selected": "ausgewählt"
},
"detail": {
"ingredients": "Zutaten",
"steps": "Zubereitung",
"portions": "Portionen",
"fewer": "Eine Portion weniger",
"more": "Eine Portion mehr",
"staple": "Vorrat",
"edit": "Bearbeiten",
"remove": "Entfernen",
"removed": "„{title}“ ist aus dem Pool entfernt.",
"undo": "Rückgängig",
"photo": "Foto aufnehmen",
"photoChange": "Foto ändern",
"photoError": "Das Foto ließ sich nicht lesen. Nimm ein JPEG, PNG oder HEIC bis 15 MB.",
"stepTimer": "{n} Min.",
"source": "Quelle",
"pieces": "{n, plural, one {Stück} other {Stück}}"
},
"form": {
"newTitle": "Neues Gericht",
"editTitle": "Gericht bearbeiten",
"title": "Titel",
"titlePlaceholder": "z. B. Gemüsecurry",
"portions": "Für wie viele Portionen sind die Mengen?",
"base": "Beilage",
"baseNone": "keine Angabe",
"effort": "Zeit in Minuten",
"tags": "Eigenschaften",
"trial": "Erst mal ausprobieren",
"trialHint": "Steht dann unter „Ausprobieren“ statt im Pool.",
"ingredients": "Zutaten",
"searchIngredient": "Zutat suchen",
"amount": "Menge",
"unit": "Einheit",
"note": "Hinweis",
"notePlaceholder": "z. B. fein gewürfelt",
"removeIngredient": "Zutat entfernen",
"noHits": "Keine Zutat gefunden.",
"steps": "Schritte",
"step": "Schritt {n}",
"timer": "Timer (Min.)",
"addStep": "Schritt hinzufügen",
"removeStep": "Schritt entfernen",
"moveUp": "Nach oben",
"moveDown": "Nach unten",
"save": "Speichern",
"saving": "Speichert …",
"cancel": "Abbrechen",
"units": {
"g": "g",
"kg": "kg",
"ml": "ml",
"l": "l",
"piece": "Stück",
"tbsp": "EL",
"tsp": "TL",
"pinch": "Prise"
},
"errors": {
"invalid": "Bitte gib einen Titel an und prüfe die Mengen.",
"amount": "Eine Menge passt nicht zur Zutat (z. B. Gramm bei Stück).",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal.",
"missingAmount": "Bei einer Zutat fehlt die Menge. Trag sie ein oder entferne die Zeile."
},
"unmatched": "Diese Zeilen konnten wir keiner Zutat zuordnen. Füge sie bei Bedarf selbst hinzu:"
},
"addLinkText": "Wir lesen Zutaten und Schritte von der Rezeptseite.",
"link": {
"title": "Rezept-Link einfügen",
"label": "Adresse der Rezeptseite",
"hint": "Funktioniert mit den meisten Rezeptportalen und Food-Blogs.",
"load": "Rezept holen",
"loading": "Liest die Seite …",
"check": "Prüf die Mengen und Zutaten, bevor du speicherst. Das Gericht landet erst mal unter „Ausprobieren“.",
"errors": {
"url": "Diese Adresse können wir nicht öffnen. Bitte gib einen öffentlichen Link (https://…) an.",
"unreachable": "Die Seite war nicht erreichbar. Versuch es später noch einmal.",
"noRecipe": "Auf dieser Seite haben wir kein Rezept gefunden. Leg das Gericht lieber von Hand an.",
"unknown": "Das hat nicht geklappt. Bitte versuch es noch einmal."
}
}
}
}
+130 -1
View File
@@ -106,6 +106,135 @@
},
"nav": {
"today": "Today",
"more": "More"
"more": "More",
"dishes": "Dishes"
},
"dishes": {
"eyebrow": "Your pool",
"title": "Dishes",
"pool": "Pool",
"trial": "To try",
"emptyTitle": "No dishes yet",
"emptyText": "Take over a few classics or add your first own dish. Once there are five, the family can start wishing.",
"emptyTrial": "Nothing to try yet. Mark a new dish as \"to try\" and it shows up here.",
"add": "Add dish",
"addTitle": "Add a dish",
"addEyebrow": "New in the pool",
"addStarters": "Take over classics",
"addStartersText": "15 family dishes with ingredients and steps, ready to wish for.",
"addManual": "Add by hand",
"addManualText": "Title, ingredients and steps typed in.",
"addLink": "Paste a recipe link",
"addPhoto": "Photograph a cookbook",
"soon": "coming soon",
"minutes": "{n} min",
"bases": {
"pasta": "Pasta",
"rice": "Rice",
"potato": "Potatoes",
"bread": "Bread",
"grain": "Grains",
"none": "no side"
},
"tags": {
"quick": "quick",
"vegetarian": "vegetarian",
"vegan": "vegan",
"kids_favorite": "kids' favourite",
"fish": "fish",
"oven": "oven",
"one_pot": "one pot",
"soup": "soup",
"sweet": "sweet"
},
"starters": {
"eyebrow": "Classics",
"title": "Take over dishes",
"intro": "Tap what you like to eat. You can change everything afterwards.",
"adopt": "{n, plural, =0 {Choose dishes} one {Take over one dish} other {Take over # dishes}}",
"inPool": "in pool",
"selected": "selected"
},
"detail": {
"ingredients": "Ingredients",
"steps": "Method",
"portions": "Portions",
"fewer": "One portion less",
"more": "One portion more",
"staple": "pantry",
"edit": "Edit",
"remove": "Remove",
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
},
"form": {
"newTitle": "New dish",
"editTitle": "Edit dish",
"title": "Title",
"titlePlaceholder": "e.g. Vegetable curry",
"portions": "How many portions are the amounts for?",
"base": "Side",
"baseNone": "not set",
"effort": "Time in minutes",
"tags": "Properties",
"trial": "Just trying it",
"trialHint": "Shows under \"To try\" instead of the pool.",
"ingredients": "Ingredients",
"searchIngredient": "Search ingredient",
"amount": "Amount",
"unit": "Unit",
"note": "Note",
"notePlaceholder": "e.g. finely chopped",
"removeIngredient": "Remove ingredient",
"noHits": "No ingredient found.",
"steps": "Steps",
"step": "Step {n}",
"timer": "Timer (min)",
"addStep": "Add step",
"removeStep": "Remove step",
"moveUp": "Move up",
"moveDown": "Move down",
"save": "Save",
"saving": "Saving …",
"cancel": "Cancel",
"units": {
"g": "g",
"kg": "kg",
"ml": "ml",
"l": "l",
"piece": "pcs",
"tbsp": "tbsp",
"tsp": "tsp",
"pinch": "pinch"
},
"errors": {
"invalid": "Please give a title and check the amounts.",
"amount": "An amount doesn't fit the ingredient (e.g. grams for pieces).",
"unknown": "That didn't work. Please try again.",
"missingAmount": "An ingredient has no amount. Enter it or remove the row."
},
"unmatched": "We could not match these lines to an ingredient. Add them yourself if needed:"
},
"addLinkText": "We read ingredients and steps from the recipe page.",
"link": {
"title": "Paste a recipe link",
"label": "Address of the recipe page",
"hint": "Works with most recipe sites and food blogs.",
"load": "Get recipe",
"loading": "Reading the page …",
"check": "Check amounts and ingredients before you save. The dish starts under “Try out”.",
"errors": {
"url": "We cannot open this address. Please use a public link (https://…).",
"unreachable": "The page could not be reached. Please try again later.",
"noRecipe": "We found no recipe on this page. Better add the dish by hand.",
"unknown": "That did not work. Please try again."
}
}
}
}
+130 -1
View File
@@ -106,6 +106,135 @@
},
"nav": {
"today": "Today",
"more": "More"
"more": "More",
"dishes": "Dishes"
},
"dishes": {
"eyebrow": "Your pool",
"title": "Dishes",
"pool": "Pool",
"trial": "To try",
"emptyTitle": "No dishes yet",
"emptyText": "Take over a few classics or add your first own dish. Once there are five, the family can start wishing.",
"emptyTrial": "Nothing to try yet. Mark a new dish as \"to try\" and it shows up here.",
"add": "Add dish",
"addTitle": "Add a dish",
"addEyebrow": "New in the pool",
"addStarters": "Take over classics",
"addStartersText": "15 family dishes with ingredients and steps, ready to wish for.",
"addManual": "Add by hand",
"addManualText": "Title, ingredients and steps typed in.",
"addLink": "Paste a recipe link",
"addPhoto": "Photograph a cookbook",
"soon": "coming soon",
"minutes": "{n} min",
"bases": {
"pasta": "Pasta",
"rice": "Rice",
"potato": "Potatoes",
"bread": "Bread",
"grain": "Grains",
"none": "no side"
},
"tags": {
"quick": "quick",
"vegetarian": "vegetarian",
"vegan": "vegan",
"kids_favorite": "kids' favourite",
"fish": "fish",
"oven": "oven",
"one_pot": "one pot",
"soup": "soup",
"sweet": "sweet"
},
"starters": {
"eyebrow": "Classics",
"title": "Take over dishes",
"intro": "Tap what you like to eat. You can change everything afterwards.",
"adopt": "{n, plural, =0 {Choose dishes} one {Take over one dish} other {Take over # dishes}}",
"inPool": "in pool",
"selected": "selected"
},
"detail": {
"ingredients": "Ingredients",
"steps": "Method",
"portions": "Portions",
"fewer": "One portion less",
"more": "One portion more",
"staple": "pantry",
"edit": "Edit",
"remove": "Remove",
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
},
"form": {
"newTitle": "New dish",
"editTitle": "Edit dish",
"title": "Title",
"titlePlaceholder": "e.g. Vegetable curry",
"portions": "How many portions are the amounts for?",
"base": "Side",
"baseNone": "not set",
"effort": "Time in minutes",
"tags": "Properties",
"trial": "Just trying it",
"trialHint": "Shows under \"To try\" instead of the pool.",
"ingredients": "Ingredients",
"searchIngredient": "Search ingredient",
"amount": "Amount",
"unit": "Unit",
"note": "Note",
"notePlaceholder": "e.g. finely chopped",
"removeIngredient": "Remove ingredient",
"noHits": "No ingredient found.",
"steps": "Steps",
"step": "Step {n}",
"timer": "Timer (min)",
"addStep": "Add step",
"removeStep": "Remove step",
"moveUp": "Move up",
"moveDown": "Move down",
"save": "Save",
"saving": "Saving …",
"cancel": "Cancel",
"units": {
"g": "g",
"kg": "kg",
"ml": "ml",
"l": "l",
"piece": "pcs",
"tbsp": "tbsp",
"tsp": "tsp",
"pinch": "pinch"
},
"errors": {
"invalid": "Please give a title and check the amounts.",
"amount": "An amount doesn't fit the ingredient (e.g. grams for pieces).",
"unknown": "That didn't work. Please try again.",
"missingAmount": "A un ingrediente le falta la cantidad. Escríbela o quita la fila."
},
"unmatched": "No pudimos asignar estas líneas a un ingrediente. Añádelas tú si hace falta:"
},
"addLinkText": "Leemos los ingredientes y los pasos de la página de la receta.",
"link": {
"title": "Pegar enlace de receta",
"label": "Dirección de la página de la receta",
"hint": "Funciona con la mayoría de webs de recetas y blogs de cocina.",
"load": "Obtener receta",
"loading": "Leyendo la página …",
"check": "Check amounts and ingredients before you save. The dish starts under “Try out”.",
"errors": {
"url": "No podemos abrir esta dirección. Usa un enlace público (https://…).",
"unreachable": "No se pudo acceder a la página. Inténtalo más tarde.",
"noRecipe": "No encontramos ninguna receta en esta página. Mejor añade el plato a mano.",
"unknown": "No ha funcionado. Inténtalo de nuevo."
}
}
}
}
+130 -1
View File
@@ -106,6 +106,135 @@
},
"nav": {
"today": "Today",
"more": "More"
"more": "More",
"dishes": "Dishes"
},
"dishes": {
"eyebrow": "Your pool",
"title": "Dishes",
"pool": "Pool",
"trial": "To try",
"emptyTitle": "No dishes yet",
"emptyText": "Take over a few classics or add your first own dish. Once there are five, the family can start wishing.",
"emptyTrial": "Nothing to try yet. Mark a new dish as \"to try\" and it shows up here.",
"add": "Add dish",
"addTitle": "Add a dish",
"addEyebrow": "New in the pool",
"addStarters": "Take over classics",
"addStartersText": "15 family dishes with ingredients and steps, ready to wish for.",
"addManual": "Add by hand",
"addManualText": "Title, ingredients and steps typed in.",
"addLink": "Paste a recipe link",
"addPhoto": "Photograph a cookbook",
"soon": "coming soon",
"minutes": "{n} min",
"bases": {
"pasta": "Pasta",
"rice": "Rice",
"potato": "Potatoes",
"bread": "Bread",
"grain": "Grains",
"none": "no side"
},
"tags": {
"quick": "quick",
"vegetarian": "vegetarian",
"vegan": "vegan",
"kids_favorite": "kids' favourite",
"fish": "fish",
"oven": "oven",
"one_pot": "one pot",
"soup": "soup",
"sweet": "sweet"
},
"starters": {
"eyebrow": "Classics",
"title": "Take over dishes",
"intro": "Tap what you like to eat. You can change everything afterwards.",
"adopt": "{n, plural, =0 {Choose dishes} one {Take over one dish} other {Take over # dishes}}",
"inPool": "in pool",
"selected": "selected"
},
"detail": {
"ingredients": "Ingredients",
"steps": "Method",
"portions": "Portions",
"fewer": "One portion less",
"more": "One portion more",
"staple": "pantry",
"edit": "Edit",
"remove": "Remove",
"removed": "\"{title}\" was removed from the pool.",
"undo": "Undo",
"photo": "Take a photo",
"photoChange": "Change photo",
"photoError": "The photo couldn't be read. Use a JPEG, PNG or HEIC up to 15 MB.",
"stepTimer": "{n} min",
"source": "Source",
"pieces": "{n, plural, one {piece} other {pieces}}"
},
"form": {
"newTitle": "New dish",
"editTitle": "Edit dish",
"title": "Title",
"titlePlaceholder": "e.g. Vegetable curry",
"portions": "How many portions are the amounts for?",
"base": "Side",
"baseNone": "not set",
"effort": "Time in minutes",
"tags": "Properties",
"trial": "Just trying it",
"trialHint": "Shows under \"To try\" instead of the pool.",
"ingredients": "Ingredients",
"searchIngredient": "Search ingredient",
"amount": "Amount",
"unit": "Unit",
"note": "Note",
"notePlaceholder": "e.g. finely chopped",
"removeIngredient": "Remove ingredient",
"noHits": "No ingredient found.",
"steps": "Steps",
"step": "Step {n}",
"timer": "Timer (min)",
"addStep": "Add step",
"removeStep": "Remove step",
"moveUp": "Move up",
"moveDown": "Move down",
"save": "Save",
"saving": "Saving …",
"cancel": "Cancel",
"units": {
"g": "g",
"kg": "kg",
"ml": "ml",
"l": "l",
"piece": "pcs",
"tbsp": "tbsp",
"tsp": "tsp",
"pinch": "pinch"
},
"errors": {
"invalid": "Please give a title and check the amounts.",
"amount": "An amount doesn't fit the ingredient (e.g. grams for pieces).",
"unknown": "That didn't work. Please try again.",
"missingAmount": "Il manque la quantité d’un ingrédient. Indique-la ou supprime la ligne."
},
"unmatched": "Nous n’avons pas pu associer ces lignes à un ingrédient. Ajoute-les toi-même si besoin :"
},
"addLinkText": "Nous lisons les ingrédients et les étapes sur la page de la recette.",
"link": {
"title": "Coller un lien de recette",
"label": "Adresse de la page de recette",
"hint": "Fonctionne avec la plupart des sites de recettes et blogs culinaires.",
"load": "Récupérer la recette",
"loading": "Lecture de la page …",
"check": "Check amounts and ingredients before you save. The dish starts under “Try out”.",
"errors": {
"url": "Nous ne pouvons pas ouvrir cette adresse. Utilise un lien public (https://…).",
"unreachable": "La page est injoignable. Réessaie plus tard.",
"noRecipe": "Aucune recette trouvée sur cette page. Ajoute plutôt le plat à la main.",
"unknown": "Cela n’a pas marché. Réessaie."
}
}
}
}
+2 -2
View File
@@ -2,5 +2,5 @@ apiVersion: v2
name: lunch
description: Was gibt's? — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste
type: application
version: 26.11.5 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.5" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
version: 26.11.6 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
appVersion: "26.11.6" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
+2 -2
View File
@@ -21,7 +21,7 @@ metadata:
title: What's cooking?
description: 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.5
version: 26.11.6
categories:
- Applications
@@ -61,7 +61,7 @@ permission:
appData: true
spec:
versionName: '26.11.5'
versionName: '26.11.6'
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
promoteImage:
+5
View File
@@ -0,0 +1,5 @@
# Dishes: your pool
v26.11.6: A new Dishes tab with the household's pool as photo tiles and a list of dishes to try. Take over family classics with a tap, or add your own dish with ingredients found as you type and steps with timers. Every dish scales its ingredients to the number of portions you choose. Take a photo of your own cooking right from the dish; it is shrunk on the box and its location data removed. Removing a dish can be undone. Paste a link from a recipe site and Lunch fills in title, ingredients, steps and photo for you to check.
## Deutsch
v26.11.6: Ein neuer Reiter Gerichte mit dem Pool des Haushalts als Bildkacheln und einer Liste zum Ausprobieren. Familienklassiker mit einem Tipp übernehmen oder ein eigenes Gericht anlegen, mit Zutaten, die beim Tippen gefunden werden, und Schritten mit Timern. Jedes Gericht rechnet seine Zutaten auf die gewählte Zahl der Portionen um. Fotos vom eigenen Essen direkt am Gericht aufnehmen; die Box verkleinert sie und entfernt die Ortsdaten. Ein entferntes Gericht lässt sich zurückholen. Einen Link von einer Rezeptseite einfügen, und Lunch trägt Titel, Zutaten, Schritte und Foto zum Prüfen ein.
+1 -3
View File
@@ -23,6 +23,7 @@
"react-dom": "19.2.0",
"server-only": "^0.0.1",
"serwist": "^9.5.13",
"sharp": "0.35.5",
"tailwind-merge": "^3.7.0",
"zod": "^4.6.7"
},
@@ -587,7 +588,6 @@
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
"integrity": "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==",
"license": "MIT",
"optional": true,
"engines": {
"node": ">=18"
}
@@ -4523,7 +4523,6 @@
"resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz",
"integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==",
"license": "ISC",
"optional": true,
"bin": {
"semver": "bin/semver.js"
},
@@ -4560,7 +4559,6 @@
"resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz",
"integrity": "sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==",
"license": "Apache-2.0",
"optional": true,
"dependencies": {
"@img/colour": "^1.1.0",
"detect-libc": "^2.1.2",
+1
View File
@@ -27,6 +27,7 @@
"react-dom": "19.2.0",
"server-only": "^0.0.1",
"serwist": "^9.5.13",
"sharp": "0.35.5",
"tailwind-merge": "^3.7.0",
"zod": "^4.6.7"
},
+9 -3
View File
@@ -24,22 +24,28 @@ export default defineConfig({
},
projects: [
{ name: "ablauf", testMatch: /ablauf\.spec\.ts/, use: { ...iphone } },
{
name: "gerichte",
testMatch: /gerichte\.spec\.ts/,
dependencies: ["ablauf"],
use: { ...iphone, storageState: "e2e/.auth/kai.json" },
},
{
name: "iphone-hell",
testMatch: /rundgang\.spec\.ts/,
dependencies: ["ablauf"],
dependencies: ["gerichte"],
use: { ...iphone, colorScheme: "light", storageState: "e2e/.auth/kai.json" },
},
{
name: "iphone-dunkel",
testMatch: /rundgang\.spec\.ts/,
dependencies: ["ablauf"],
dependencies: ["gerichte"],
use: { ...iphone, colorScheme: "dark", storageState: "e2e/.auth/kai.json" },
},
{
name: "desktop",
testMatch: /rundgang\.spec\.ts/,
dependencies: ["ablauf"],
dependencies: ["gerichte"],
use: { ...devices["Desktop Chrome"], viewport: { width: 1280, height: 860 }, storageState: "e2e/.auth/kai.json" },
},
],
+99
View File
@@ -0,0 +1,99 @@
import { randomUUID } from "node:crypto";
import pg from "pg";
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
import { seedHousehold } from "./fixture";
vi.mock("server-only", () => ({}));
// lib/dishes.ts gegen die Testdatenbank: Mengen werden pro Portion in der
// Basiseinheit gespeichert, Unpassendes abgewiesen, Bearbeiten ersetzt,
// Entfernen archiviert — und kein Haushalt sieht die Gerichte des anderen.
const url = process.env.TEST_DATABASE_URL;
describe.skipIf(!url)("dishes", () => {
const client = new pg.Client({ connectionString: url });
const a = randomUUID();
const b = randomUUID();
let member = "";
let lib: typeof import("@/lib/dishes");
const ing: Record<string, string> = {};
async function as<T>(h: string, fn: () => Promise<T>): Promise<T> {
await client.query("begin");
try {
await client.query("select set_config('app.household_id', $1, true)", [h]);
const r = await fn();
await client.query("commit");
return r;
} catch (e) {
await client.query("rollback");
throw e;
}
}
beforeAll(async () => {
process.env.DATABASE_URL = url;
await client.connect();
for (const r of (await client.query("select id, key from ingredients where key in ('ground_beef','olive_oil','egg')")).rows) ing[r.key] = r.id;
lib = await import("@/lib/dishes");
member = (await seedHousehold(client, a, ing.ground_beef!)).member;
await seedHousehold(client, b, ing.ground_beef!);
});
afterAll(async () => {
(await import("@/lib/db")).pool.end();
await client.end();
});
const input = (over: Partial<import("@/lib/dishes").DishInput> = {}) => ({
title: "Hack-Pfanne",
portions: 4,
base: null,
tags: [],
effortMinutes: 20,
isTrial: false,
ingredients: [
{ ingredientId: ing.ground_beef!, qty: 0.5, unit: "kg" as const },
{ ingredientId: ing.olive_oil!, qty: 2, unit: "tbsp" as const },
{ ingredientId: ing.egg!, qty: 2, unit: "piece" as const },
],
steps: [{ text: "Alles anbraten.", timerMinutes: 10 }],
...over,
});
it("stores amounts per portion in the base unit", async () => {
const id = await as(a, () => lib.saveDish(client as never, a, member, input()));
const dish = await as(a, () => lib.getDish(client as never, id, "de"));
expect(dish!.ingredients.map((i) => [i.unit, i.qtyPerPortion])).toEqual([
["g", 125],
["ml", 7.5],
["piece", 0.5],
]);
expect(dish!.steps).toEqual([{ text: "Alles anbraten.", timerSeconds: 600 }]);
});
it("refuses an amount that does not fit the ingredient", async () => {
await expect(
as(a, () => lib.saveDish(client as never, a, member, input({ ingredients: [{ ingredientId: ing.egg!, qty: 200, unit: "g" }] }))),
).rejects.toBeInstanceOf(lib.InvalidAmount);
});
it("editing replaces ingredients and steps; archiving hides and restoring brings back", async () => {
const id = await as(a, () => lib.saveDish(client as never, a, member, input()));
await as(a, () => lib.saveDish(client as never, a, member, input({ title: "Neu", ingredients: [], steps: [] }), id));
const edited = await as(a, () => lib.getDish(client as never, id, "de"));
expect([edited!.title, edited!.ingredients.length, edited!.steps.length]).toEqual(["Neu", 0, 0]);
await as(a, () => lib.setArchived(client as never, id, true));
expect(await as(a, () => lib.getDish(client as never, id, "de"))).toBeNull();
expect((await as(a, () => lib.listDishes(client as never))).some((d) => d.id === id)).toBe(false);
await as(a, () => lib.setArchived(client as never, id, false));
expect((await as(a, () => lib.getDish(client as never, id, "de")))!.title).toBe("Neu");
});
it("another household can neither read nor change the dish", async () => {
const id = await as(a, () => lib.saveDish(client as never, a, member, input()));
expect(await as(b, () => lib.getDish(client as never, id, "de"))).toBeNull();
expect(await as(b, () => lib.setArchived(client as never, id, true))).toBe(false);
await expect(as(b, () => lib.saveDish(client as never, b, member, input(), id))).rejects.toThrow();
});
});
+18
View File
@@ -0,0 +1,18 @@
import { describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
describe("fetch-safe", () => {
it("knows private and special addresses", async () => {
const { isPrivateAddress } = await import("@/lib/fetch-safe");
for (const ip of ["10.1.2.3", "127.0.0.1", "192.168.1.1", "172.20.0.1", "169.254.169.254", "100.64.0.1", "0.0.0.0", "::1", "fd00::1", "fe80::1", "::ffff:10.0.0.1"])
expect([ip, isPrivateAddress(ip)]).toEqual([ip, true]);
for (const ip of ["8.8.8.8", "93.184.216.34", "2606:4700::1111"]) expect([ip, isPrivateAddress(ip)]).toEqual([ip, false]);
});
it("refuses non-http schemes, odd ports, local names and private hosts before any request", async () => {
const { fetchPublic, FetchRefused } = await import("@/lib/fetch-safe");
for (const url of ["file:///etc/passwd", "ftp://example.org/", "http://example.org:8080/", "http://user:pw@example.org/", "http://localhost/", "http://lunch.svc.cluster.local/", "http://127.0.0.1/", "http://[::1]/", "http://192.168.1.10/rezept"])
await expect(fetchPublic(url)).rejects.toBeInstanceOf(FetchRefused);
});
});
+31
View File
@@ -0,0 +1,31 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import { normalize, searchIngredients, type IngredientEntry } from "@/lib/ingredient-search";
const list: IngredientEntry[] = JSON.parse(readFileSync("db/seed/ingredients.json", "utf8")).map(
(i: { key: string; unit: "g"; category: string; names: Record<string, string>; synonyms: string[] }) => ({ ...i, id: i.key }),
);
const keys = (q: string, l = "de") => searchIngredients(list, q, l).map((i) => i.key);
describe("ingredient search", () => {
it("normalizes accents, umlauts and ß", () => {
expect(normalize("Crème fraîche")).toBe("creme fraiche");
expect(normalize("Süßkartoffel")).toBe("susskartoffel");
});
it("finds by the start of the name in the person's language first", () => {
expect(keys("zwieb")[0]).toBe("onion");
expect(keys("onion", "en")[0]).toBe("onion");
expect(keys("oignon", "fr")[0]).toBe("onion");
});
it("finds words inside names and synonyms", () => {
expect(keys("hack")).toContain("ground_beef");
expect(keys("creme")).toContain("creme_fraiche");
});
it("returns nothing for an empty query and at most the limit", () => {
expect(keys("")).toEqual([]);
expect(searchIngredients(list, "e", "de", 5)).toHaveLength(5);
});
});
+61
View File
@@ -0,0 +1,61 @@
import { readFileSync } from "node:fs";
import { describe, expect, it } from "vitest";
import type { IngredientEntry } from "@/lib/ingredient-search";
import { durationMinutes, extractRecipe, matchLines, parseIngredientLine } from "@/lib/recipe-import";
const list: IngredientEntry[] = JSON.parse(readFileSync("db/seed/ingredients.json", "utf8")).map(
(i: IngredientEntry & { key: string }) => ({ ...i, id: i.key }),
);
// Eine Seite wie viele deutsche Rezeptportale: JSON-LD im @graph, Anweisungen als HowToStep.
const page = `<html><head>
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"x"},
{"@type":["Recipe"],"name":"Omas Gulasch &amp; Nudeln","recipeYield":"4 Portionen","totalTime":"PT2H15M",
"image":[{"@type":"ImageObject","url":"https://example.org/gulasch.jpg"}],
"recipeIngredient":["750 g Rindergulasch","2 EL Tomatenmark","3 Zwiebeln, in Ringen","1 Prise Salz","1 Becher Sahne","Salz und Pfeffer"],
"recipeInstructions":[{"@type":"HowToStep","text":"Fleisch scharf anbraten."},{"@type":"HowToSection","name":"Sauce","itemListElement":[{"@type":"HowToStep","text":"Zwiebeln dazu &amp; schmoren."}]}]}]}
</script></head><body></body></html>`;
describe("recipe import", () => {
it("finds the Recipe in JSON-LD, also inside @graph and with @type as an array", () => {
const r = extractRecipe(page)!;
expect(r.title).toBe("Omas Gulasch & Nudeln");
expect(r.yield).toBe(4);
expect(r.totalMinutes).toBe(135);
expect(r.image).toBe("https://example.org/gulasch.jpg");
expect(r.ingredients).toHaveLength(6);
expect(r.steps).toEqual(["Fleisch scharf anbraten.", "Zwiebeln dazu & schmoren."]);
});
it("returns null for a page without a recipe or with broken JSON", () => {
expect(extractRecipe("<html><body>Hallo</body></html>")).toBeNull();
expect(extractRecipe('<script type="application/ld+json">{kaputt</script>')).toBeNull();
});
it("reads ISO durations", () => {
expect(durationMinutes("PT45M")).toBe(45);
expect(durationMinutes("PT1H")).toBe(60);
expect(durationMinutes("P1DT2H")).toBe(1560);
expect(durationMinutes("bald")).toBeNull();
});
it("splits ingredient lines in four languages", () => {
expect(parseIngredientLine("750 g Rindergulasch")).toMatchObject({ qty: 750, unit: "g", name: "Rindergulasch" });
expect(parseIngredientLine("2 EL Tomatenmark")).toMatchObject({ qty: 2, unit: "tbsp", name: "Tomatenmark" });
expect(parseIngredientLine("3 Zwiebeln, in Ringen")).toMatchObject({ qty: 3, unit: "piece", name: "Zwiebeln" });
expect(parseIngredientLine("500g Mehl")).toMatchObject({ qty: 500, unit: "g", name: "Mehl" });
expect(parseIngredientLine("1 ½ tsp ground cumin")).toMatchObject({ qty: 1.5, unit: "tsp", name: "ground cumin" });
expect(parseIngredientLine("1 lb ground beef")).toMatchObject({ qty: 1, unit: "g", factor: 453.6 });
expect(parseIngredientLine("200 g de farine")).toMatchObject({ qty: 200, unit: "g", name: "farine" });
expect(parseIngredientLine("Salz und Pfeffer")).toMatchObject({ qty: null, unit: null });
});
it("matches lines to canonical ingredients and keeps unfitting amounts for the person", () => {
const m = matchLines(["750 g Rindergulasch", "3 Zwiebeln", "1 Becher Sahne", "2 EL Tomatenmark"], list, "de");
expect(m[0]).toMatchObject({ ingredient: { id: "beef_stew" }, qty: 750, unit: "g" });
expect(m[1]).toMatchObject({ ingredient: { id: "onion" }, qty: 3, unit: "piece" });
expect(m[2]!.ingredient?.id).toBe("cream");
expect(m[2]!.qty).toBeNull();
expect(m[3]).toMatchObject({ ingredient: { id: "tomato_paste" }, qty: 2, unit: "tbsp" });
});
});
+54
View File
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { formatQuantity, parseNumber, scale, shoppingQuantity, toBase } from "@/lib/units";
describe("units", () => {
it("scales per-portion amounts", () => {
expect(scale(125, 4)).toBe(500);
expect(scale(0.25, 4)).toBe(1);
});
it("formats weights and volumes the way a kitchen reads them", () => {
expect(formatQuantity(125, "g")).toEqual({ amount: "125", unit: "g" });
expect(formatQuantity(1500, "g")).toEqual({ amount: "1,5", unit: "kg" });
expect(formatQuantity(1000, "ml")).toEqual({ amount: "1", unit: "l" });
expect(formatQuantity(482, "g")).toEqual({ amount: "480", unit: "g" });
expect(formatQuantity(2.3, "g")).toEqual({ amount: "2,5", unit: "g" });
expect(formatQuantity(1500, "g", "en")).toEqual({ amount: "1.5", unit: "kg" });
});
it("shows pieces as kitchen fractions", () => {
expect(formatQuantity(0.5, "piece").amount).toBe("½");
expect(formatQuantity(1.25, "piece").amount).toBe("1¼");
expect(formatQuantity(0.75, "piece").amount).toBe("¾");
expect(formatQuantity(2, "piece").amount).toBe("2");
expect(formatQuantity(1.4, "piece").amount).toBe("1,4");
});
it("rounds pieces up for shopping", () => {
expect(shoppingQuantity(0.25, "piece")).toBe(1);
expect(shoppingQuantity(2, "piece")).toBe(2);
expect(shoppingQuantity(480, "g")).toBe(480);
});
it("converts kitchen measures into the base unit, and refuses what does not fit", () => {
expect(toBase(1.5, "kg", "g")).toBe(1500);
expect(toBase(2, "tbsp", "ml")).toBe(30);
expect(toBase(1, "l", "ml")).toBe(1000);
expect(toBase(2, "tsp", "g")).toBe(8);
expect(toBase(3, "piece", "piece")).toBe(3);
expect(toBase(200, "g", "piece")).toBeNull();
expect(toBase(2, "piece", "g")).toBeNull();
expect(toBase(-1, "g", "g")).toBeNull();
});
it("reads numbers in German and English notation", () => {
expect(parseNumber("1,5")).toBe(1.5);
expect(parseNumber("1.5")).toBe(1.5);
expect(parseNumber("1 1/2")).toBe(1.5);
expect(parseNumber("½")).toBe(0.5);
expect(parseNumber("2½")).toBe(2.5);
expect(parseNumber("3/4")).toBe(0.75);
expect(parseNumber("")).toBeNull();
expect(parseNumber("etwas")).toBeNull();
});
});