From 20fb6c3d22953f5a139c7f847a88ec1062bf5e33 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kai=20B=C3=B6hm?= Date: Fri, 6 Nov 2026 21:35:01 +0000 Subject: [PATCH] Dishes: pool, classics, portions, own dishes, photos, recipe link (26.11.6) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q --- .github/workflows/ci.yml | 3 +- CLAUDE.md | 23 +- OlaresManifest.yaml | 4 +- app/(app)/gerichte/[id]/bearbeiten/page.tsx | 48 +++ app/(app)/gerichte/[id]/page.tsx | 64 ++++ app/(app)/gerichte/hinzufuegen/page.tsx | 47 +++ app/(app)/gerichte/link/page.tsx | 19 + app/(app)/gerichte/neu/page.tsx | 19 + app/(app)/gerichte/page.tsx | 97 +++++ app/(app)/gerichte/vorlagen/page.tsx | 40 ++ app/api/dishes/[id]/archive/route.ts | 18 + app/api/dishes/[id]/photo/route.ts | 29 ++ app/api/dishes/[id]/route.ts | 23 ++ app/api/dishes/adopt/route.ts | 21 ++ app/api/dishes/import/route.ts | 49 +++ app/api/dishes/route.ts | 36 ++ app/api/fotos/[id]/route.ts | 22 ++ app/api/ingredients/route.ts | 17 + components/app-nav.tsx | 7 +- components/dishes/dish-actions.tsx | 102 +++++ components/dishes/dish-form.tsx | 396 ++++++++++++++++++++ components/dishes/dish-tile.tsx | 32 ++ components/dishes/link-import.tsx | 68 ++++ components/dishes/portion-scaler.tsx | 79 ++++ components/dishes/starter-picker.tsx | 87 +++++ components/dishes/undo-archive.tsx | 34 ++ docs/PROJEKTSTART.md | 1 + e2e/gerichte.spec.ts | 161 ++++++++ e2e/rundgang.spec.ts | 18 +- lib/auth/guard.ts | 28 ++ lib/dishes.ts | 152 ++++++++ lib/fetch-safe.ts | 89 +++++ lib/ingredient-search.ts | 42 +++ lib/ingredients.ts | 23 ++ lib/photos.ts | 54 +++ lib/recipe-import.ts | 195 ++++++++++ lib/units.ts | 97 +++++ messages/de.json | 131 ++++++- messages/en.json | 131 ++++++- messages/es.json | 131 ++++++- messages/fr.json | 131 ++++++- olares/Chart.yaml | 4 +- olares/OlaresManifest.yaml | 4 +- olares/markt/26.11.6.md | 5 + package-lock.json | 4 +- package.json | 1 + playwright.config.ts | 12 +- tests/dishes.test.ts | 99 +++++ tests/fetch-safe.test.ts | 18 + tests/ingredient-search.test.ts | 31 ++ tests/recipe-import.test.ts | 61 +++ tests/units.test.ts | 54 +++ 52 files changed, 3038 insertions(+), 23 deletions(-) create mode 100644 app/(app)/gerichte/[id]/bearbeiten/page.tsx create mode 100644 app/(app)/gerichte/[id]/page.tsx create mode 100644 app/(app)/gerichte/hinzufuegen/page.tsx create mode 100644 app/(app)/gerichte/link/page.tsx create mode 100644 app/(app)/gerichte/neu/page.tsx create mode 100644 app/(app)/gerichte/page.tsx create mode 100644 app/(app)/gerichte/vorlagen/page.tsx create mode 100644 app/api/dishes/[id]/archive/route.ts create mode 100644 app/api/dishes/[id]/photo/route.ts create mode 100644 app/api/dishes/[id]/route.ts create mode 100644 app/api/dishes/adopt/route.ts create mode 100644 app/api/dishes/import/route.ts create mode 100644 app/api/dishes/route.ts create mode 100644 app/api/fotos/[id]/route.ts create mode 100644 app/api/ingredients/route.ts create mode 100644 components/dishes/dish-actions.tsx create mode 100644 components/dishes/dish-form.tsx create mode 100644 components/dishes/dish-tile.tsx create mode 100644 components/dishes/link-import.tsx create mode 100644 components/dishes/portion-scaler.tsx create mode 100644 components/dishes/starter-picker.tsx create mode 100644 components/dishes/undo-archive.tsx create mode 100644 e2e/gerichte.spec.ts create mode 100644 lib/auth/guard.ts create mode 100644 lib/dishes.ts create mode 100644 lib/fetch-safe.ts create mode 100644 lib/ingredient-search.ts create mode 100644 lib/ingredients.ts create mode 100644 lib/photos.ts create mode 100644 lib/recipe-import.ts create mode 100644 lib/units.ts create mode 100644 olares/markt/26.11.6.md create mode 100644 tests/dishes.test.ts create mode 100644 tests/fetch-safe.test.ts create mode 100644 tests/ingredient-search.test.ts create mode 100644 tests/recipe-import.test.ts create mode 100644 tests/units.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c682328..e264eb6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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() diff --git a/CLAUDE.md b/CLAUDE.md index edcc0a3..d3cf4fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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//`, ausgeliefert nur über `/api/fotos/`. +- 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 diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index dfe12d3..48b9289 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -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: diff --git a/app/(app)/gerichte/[id]/bearbeiten/page.tsx b/app/(app)/gerichte/[id]/bearbeiten/page.tsx new file mode 100644 index 0000000..4ea3fa9 --- /dev/null +++ b/app/(app)/gerichte/[id]/bearbeiten/page.tsx @@ -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 ( +
+
+

{dish.title}

+

{t("form.editTitle")}

+
+ ({ + 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 })), + }} + /> +
+ ); +} diff --git a/app/(app)/gerichte/[id]/page.tsx b/app/(app)/gerichte/[id]/page.tsx new file mode 100644 index 0000000..0b96080 --- /dev/null +++ b/app/(app)/gerichte/[id]/page.tsx @@ -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 ( +
+
+ + + + + {canWrite ? : null} +
+
+
+ {dish.tags.length ?

{dish.tags.map((tag) => t(`tags.${tag}`)).join(" · ")}

: null} +

{dish.title}

+ {meta ?

{meta}

: null} +
+ {canWrite ? : null} + + {dish.sourceUrl ? ( +

+ {t("detail.source")}:{" "} + + {new URL(dish.sourceUrl).hostname} + +

+ ) : null} +
+
+ ); +} diff --git a/app/(app)/gerichte/hinzufuegen/page.tsx b/app/(app)/gerichte/hinzufuegen/page.tsx new file mode 100644 index 0000000..028549c --- /dev/null +++ b/app/(app)/gerichte/hinzufuegen/page.tsx @@ -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 ( +
+
+

{t("addEyebrow")}

+

{t("addTitle")}

+
+
    + {options.map(({ href, icon: Icon, title, text }) => ( +
  • + + + + {title} + {text} + + + +
  • + ))} + {soon.map(({ icon: Icon, title }) => ( +
  • + + {title} + {t("soon")} +
  • + ))} +
+
+ ); +} diff --git a/app/(app)/gerichte/link/page.tsx b/app/(app)/gerichte/link/page.tsx new file mode 100644 index 0000000..30b0b17 --- /dev/null +++ b/app/(app)/gerichte/link/page.tsx @@ -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 ( +
+
+

{t("addEyebrow")}

+

{t("link.title")}

+
+ +
+ ); +} diff --git a/app/(app)/gerichte/neu/page.tsx b/app/(app)/gerichte/neu/page.tsx new file mode 100644 index 0000000..a498d40 --- /dev/null +++ b/app/(app)/gerichte/neu/page.tsx @@ -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 ( +
+
+

{t("addEyebrow")}

+

{t("form.newTitle")}

+
+ +
+ ); +} diff --git a/app/(app)/gerichte/page.tsx b/app/(app)/gerichte/page.tsx new file mode 100644 index 0000000..9806c9c --- /dev/null +++ b/app/(app)/gerichte/page.tsx @@ -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 ( +
+
+

{t("eyebrow")}

+

{t("title")}

+
+ + {removed ? : null} + + + + {dishes.length ? ( +
    + {dishes.map((d) => ( +
  • + +
  • + ))} +
+ ) : ( +
+

{trial ? t("trial") : t("emptyTitle")}

+

{trial ? t("emptyTrial") : t("emptyText")}

+ {!trial && canWrite ? ( + + {t("addStarters")} + + ) : null} +
+ )} + + {canWrite ? ( + + + {t("add")} + + ) : null} +
+ ); +} diff --git a/app/(app)/gerichte/vorlagen/page.tsx b/app/(app)/gerichte/vorlagen/page.tsx new file mode 100644 index 0000000..d1e84d0 --- /dev/null +++ b/app/(app)/gerichte/vorlagen/page.tsx @@ -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 ( +
+
+

{t("starters.eyebrow")}

+

{t("starters.title")}

+

{t("starters.intro")}

+
+ +
+ ); +} diff --git a/app/api/dishes/[id]/archive/route.ts b/app/api/dishes/[id]/archive/route.ts new file mode 100644 index 0000000..127a216 --- /dev/null +++ b/app/api/dishes/[id]/archive/route.ts @@ -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); +} diff --git a/app/api/dishes/[id]/photo/route.ts b/app/api/dishes/[id]/photo/route.ts new file mode 100644 index 0000000..6ee4429 --- /dev/null +++ b/app/api/dishes/[id]/photo/route.ts @@ -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 }); +} diff --git a/app/api/dishes/[id]/route.ts b/app/api/dishes/[id]/route.ts new file mode 100644 index 0000000..ad4a3b9 --- /dev/null +++ b/app/api/dishes/[id]/route.ts @@ -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; + } +} diff --git a/app/api/dishes/adopt/route.ts b/app/api/dishes/adopt/route.ts new file mode 100644 index 0000000..01b29d5 --- /dev/null +++ b/app/api/dishes/adopt/route.ts @@ -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 }); +} diff --git a/app/api/dishes/import/route.ts b/app/api/dishes/import/route.ts new file mode 100644 index 0000000..0925e2c --- /dev/null +++ b/app/api/dishes/import/route.ts @@ -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 })), + }); +} diff --git a/app/api/dishes/route.ts b/app/api/dishes/route.ts new file mode 100644 index 0000000..a89b9f8 --- /dev/null +++ b/app/api/dishes/route.ts @@ -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; + } +} diff --git a/app/api/fotos/[id]/route.ts b/app/api/fotos/[id]/route.ts new file mode 100644 index 0000000..cec7505 --- /dev/null +++ b/app/api/fotos/[id]/route.ts @@ -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" }, + }); +} diff --git a/app/api/ingredients/route.ts b/app/api/ingredients/route.ts new file mode 100644 index 0000000..2f2c305 --- /dev/null +++ b/app/api/ingredients/route.ts @@ -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 }))); +} diff --git a/components/app-nav.tsx b/components/app-nav.tsx index 61583fc..7415b33 100644 --- a/components/app-nav.tsx +++ b/components/app-nav.tsx @@ -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; diff --git a/components/dishes/dish-actions.tsx b/components/dishes/dish-actions.tsx new file mode 100644 index 0000000..0b376e9 --- /dev/null +++ b/components/dishes/dish-actions.tsx @@ -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(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 ( + <> + e.target.files?.[0] && upload(e.target.files[0])} + /> + + {error ? ( +
+ {t("photoError")} +
+ ) : 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 ( +
+ + + {t("edit")} + + +
+ ); +} diff --git a/components/dishes/dish-form.tsx b/components/dishes/dish-form.tsx new file mode 100644 index 0000000..8a85581 --- /dev/null +++ b/components/dishes/dish-form.tsx @@ -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 = { + 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>(new Set(initial?.tags ?? [])); + const [isTrial, setIsTrial] = useState(initial?.isTrial ?? false); + const [rows, setRows] = useState( + 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( + 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(null); + const [checked, setChecked] = useState(false); + const [busy, setBusy] = useState(false); + + const update = (key: number, patch: Partial) => setRows((rs) => rs.map((r) => (r.key === key ? { ...r, ...patch } : r))); + const updateStep = (key: number, patch: Partial) => 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 ( +
+
+
+ + setTitle(e.target.value)} maxLength={120} required placeholder={t("form.titlePlaceholder")} /> +
+
+
+ + setEffort(e.target.value)} /> +
+
+ + +
+
+
+ {t("form.tags")} +
+ {TAGS.map((tag) => { + const on = tags.has(tag); + return ( + + ); + })} +
+
+ +
+ +
+

{t("form.ingredients")}

+
+ + setPortions(e.target.value)} /> +
+ {initial?.unmatched?.length ? ( +
+

{t("form.unmatched")}

+
    + {initial.unmatched.map((line) => ( +
  • {line}
  • + ))} +
+
+ ) : null} +
    + {rows.map((row) => ( +
  • +
    + update(row.key, { ingredient: p, unit: p.unit })} /> + +
    +
    + update(row.key, { qty: e.target.value })} + /> + +
    + update(row.key, { note: e.target.value })} + /> +
  • + ))} +
+ +
+ +
+

{t("form.steps")}

+
    + {steps.map((s, index) => ( +
  1. + +