From 0a34bc91690911303d5a5f3acc9eebe4030107fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kai=20B=C3=B6hm?= Date: Sat, 7 Nov 2026 14:13:51 +0000 Subject: [PATCH] Add ingredient groups, own ingredients and household products (26.11.38) Pasta, rice, cheese and pulses become umbrella ingredients with their kinds underneath; searching a group term lists the group first, then every kind. Planners can add own ingredients, visible only to their household. A product can be remembered per ingredient for the whole household and is used by every dish without its own product. A group's price is the mean of its kinds. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q --- CLAUDE.md | 5 +- OlaresManifest.yaml | 6 +- app/api/dishes/import/route.ts | 2 +- app/api/dishes/photo-import/route.ts | 2 +- app/api/dishes/style/route.ts | 3 +- app/api/dishes/text-import/route.ts | 2 +- app/api/ingredients/route.ts | 58 ++++++- components/dishes/dish-form.tsx | 100 +++-------- components/dishes/ingredient-picker.tsx | 194 ++++++++++++++++++++++ db/migrations/0022_ingredient_groups.sql | 39 +++++ db/seed/ingredients.json | 203 +++++++++++++++++++---- docs/entscheidungen.md | 20 +++ e2e/gerichte.spec.ts | 47 ++++++ lib/backup.ts | 10 +- lib/costs.ts | 7 +- lib/dishes.ts | 29 +++- lib/ingredient-search.ts | 20 ++- lib/ingredients.ts | 50 +++++- lib/pricing.ts | 24 +++ lib/receipts.ts | 6 +- lib/recipe-draft.ts | 6 +- lib/shopping.ts | 5 +- messages/de.json | 45 ++++- messages/en.json | 45 ++++- messages/es.json | 45 ++++- messages/fr.json | 45 ++++- olares/Chart.yaml | 4 +- olares/OlaresManifest.yaml | 6 +- olares/markt/26.11.38.md | 5 + scripts/seed.mjs | 26 ++- tests/fixture.ts | 4 +- tests/ingredient-groups.test.ts | 94 +++++++++++ tests/ingredient-search.test.ts | 25 ++- tests/pricing.test.ts | 18 +- tests/rls.test.ts | 4 +- 35 files changed, 1040 insertions(+), 164 deletions(-) create mode 100644 components/dishes/ingredient-picker.tsx create mode 100644 db/migrations/0022_ingredient_groups.sql create mode 100644 olares/markt/26.11.38.md create mode 100644 tests/ingredient-groups.test.ts diff --git a/CLAUDE.md b/CLAUDE.md index 3a467e1..feee3f4 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.37 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut: +> **Status:** 26.11.38 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut: > Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den > Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit > Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel @@ -17,7 +17,8 @@ > bis zu 5 Fotos je Gericht (26.11.23), Gerichte einsprechen (26.11.24), Kassenbons (V2b, 26.11.25), > Führung (26.11.27), Präsentationsmodus und Küchendisplay (26.11.28), > lange Bons und Aldi (26.11.29), „Mein Gericht“ (26.11.30), Bons „nicht zum Kochen“ -> (26.11.33), foodplanhero für Maike (26.11.35). Offen ist der +> (26.11.33), foodplanhero für Maike (26.11.35), eine Schrift (26.11.37), Produktgruppen, +> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015). Offen ist der > Magic Link (braucht SMTP). > **Letzte Aktualisierung:** 7. November 2026 diff --git a/OlaresManifest.yaml b/OlaresManifest.yaml index c4a898e..e7757ff 100644 --- a/OlaresManifest.yaml +++ b/OlaresManifest.yaml @@ -1,5 +1,5 @@ # ============================================================================ -# OlaresManifest.yaml — foodplanhero (lunch, bis 26.11.37 „Was gibt's?“) +# OlaresManifest.yaml — foodplanhero (lunch, bis 26.11.34 „Was gibt's?“) # # Linter-Regeln, die hier zwingend gelten (scripts/check-chart.sh): # - metadata.name, metadata.appid, Chart.yaml.name und der Ordnername @@ -21,7 +21,7 @@ metadata: title: foodplanhero description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.37 + version: 26.11.38 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.37' + versionName: '26.11.38' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/app/api/dishes/import/route.ts b/app/api/dishes/import/route.ts index 065274b..253e475 100644 --- a/app/api/dishes/import/route.ts +++ b/app/api/dishes/import/route.ts @@ -42,5 +42,5 @@ export async function POST(request: Request) { byAi = true; } const imageUrl = recipe.image ? new URL(recipe.image, page.url).toString() : null; - return json({ ...(await draftFromRecipe(recipe, await getLocale(), { sourceUrl: page.url, imageUrl, ai })), byAi }); + return json({ ...(await draftFromRecipe(recipe, await getLocale(), { sourceUrl: page.url, imageUrl, ai, householdId: session.householdId })), byAi }); } diff --git a/app/api/dishes/photo-import/route.ts b/app/api/dishes/photo-import/route.ts index 8275b47..89d2dc0 100644 --- a/app/api/dishes/photo-import/route.ts +++ b/app/api/dishes/photo-import/route.ts @@ -40,5 +40,5 @@ export async function POST(request: Request) { throw error; } if (!recipe) return fail("noRecipe", 422); - return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai })), byAi: true }); + return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai, householdId: session.householdId })), byAi: true }); } diff --git a/app/api/dishes/style/route.ts b/app/api/dishes/style/route.ts index 1a3a53a..1099afe 100644 --- a/app/api/dishes/style/route.ts +++ b/app/api/dishes/style/route.ts @@ -5,6 +5,7 @@ import { guardWrite, isResponse } from "@/lib/auth/guard"; import { fail, json, readJson } from "@/lib/auth/http"; import { stepIngredient } from "@/lib/dishes"; import { allIngredients } from "@/lib/ingredients"; +import { withHousehold } from "@/lib/db"; import { standardizeSteps } from "@/lib/recipe-standardize"; export const dynamic = "force-dynamic"; @@ -24,7 +25,7 @@ export async function POST(request: Request) { const body = input.safeParse(await readJson(request)); if (!body.success) return fail("invalid", 400); const locale = await getLocale(); - const all = new Map((await allIngredients()).map((e) => [e.id, e])); + const all = new Map((await withHousehold(session.householdId, (c) => allIngredients(c))).map((e) => [e.id, e])); const own = body.data.ingredientIds.map((id) => all.get(id)).filter((e) => !!e); const styled = await standardizeSteps( await aiFor(session.householdId), diff --git a/app/api/dishes/text-import/route.ts b/app/api/dishes/text-import/route.ts index be43ec6..9e3b8f0 100644 --- a/app/api/dishes/text-import/route.ts +++ b/app/api/dishes/text-import/route.ts @@ -28,5 +28,5 @@ export async function POST(request: Request) { } if (!recipe) return fail("noRecipe", 422); recipe = { ...recipe, ingredients: guardAmounts(recipe.ingredients, body.data.text), steps: guardSteps(recipe.steps, body.data.text) }; - return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai })), byAi: true }); + return json({ ...(await draftFromRecipe(recipe, await getLocale(), { ai, householdId: session.householdId })), byAi: true }); } diff --git a/app/api/ingredients/route.ts b/app/api/ingredients/route.ts index 2f2c305..baf68c3 100644 --- a/app/api/ingredients/route.ts +++ b/app/api/ingredients/route.ts @@ -1,17 +1,61 @@ 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"; +import { z } from "zod"; +import { guardRead, guardWrite, isResponse } from "@/lib/auth/guard"; +import { fail, json, readJson } from "@/lib/auth/http"; +import { PLANNERS } from "@/lib/auth/roles"; +import { CATEGORIES } from "@/lib/categories"; +import { withHousehold } from "@/lib/db"; +import { searchIngredients, type IngredientEntry } from "@/lib/ingredient-search"; +import { allIngredients, createOwnIngredient, OwnIngredientRefused } from "@/lib/ingredients"; export const dynamic = "force-dynamic"; -// Zutaten-Suche beim Tippen, in der Sprache der Person. +const view = (i: IngredientEntry, locale: string, all: IngredientEntry[], products = new Map()) => ({ + id: i.id, + name: i.names[locale] ?? i.names.en, + unit: i.unit, + group: !!i.isGroup, + kinds: i.isGroup ? all.filter((e) => e.parentId === i.id).length : 0, + parentId: i.parentId ?? null, + own: !!i.own, + // Gemerktes Produkt des Haushalts — das Formular zeigt es gleich beim Wählen. + product: products.get(i.id) ?? null, +}); + +// Zutaten-Suche beim Tippen, in der Sprache der Person — mit den eigenen des +// Haushalts und den Produktgruppen (26.11.38). Ohne q: nur die Gruppen (fürs Anlegen). 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 }))); + const { all, products } = await withHousehold(session.householdId, async (c) => ({ + all: await allIngredients(c), + products: new Map((await c.query("select ingredient_id, product from household_products")).rows.map((r) => [r.ingredient_id as string, r.product as string])), + })); + const hits = q.trim() ? searchIngredients(all, q.slice(0, 60), locale) : all.filter((i) => i.isGroup); + return json(hits.map((i) => view(i, locale, all, products))); +} + +const create = z.object({ + name: z.string().trim().min(1).max(60), + unit: z.enum(["g", "ml", "piece"]), + parentId: z.string().uuid().nullable(), + category: z.enum(CATEGORIES), +}); + +// Eigene Zutat anlegen — wer Gerichte pflegt (Kai: „Ja, wer Gerichte pflegt“). +export async function POST(request: Request) { + const session = await guardWrite(request, [...PLANNERS]); + if (isResponse(session)) return session; + const body = create.safeParse(await readJson(request)); + if (!body.success) return fail("invalid", 400); + const locale = await getLocale(); + try { + const entry = await withHousehold(session.householdId, (c) => createOwnIngredient(c, session.householdId, body.data)); + return json(view(entry, locale, []), 201); + } catch (error) { + if (error instanceof OwnIngredientRefused) return fail(error.message, 409); + throw error; + } } diff --git a/components/dishes/dish-form.tsx b/components/dishes/dish-form.tsx index 62da5ef..33a4de3 100644 --- a/components/dishes/dish-form.tsx +++ b/components/dishes/dish-form.tsx @@ -13,9 +13,11 @@ import { parseNumber, type BaseUnit } from "@/lib/units"; import { cn } from "@/lib/utils"; import { SECTIONS, type Section } from "@/lib/recipe-style"; -export type Picked = { id: string; name: string; unit: BaseUnit }; +import { IngredientPicker, type Picked } from "./ingredient-picker"; +export { IngredientPicker, type Picked }; // Produkt (optional): Name, Packung in der Einheit der Zeile, Kochzeit laut Packung. -type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean }; +// inherited: Lieblingsprodukt des Haushalts für diese Zutat (26.11.38); remember: dieses Produkt für alle Gerichte merken. +type Row = { key: number; ingredient: Picked | null; qty: string; unit: string; note: string; product: string; pack: string; cook: string; open: boolean; remember?: boolean; inherited?: string | null }; type StepRow = { key: number; text: string; timer: string; section: Section | "" }; export type DishFormValue = { @@ -32,7 +34,7 @@ export type DishFormValue = { qty: number | null; unit?: string | null; note: string | null; - product?: { name: string; pack: number | null; cookMinutes: number | null } | null; + product?: { name: string; pack: number | null; cookMinutes: number | null; fromHousehold?: boolean } | null; }[]; steps: { text: string; timerMinutes: number | null; section?: Section | null }[]; sourceUrl?: string | null; @@ -76,10 +78,12 @@ export function DishForm({ initial }: { initial?: DishFormValue }) { 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 ?? "", - product: i.product?.name ?? "", - pack: i.product?.pack ? formatQty(i.product.pack) : "", - cook: i.product?.cookMinutes ? String(i.product.cookMinutes) : "", - open: !!i.product, + // Ein geerbtes Lieblingsprodukt füllt die Felder nicht — leer heißt: es gilt weiter. + product: i.product && !i.product.fromHousehold ? i.product.name : "", + pack: i.product?.pack && !i.product.fromHousehold ? formatQty(i.product.pack) : "", + cook: i.product?.cookMinutes && !i.product.fromHousehold ? String(i.product.cookMinutes) : "", + open: !!i.product && !i.product.fromHousehold, + inherited: i.product?.fromHousehold ? i.product.name : null, })) : [{ key: next(), ingredient: null, qty: "", unit: "g", note: "", product: "", pack: "", cook: "", open: false }], ); @@ -152,6 +156,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) { name: r.product.trim(), pack: r.pack.trim() ? (parseNumber(r.pack) ?? null) : null, cookMinutes: r.cook.trim() ? Math.round(parseNumber(r.cook) ?? 0) || null : null, + remember: !!r.remember, } : null, })); @@ -277,7 +282,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) { {rows.map((row) => (
  • - update(row.key, { ingredient: p, unit: p.unit })} /> + update(row.key, { ingredient: p, unit: p.unit, inherited: row.product ? row.inherited : (p.product ?? null) })} />

    {t("form.productHint")}

    + ) : ( - +
    + {row.inherited ?

    {t("form.inheritedProduct", { product: row.inherited })}

    : null} + +
    )}
  • ))} @@ -461,67 +473,3 @@ export function DishForm({ initial }: { initial?: DishFormValue }) { // Zutat suchen und wählen. Tippen sucht in der Sprache der Person, auch über // Synonyme (lib/ingredient-search.ts); ein Tipp auf einen Treffer wählt ihn. -export 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([]); - const [open, setOpen] = useState(false); - const timer = useRef | 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 ( -
    - 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 ? ( -
      - {hits.length ? ( - hits.map((h) => ( -
    • - -
    • - )) - ) : ( -
    • {t("noHits")}
    • - )} -
    - ) : null} -
    - ); -} diff --git a/components/dishes/ingredient-picker.tsx b/components/dishes/ingredient-picker.tsx new file mode 100644 index 0000000..48b59bd --- /dev/null +++ b/components/dishes/ingredient-picker.tsx @@ -0,0 +1,194 @@ +"use client"; + +import { Plus } from "lucide-react"; +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 { CATEGORIES } from "@/lib/categories"; +import { normalize } from "@/lib/ingredient-search"; +import type { BaseUnit } from "@/lib/units"; +import { cn } from "@/lib/utils"; + +export type Picked = { id: string; name: string; unit: BaseUnit; group?: boolean; product?: string | null }; +type Hit = Picked & { kinds: number; parentId: string | null; own: boolean }; + +// Zutat suchen und wählen (26.11.38): Ein Oberbegriff („Pasta“) steht oben als +// „beliebige Sorte“, seine Sorten eingerückt darunter. Findet die Suche nichts +// Passendes, legt, wer Gerichte pflegt, eine eigene Zutat für den Haushalt an. +export function IngredientPicker({ value, onPick, canCreate = false }: { value: Picked | null; onPick: (p: Picked) => void; canCreate?: boolean }) { + const t = useTranslations("dishes.form"); + const ti = useTranslations("ingredients"); + const id = useId(); + const [query, setQuery] = useState(value?.name ?? ""); + const [hits, setHits] = useState([]); + const [open, setOpen] = useState(false); + const [creating, setCreating] = useState(false); + const timer = useRef | 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]); + + const pick = (h: Picked) => { + onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null }); + setQuery(h.name); + setOpen(false); + setCreating(false); + }; + const groupIds = new Set(hits.filter((h) => h.group).map((h) => h.id)); + const exact = hits.some((h) => normalize(h.name) === normalize(query)); + const offerCreate = canCreate && query.trim().length >= 2 && !exact; + + return ( +
    + 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); + setCreating(false); + }} + /> + {open && query.trim() && query !== value?.name && !creating ? ( +
      + {hits.map((h) => { + const member = !!h.parentId && groupIds.has(h.parentId); + return ( +
    • + +
    • + ); + })} + {!hits.length && !offerCreate ?
    • {t("noHits")}
    • : null} + {offerCreate ? ( +
    • + +
    • + ) : null} +
    + ) : null} + {creating ? setCreating(false)} onCreated={pick} /> : null} +
    + ); +} + +function CreateIngredient({ name: initial, onCancel, onCreated }: { name: string; onCancel: () => void; onCreated: (p: Picked) => void }) { + const t = useTranslations("ingredients"); + const id = useId(); + const [name, setName] = useState(initial); + const [unit, setUnit] = useState("g"); + const [groups, setGroups] = useState([]); + const [parentId, setParentId] = useState(""); + const [category, setCategory] = useState("pasta_rice"); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(false); + + useEffect(() => { + void fetch("/api/ingredients") + .then((r) => (r.ok ? r.json() : [])) + .then(setGroups) + .catch(() => undefined); + }, []); + + async function save() { + setBusy(true); + setError(false); + const res = await fetch("/api/ingredients", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ name, unit, parentId: parentId || null, category }), + }).catch(() => null); + setBusy(false); + if (!res?.ok) return setError(true); + onCreated(await res.json()); + } + + return ( +
    +

    {t("title")}

    +
    + + setName(e.target.value)} /> +
    +
    +
    + + +
    +
    + + +
    +
    + {!parentId ? ( +
    + + +
    + ) : null} + {error ? {t("error")} : null} +
    + + +
    +
    + ); +} diff --git a/db/migrations/0022_ingredient_groups.sql b/db/migrations/0022_ingredient_groups.sql new file mode 100644 index 0000000..10ece71 --- /dev/null +++ b/db/migrations/0022_ingredient_groups.sql @@ -0,0 +1,39 @@ +-- Produktgruppen und eigene Zutaten (Kai, 7.11.2026, 26.11.38). +-- +-- Gruppen: Eine Zutat kann ein Oberbegriff sein (Pasta, Reis, Käse, Hülsenfrüchte) +-- und selbst gewählt werden („Pasta, beliebige Sorte“); die Sorten zeigen mit +-- parent_id auf ihn. Kommen aus db/seed wie alle globalen Zutaten. +-- +-- Eigene Zutaten: Fehlt etwas im Katalog („Gnocchi“), legen Erwachsene es für +-- ihren Haushalt an (household_id). Global bleibt household_id leer. +-- +-- Lieblingsprodukt je Zutat oder Gruppe für den ganzen Haushalt („unsere Pasta +-- ist Barilla Nr. 5“): household_products; ein Produkt am Gericht geht vor. + +alter table ingredients add column is_group boolean not null default false; +alter table ingredients add column parent_id uuid references ingredients (id); +alter table ingredients add column household_id uuid references households (id) on delete cascade; +create index ingredients_parent_idx on ingredients (parent_id) where parent_id is not null; +create index ingredients_household_idx on ingredients (household_id) where household_id is not null; + +drop policy ingredients_read on ingredients; +create policy ingredients_read on ingredients for select + using (household_id is null or household_id = app_household_id() or app_maintenance()); +create policy ingredients_own on ingredients for all + using (household_id = app_household_id()) + with check (household_id = app_household_id() and not is_group); + +create table household_products ( + household_id uuid not null references households (id) on delete cascade, + ingredient_id uuid not null references ingredients (id) on delete cascade, + product text not null check (length(trim(product)) between 1 and 80), + product_pack numeric(12, 3) check (product_pack is null or product_pack > 0), + cook_minutes integer check (cook_minutes is null or cook_minutes between 1 and 240), + updated_at timestamptz not null default now(), + primary key (household_id, ingredient_id) +); +alter table household_products enable row level security; +alter table household_products force row level security; +create policy household_products_household on household_products + using (household_id = app_household_id()) + with check (household_id = app_household_id()); diff --git a/db/seed/ingredients.json b/db/seed/ingredients.json index e4f3958..eccec90 100644 --- a/db/seed/ingredients.json +++ b/db/seed/ingredients.json @@ -1,4 +1,108 @@ [ + { + "key": "pasta", + "category": "pasta_rice", + "unit": "g", + "freshness": 3, + "packs": [ + 500, + 1000 + ], + "pantry": true, + "group": true, + "names": { + "de": "Pasta", + "en": "Pasta", + "fr": "Pâtes", + "es": "Pasta" + }, + "synonyms": [ + "Nudeln", + "Teigwaren", + "beliebige Nudeln", + "noodles", + "pâtes", + "fideos" + ] + }, + { + "key": "rice", + "category": "pasta_rice", + "unit": "g", + "freshness": 3, + "packs": [ + 500, + 1000 + ], + "pantry": true, + "group": true, + "names": { + "de": "Reis", + "en": "Rice", + "fr": "Riz", + "es": "Arroz" + }, + "synonyms": [ + "Reissorten", + "beliebiger Reis", + "rice", + "riz", + "arroz" + ] + }, + { + "key": "cheese", + "category": "cheese", + "unit": "g", + "freshness": 2, + "packs": [ + 200, + 400 + ], + "pantry": false, + "group": true, + "names": { + "de": "Käse", + "en": "Cheese", + "fr": "Fromage", + "es": "Queso" + }, + "synonyms": [ + "Käsesorten", + "beliebiger Käse", + "cheese", + "fromage", + "queso" + ] + }, + { + "key": "legumes", + "category": "pasta_rice", + "unit": "g", + "freshness": 3, + "packs": [ + 400, + 500 + ], + "pantry": true, + "group": true, + "names": { + "de": "Hülsenfrüchte", + "en": "Pulses", + "fr": "Légumineuses", + "es": "Legumbres" + }, + "synonyms": [ + "Linsen", + "Bohnen", + "Kichererbsen", + "Erbsen", + "Hülsenfrucht", + "lentils", + "beans", + "légumes secs" + ] + }, { "key": "potato", "category": "vegetables", @@ -4095,7 +4199,8 @@ 200, 400 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "grated_cheese", @@ -4122,7 +4227,8 @@ 200, 250 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "emmental", @@ -4170,7 +4276,8 @@ 150, 200 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "mozzarella", @@ -4194,7 +4301,8 @@ 125, 250 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "feta", @@ -4218,7 +4326,8 @@ 150, 200 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "cheddar", @@ -4267,7 +4376,8 @@ 200, 300 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "mascarpone", @@ -4332,7 +4442,8 @@ 150, 200 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "camembert", @@ -4377,7 +4488,8 @@ 200, 250 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "gruyere", @@ -4446,7 +4558,8 @@ 200, 250 ], - "pantry": false + "pantry": false, + "parent": "cheese" }, { "key": "egg", @@ -4563,7 +4676,8 @@ 400, 500 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "fresh_tagliatelle", @@ -4587,7 +4701,8 @@ 250, 400 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "maultaschen", @@ -5146,7 +5261,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "pasta" }, { "key": "penne", @@ -5168,7 +5284,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "pasta" }, { "key": "fusilli", @@ -5192,7 +5309,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "pasta" }, { "key": "macaroni", @@ -5217,7 +5335,8 @@ 500, 1000 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "tagliatelle", @@ -5241,7 +5360,8 @@ 250, 500 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "lasagne_sheets", @@ -5264,7 +5384,8 @@ 250, 500 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "soup_pasta", @@ -5290,7 +5411,8 @@ 250, 500 ], - "pantry": false + "pantry": false, + "parent": "pasta" }, { "key": "egg_noodles", @@ -5373,7 +5495,8 @@ 1000, 2000 ], - "pantry": true + "pantry": true, + "parent": "rice" }, { "key": "basmati_rice", @@ -5398,7 +5521,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "rice" }, { "key": "risotto_rice", @@ -5421,7 +5545,8 @@ 500, 1000 ], - "pantry": false + "pantry": false, + "parent": "rice" }, { "key": "paella_rice", @@ -5445,7 +5570,8 @@ 500, 1000 ], - "pantry": false + "pantry": false, + "parent": "rice" }, { "key": "pudding_rice", @@ -5469,7 +5595,8 @@ 500, 1000 ], - "pantry": false + "pantry": false, + "parent": "rice" }, { "key": "couscous", @@ -5580,7 +5707,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "legumes" }, { "key": "brown_lentils", @@ -5607,7 +5735,8 @@ 500, 1000 ], - "pantry": true + "pantry": true, + "parent": "legumes" }, { "key": "dried_chickpeas", @@ -5627,7 +5756,8 @@ "packs": [ 500 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "dried_white_beans", @@ -5650,7 +5780,8 @@ "packs": [ 500 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "split_peas", @@ -5673,7 +5804,8 @@ "packs": [ 500 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "chopped_tomatoes", @@ -5819,7 +5951,8 @@ 250, 400 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "black_beans", @@ -5842,7 +5975,8 @@ 250, 400 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "chickpeas", @@ -5867,7 +6001,8 @@ 240, 400 ], - "pantry": true + "pantry": true, + "parent": "legumes" }, { "key": "white_beans", @@ -5892,7 +6027,8 @@ 250, 400 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "baked_beans", @@ -5937,7 +6073,8 @@ 400, 800 ], - "pantry": false + "pantry": false, + "parent": "legumes" }, { "key": "sweetcorn", diff --git a/docs/entscheidungen.md b/docs/entscheidungen.md index 13620f3..be5642a 100644 --- a/docs/entscheidungen.md +++ b/docs/entscheidungen.md @@ -255,3 +255,23 @@ Mit foodplanhero standen vier Schriften auf der Startseite: Poppins (Logo), Cave alles** — Logo, Überschriften (SemiBold), Text, Knöpfe —, wie in Kais Figma-Entwurf. **Caveat** bleibt, aber nur als Maikes Unterschrift „by Maike“, nirgends sonst. Newsreader und Geist sind entfernt. Farben, Flächen und Abstände aus E-0009 bleiben. + +## E-0015 · Produktgruppen, eigene Zutaten, Lieblingsprodukt je Haushalt + +*7.11.2026 · Kai („den Oberbegriff Pasta eigentlich besser … Oder Produktgruppen?“)* + +**Gruppen.** Es gibt vier Oberbegriffe: Pasta, Reis, Käse sowie Linsen und Hülsenfrüchte. +Jede Gruppe ist selbst eine Zutat (`is_group`) und lässt sich als „beliebige Sorte“ wählen. +Die Sorten hängen über `parent_id` an ihrer Gruppe. Trifft die Suche eine Gruppe, auch über +ein Synonym („Nudeln“), steht die Gruppe oben und alle ihre Sorten folgen. Gibt es keinen +eigenen Bon-Preis für die Gruppe, ist ihr Preis der Durchschnitt der besten Preise ihrer +Sorten. + +**Eigene Zutaten.** Zutaten anlegen darf, wer Gerichte pflegt (Admin und Mitglied). Eine +eigene Zutat gehört dem Haushalt (`household_id`). Die Zeilensicherheit zeigt sie nur +diesem Haushalt, und Gruppen anlegen kann ein Haushalt nicht. Doppelte Namen werden +abgewiesen. Eigene Zutaten gehen in die Sicherung. + +**Lieblingsprodukt.** Es gilt je Zutat für den ganzen Haushalt (`household_products`) und +wird mit dem Haken „Für alle Gerichte mit … merken“ gesetzt. Ein Produkt, das am Gericht +selbst steht, geht immer vor. diff --git a/e2e/gerichte.spec.ts b/e2e/gerichte.spec.ts index 46de691..20a8195 100644 --- a/e2e/gerichte.spec.ts +++ b/e2e/gerichte.spec.ts @@ -356,3 +356,50 @@ test.describe("cookbook photo and AI setting", () => { await expect(page.getByRole("note").first()).toContainText("Von der AI gelesen"); }); }); + +// Produktgruppen und eigene Zutaten (26.11.38, Kai: „den Oberbegriff Pasta eigentlich besser“). +test("a group term shows the group with its kinds; an own ingredient and a remembered product", async ({ page }) => { + await page.goto("/gerichte/neu"); + await page.fill("#title", "Gnocchi in Salbeibutter"); + const search = page.getByRole("combobox", { name: "Zutat suchen" }).first(); + await search.fill("Nudeln"); + const options = page.getByRole("listbox").getByRole("option"); + await expect(options.first()).toContainText("Pasta · beliebige Sorte"); + await expect(page.getByRole("option", { name: "Spaghetti", exact: true })).toBeVisible(); + await expect(page.getByRole("option", { name: "Penne", exact: true })).toBeVisible(); + + await search.fill("Gnocchi Hausmacher"); + await page.getByRole("option", { name: "„Gnocchi Hausmacher“ als neue Zutat anlegen" }).click(); + const create = page.getByRole("group", { name: "Neue Zutat" }); + await create.getByLabel("Gehört zu").selectOption({ label: "Pasta" }); + await expect(create.getByLabel("Regal im Laden")).toHaveCount(0); + await create.getByRole("button", { name: "Anlegen" }).click(); + await expect(search).toHaveValue("Gnocchi Hausmacher"); + await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("500"); + await page.getByRole("button", { name: "Produkt hinterlegen" }).click(); + await page.getByLabel("Produkt für Gnocchi Hausmacher").fill("Rana Gnocchi"); + await page.getByLabel("Für alle Gerichte mit Gnocchi Hausmacher merken").check(); + await page.getByLabel("Schritt 1", { exact: true }).fill("Gnocchi in Salzwasser garen."); + await page.getByRole("button", { name: "Speichern" }).click(); + await expect(page.getByRole("heading", { level: 1 })).toHaveText("Gnocchi in Salbeibutter"); + + // Ein zweites Gericht bekommt das gemerkte Produkt gleich beim Wählen. + await page.goto("/gerichte/neu"); + await page.fill("#title", "Gnocchi-Auflauf"); + await page.getByRole("combobox", { name: "Zutat suchen" }).first().fill("Gnocchi Haus"); + await page.getByRole("option", { name: /Gnocchi Hausmacher.*eigene/ }).click(); + await expect(page.getByText("Euer Produkt für alle Gerichte: Rana Gnocchi")).toBeVisible(); + await expect(page.getByRole("button", { name: "Anderes Produkt für dieses Gericht" })).toBeVisible(); + await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("400"); + await page.getByLabel("Schritt 1", { exact: true }).fill("Gnocchi in die Form geben."); + await page.getByRole("button", { name: "Speichern" }).click(); + await expect(page.locator("main")).toContainText("Rana Gnocchi"); + + // Wieder aus dem Pool, damit der Plan danach denselben Bestand vorschlägt. + for (const title of ["Gnocchi-Auflauf", "Gnocchi in Salbeibutter"]) { + await page.goto("/gerichte"); + await page.getByRole("link", { name: new RegExp(title) }).click(); + await page.getByRole("button", { name: "Entfernen" }).click(); + await expect(page).toHaveURL(/entfernt=/); + } +}); diff --git a/lib/backup.ts b/lib/backup.ts index 430ebaa..62a7612 100644 --- a/lib/backup.ts +++ b/lib/backup.ts @@ -22,6 +22,8 @@ export const TABLES = [ "passkeys", "invitations", "kid_devices", // nur Hashes; nach dem Zurückspielen gilt das Tablet weiter + "ingredients", // nur die eigenen des Haushalts (WHERE unten); die globalen kommen aus db/seed + "household_products", "stores", "store_aisles", "dishes", @@ -45,13 +47,15 @@ export const TABLES = [ "household_ai", // Schlüssel verschlüsselt: gehört mit tresor.key zusammen ] as const; +/** Tabellen, die globale und eigene Zeilen mischen: nur die eigenen in den Abzug. */ +const ONLY_OWN: Record = { ingredients: "where t.household_id is not null" }; + /** Bewusst nicht im Abzug, je mit Grund. */ export const EXCLUDED: Record = { instance: "eigene Zeile im Abzug (box-weit, nicht je Haushalt)", sessions: "kurzlebig; nach dem Zurückspielen meldet sich jede Person mit ihrem Passkey neu an", auth_challenges: "lebt fünf Minuten", auth_attempts: "Bremse, lebt einen Tag", - ingredients: "kommt aus db/seed mit festen Kennungen (scripts/seed.mjs), nicht aus dem Haushalt", schema_migrations: "gehört zur Datenbank, nicht zu den Daten", starter_dishes: "Vorlage aus db/seed, wird bei jedem Start eingespielt", starter_dish_ingredients: "Vorlage aus db/seed", @@ -92,7 +96,9 @@ export async function createBackup(): Promise { const out: Record[]> = {}; for (const table of TABLES) { // to_jsonb hält bytea als \x…-Text; jsonb_populate_recordset wandelt beim Zurückspielen zurück. - const { rows } = await client.query(`select coalesce(jsonb_agg(to_jsonb(t) order by to_jsonb(t)::text), '[]'::jsonb) as rows from ${table} t`); + const { rows } = await client.query( + `select coalesce(jsonb_agg(to_jsonb(t) order by to_jsonb(t)::text), '[]'::jsonb) as rows from ${table} t ${ONLY_OWN[table] ?? ""}`, + ); out[table] = rows[0].rows; } return out; diff --git a/lib/costs.ts b/lib/costs.ts index dd02fcc..1bfec1b 100644 --- a/lib/costs.ts +++ b/lib/costs.ts @@ -1,6 +1,6 @@ import "server-only"; import type { PoolClient } from "pg"; -import { currentPrices, dishCost, priceClasses, type DishCost, type PriceClass, type PricePoint } from "./pricing"; +import { currentPrices, dishCost, priceClasses, withGroupPrices, type DishCost, type PriceClass, type PricePoint } from "./pricing"; import { toBase, type BaseUnit, type InputUnit } from "./units"; // Preise und Kosten aus der Datenbank (Rechnen in lib/pricing.ts). @@ -25,7 +25,10 @@ export async function loadPrices(client: PoolClient, currency: string): Promise< from default_prices where currency = $1`, [currency], ); - return currentPrices(rows); + const members = new Map(); + for (const r of (await client.query("select id, parent_id from ingredients where parent_id is not null")).rows as { id: string; parent_id: string }[]) + members.set(r.parent_id, [...(members.get(r.parent_id) ?? []), r.id]); + return withGroupPrices(currentPrices(rows), members); } /** Kosten pro Portion je Gericht (alle oder die genannten). */ diff --git a/lib/dishes.ts b/lib/dishes.ts index 6aa6049..e6786f9 100644 --- a/lib/dishes.ts +++ b/lib/dishes.ts @@ -37,6 +37,8 @@ export const dishInput = z.object({ name: z.string().trim().min(1).max(80), pack: z.number().positive().max(100000).nullable().optional(), cookMinutes: z.number().int().min(1).max(240).nullable().optional(), + // „Für alle Gerichte merken“ (26.11.38): gilt dann für den ganzen Haushalt. + remember: z.boolean().optional(), }) .nullable() .optional(), @@ -84,7 +86,7 @@ export type DishDetail = DishSummary & { }; /** Produkt an einer Zutat des Gerichts; pack in der Basiseinheit der Zutat. */ -export type Product = { name: string; pack: number | null; cookMinutes: number | null }; +export type Product = { name: string; pack: number | null; cookMinutes: number | null; fromHousehold?: boolean }; /** Alle Namen einer Zutat (jede Sprache, Einzahl, Synonyme) — für die Zuordnung zu Schritten. */ export function stepIngredient(e: IngredientEntry): StepIngredient { @@ -104,11 +106,13 @@ export async function getDish(client: PoolClient, id: string, locale: string): P 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 entries = new Map((await allIngredients()).map((i) => [i.id, i])); + const entries = new Map((await allIngredients(client)).map((i) => [i.id, i])); const ingredients = ( await client.query( - `select ingredient_id, qty_per_portion, unit, note, is_staple, product, product_pack::float as product_pack, product_cook_minutes - from dish_ingredients where dish_id = $1 order by position`, + `select di.ingredient_id, di.qty_per_portion, di.unit, di.note, di.is_staple, di.product, di.product_pack::float as product_pack, + di.product_cook_minutes, hp.product as house_product, hp.product_pack::float as house_pack, hp.cook_minutes as house_cook + from dish_ingredients di left join household_products hp on hp.ingredient_id = di.ingredient_id + where di.dish_id = $1 order by di.position`, [id], ) ).rows.map((r) => ({ @@ -119,7 +123,12 @@ export async function getDish(client: PoolClient, id: string, locale: string): P unit: r.unit, note: r.note, isStaple: r.is_staple, - product: r.product ? { name: r.product, pack: r.product_pack, cookMinutes: r.product_cook_minutes } : null, + // Produkt am Gericht, sonst das Lieblingsprodukt des Haushalts für diese Zutat (26.11.38). + product: r.product + ? { name: r.product, pack: r.product_pack, cookMinutes: r.product_cook_minutes } + : r.house_product + ? { name: r.house_product, pack: r.house_pack, cookMinutes: r.house_cook, fromHousehold: true } + : null, })); const rows = ( await client.query("select section, text, timer_seconds, ingredient_ids from dish_steps where dish_id = $1 order by position", [id]) @@ -161,7 +170,7 @@ 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 { - const all = await allIngredients(); + const all = await allIngredients(client); const units = new Map(all.map((i) => [i.id, i.unit])); const rows = input.ingredients.map((i, position) => { const base = units.get(i.ingredientId); @@ -207,6 +216,14 @@ export async function saveDish(client: PoolClient, householdId: string, memberId [householdId, dishId, r.ingredientId, r.perPortion, r.base, r.note ?? null, r.position, r.product?.name ?? null, r.product ? r.pack : null, r.product?.cookMinutes ?? null], ); + if (r.product?.remember) { + await client.query( + `insert into household_products (household_id, ingredient_id, product, product_pack, cook_minutes) values ($1, $2, $3, $4, $5) + on conflict (household_id, ingredient_id) do update set product = excluded.product, product_pack = excluded.product_pack, + cook_minutes = excluded.cook_minutes, updated_at = now()`, + [householdId, r.ingredientId, r.product.name, r.pack, r.product.cookMinutes ?? null], + ); + } } // Abschnitte: was das Formular sagt, sonst nach den Verben; Zutaten je Schritt aus dem Text. const own = all.filter((e) => input.ingredients.some((i) => i.ingredientId === e.id)).map(stepIngredient); diff --git a/lib/ingredient-search.ts b/lib/ingredient-search.ts index 71939c6..3d863e2 100644 --- a/lib/ingredient-search.ts +++ b/lib/ingredient-search.ts @@ -10,6 +10,12 @@ export type IngredientEntry = { names: Record; synonyms: string[]; forms?: Partial> | null; + /** Oberbegriff (Pasta, Reis …), selbst wählbar als „beliebige Sorte“. */ + isGroup?: boolean; + /** Sorte einer Gruppe („spaghetti“ → „pasta“). */ + parentId?: string | null; + /** Eigene Zutat des Haushalts. */ + own?: boolean; }; export function normalize(text: string): string { @@ -37,10 +43,22 @@ export function searchIngredients(list: IngredientEntry[], query: string, locale else if (one.startsWith(q)) score = 75; else if (name.split(" ").some((w) => w.startsWith(q))) score = 60; else if (name.includes(q)) score = 40; + // Ein Oberbegriff zählt mit seinen Synonymen wie mit seinem Namen: „Nudeln“ meint Pasta. + else if (entry.isGroup && entry.synonyms.some((s) => normalize(s).startsWith(q))) score = 85; 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); + const ranked = scored.sort((a, b) => b.score - a.score).map((s) => s.entry); + // Produktgruppen (26.11.38): Trifft die Suche einen Oberbegriff („Nudeln“ → Pasta), + // kommt er zuerst und gleich dahinter alle seine Sorten — auch Spaghetti und Penne, + // die selbst nicht „Nudeln“ heißen. Danach der Rest. + const group = ranked.find((e) => e.isGroup && ranked.indexOf(e) < 3); + if (!group) return ranked.slice(0, limit); + const members = list + .filter((e) => e.parentId === group.id) + .sort((a, b) => (a.names[locale] ?? a.names.en ?? "").localeCompare(b.names[locale] ?? b.names.en ?? "", locale)); + const seen = new Set([group.id, ...members.map((m) => m.id)]); + return [group, ...members, ...ranked.filter((e) => !seen.has(e.id))].slice(0, Math.max(limit, members.length + 3)); } diff --git a/lib/ingredients.ts b/lib/ingredients.ts index b6f6099..53dd977 100644 --- a/lib/ingredients.ts +++ b/lib/ingredients.ts @@ -1,14 +1,18 @@ import "server-only"; +import type { PoolClient } from "pg"; 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. +// (Neustart). Einmal laden, im Speicher halten. Eigene Zutaten eines Haushalts +// (26.11.38) kommen je Anfrage dazu — mit einem Client in seinem Kontext. let cache: Promise | null = null; -export function allIngredients(): Promise { +const COLUMNS = `id, key, default_unit as unit, category, names, synonyms, forms, is_group as "isGroup", parent_id as "parentId"`; + +function globalIngredients(): Promise { cache ??= pool - .query("select id, key, default_unit as unit, category, names, synonyms, forms from ingredients order by key") + .query(`select ${COLUMNS} from ingredients where household_id is null order by key`) .then((r) => r.rows as IngredientEntry[]) .catch((error) => { cache = null; @@ -17,7 +21,43 @@ export function allIngredients(): Promise { return cache; } -export async function ingredientName(id: string, locale: string): Promise { - const entry = (await allIngredients()).find((i) => i.id === id); +/** Alle Zutaten; mit client (withHousehold) auch die eigenen des Haushalts. */ +export async function allIngredients(client?: PoolClient): Promise { + const global = await globalIngredients(); + if (!client) return global; + const own = (await client.query(`select ${COLUMNS}, true as own from ingredients where household_id is not null order by key`)).rows as IngredientEntry[]; + return own.length ? [...global, ...own] : global; +} + +export async function ingredientName(id: string, locale: string, client?: PoolClient): Promise { + const entry = (await allIngredients(client)).find((i) => i.id === id); return entry?.names[locale] ?? entry?.names.en ?? ""; } + +export class OwnIngredientRefused extends Error {} + +/** + * Eigene Zutat für den Haushalt anlegen (26.11.38). Gehört sie zu einer Gruppe, + * steht sie im Regal der Gruppe; sonst im gewählten. Den Namen gibt es danach in + * jeder Sprache gleich — der Haushalt hat ihn so geschrieben. + */ +export async function createOwnIngredient( + client: PoolClient, + householdId: string, + input: { name: string; unit: "g" | "ml" | "piece"; parentId: string | null; category: string }, +): Promise { + const name = input.name.trim(); + const all = await allIngredients(client); + const lower = name.toLocaleLowerCase("de"); + if (all.some((e) => Object.values(e.names).some((n) => n.toLocaleLowerCase("de") === lower))) throw new OwnIngredientRefused("exists"); + const parent = input.parentId ? all.find((e) => e.id === input.parentId && e.isGroup) : null; + if (input.parentId && !parent) throw new OwnIngredientRefused("group"); + const names = { de: name, en: name, fr: name, es: name }; + const { rows } = await client.query( + `insert into ingredients (key, category, default_unit, names, synonyms, household_id, parent_id) + values ('own_' || replace(gen_random_uuid()::text, '-', ''), $1, $2, $3, '{}', $4, $5) + returning ${COLUMNS}, true as own`, + [parent?.category ?? input.category, input.unit, JSON.stringify(names), householdId, parent?.id ?? null], + ); + return rows[0] as IngredientEntry; +} diff --git a/lib/pricing.ts b/lib/pricing.ts index 455ef6f..1380126 100644 --- a/lib/pricing.ts +++ b/lib/pricing.ts @@ -41,6 +41,30 @@ export function currentPrices(points: PricePoint[]): Map { return best; } +/** + * Produktgruppen (26.11.38): Hat ein Oberbegriff („Pasta“) keinen besseren Preis als + * seine Sorten, gilt der Schnitt der Sorten mit dem besten Rang (Bon vor Richtpreis), + * in derselben Einheit. Wer Spaghetti per Bon kennt, kennt damit auch „Pasta“. + */ +export function withGroupPrices(prices: Map, members: Map): Map { + const out = new Map(prices); + for (const [groupId, ids] of members) { + const own = prices.get(groupId); + const known = ids.map((id) => prices.get(id)).filter((p): p is PricePoint => !!p && (!own || p.unit === own.unit)); + if (!known.length) continue; + const best = Math.max(...known.map(rank)); + if (own && rank(own) >= best) continue; + const top = known.filter((p) => rank(p) === best); + out.set(groupId, { + ...top[0]!, + ingredientId: groupId, + pricePerUnit: top.reduce((sum, p) => sum + p.pricePerUnit, 0) / top.length, + observedAt: top.map((p) => p.observedAt).sort().at(-1)!, + }); + } + return out; +} + export function dishCost(lines: CostLine[], prices: Map): DishCost { const own = lines.filter((l) => !l.staple); let sum = 0; diff --git a/lib/receipts.ts b/lib/receipts.ts index 259bc00..0600b81 100644 --- a/lib/receipts.ts +++ b/lib/receipts.ts @@ -61,7 +61,7 @@ Never use a key that is not listed for that line.`; /** Vorschläge je Zeile: gelernt → Produkt eines Gerichts → Suche → (gesammelt) AI. */ export async function suggestLines(client: PoolClient, lines: string[], locale: string, ai: Awaited>): Promise { - const list = await allIngredients(); + const list = await allIngredients(client); const byId = new Map(list.map((e) => [e.id, e])); const aliases = new Map( (await client.query("select raw_text_normalized as k, ingredient_id as i, pack_qty::float as q, pack_unit as u from ingredient_aliases")).rows.map((r) => [r.k as string, r]), @@ -236,7 +236,7 @@ export async function getReceipt(client: PoolClient, id: string, locale: string) ) ).rows[0]; if (!receipt) return null; - const names = new Map((await allIngredients()).map((e) => [e.id, e])); + const names = new Map((await allIngredients(client)).map((e) => [e.id, e])); const lines: ReviewLine[] = ( await client.query( `select id, raw_text as text, qty::float, total_price::float as "totalPrice", ingredient_id as "ingredientId", @@ -269,7 +269,7 @@ export async function confirmReceipt( ): Promise { const receipt = (await client.query("select status, photo_path, created_at from receipts where id = $1 for update", [id])).rows[0]; if (!receipt || receipt.status !== "review") throw new ReceiptRefused("status"); - const units = new Map((await allIngredients()).map((e) => [e.id, e.unit])); + const units = new Map((await allIngredients(client)).map((e) => [e.id, e.unit])); const when = input.purchasedAt ?? receipt.created_at.toISOString().slice(0, 10); await client.query("update receipts set store_id = $2, purchased_at = $3::date::timestamptz where id = $1", [id, input.storeId, when]); for (const d of input.decisions) { diff --git a/lib/recipe-draft.ts b/lib/recipe-draft.ts index 5714b32..2f999bb 100644 --- a/lib/recipe-draft.ts +++ b/lib/recipe-draft.ts @@ -2,6 +2,7 @@ import "server-only"; import type { AiSettings } from "./ai"; import { INPUT_UNITS, stepIngredient } from "./dishes"; import { standardizeSteps } from "./recipe-standardize"; +import { withHousehold } from "./db"; import { allIngredients } from "./ingredients"; import { matchLines, type RawRecipe } from "./recipe-import"; import { toBase } from "./units"; @@ -11,9 +12,10 @@ import { toBase } from "./units"; export async function draftFromRecipe( recipe: RawRecipe, locale: string, - extra: { sourceUrl?: string | null; imageUrl?: string | null; ai?: AiSettings | null } = {}, + extra: { sourceUrl?: string | null; imageUrl?: string | null; ai?: AiSettings | null; householdId?: string } = {}, ) { - const all = await allIngredients(); + // Mit Haushalt auch seine eigenen Zutaten (26.11.38). + const all = extra.householdId ? await withHousehold(extra.householdId, (c) => allIngredients(c)) : await allIngredients(); const lines = matchLines(recipe.ingredients, all, locale); // Schritte in die Hausform (Abschnitte, eine Handlung je Schritt, Timer aus der Quelle). const byId = new Map(all.map((e) => [e.id, e])); diff --git a/lib/shopping.ts b/lib/shopping.ts index 5b98f52..741abb4 100644 --- a/lib/shopping.ts +++ b/lib/shopping.ts @@ -58,10 +58,13 @@ export async function syncList(client: PoolClient, householdId: string, round: R (i.pantry_default or exists (select 1 from pantry_staples p where p.ingredient_id = i.id)) as pantry, coalesce(i.names ->> $2, i.names ->> 'de', i.key) as name, coalesce(i.forms -> $2, i.forms -> 'en') as form, - di.product, di.product_pack::float as product_pack + -- Produkt am Gericht, sonst das Lieblingsprodukt des Haushalts (26.11.38). + coalesce(di.product, hp.product) as product, + (case when di.product is not null then di.product_pack else hp.product_pack end)::float as product_pack from slots s join dishes d on d.id = s.dish_id join dish_ingredients di on di.dish_id = d.id join ingredients i on i.id = di.ingredient_id + left join household_products hp on hp.ingredient_id = di.ingredient_id where s.round_id = $1 and s.cooked_at is null order by s.position`, [round.id, locale], diff --git a/messages/de.json b/messages/de.json index 8b54932..e15bb4e 100644 --- a/messages/de.json +++ b/messages/de.json @@ -387,7 +387,10 @@ "productPack": "Packung in {unit}", "productCook": "Kochzeit (Min.)", "productHint": "Die Kochzeit wird zum Timer im Schritt, der die Zutat kocht; Name und Packung stehen auf der Einkaufsliste.", - "addProduct": "Produkt hinterlegen" + "addProduct": "Produkt hinterlegen", + "rememberProduct": "Für alle Gerichte mit {name} merken", + "inheritedProduct": "Euer Produkt für alle Gerichte: {product}", + "otherProduct": "Anderes Produkt für dieses Gericht" }, "addLinkText": "Wir lesen Zutaten und Schritte von der Rezeptseite.", "link": { @@ -969,5 +972,45 @@ "unlockText": "Danach zeigt dieses Gerät die Rezepte und den Plan von {household} — groß, zum Ablesen beim Kochen. Ändern kann man hier nichts.", "linkExpiredTitle": "Link abgelaufen", "linkExpiredText": "Dieser Link gilt nicht mehr. Ein Admin kann unter „Mehr“ › „Küchendisplay“ einen neuen erstellen." + }, + "ingredients": { + "categories": { + "vegetables": "Gemüse", + "fruit": "Obst", + "herbs": "Kräuter", + "bakery": "Brot & Backwaren", + "meat": "Fleisch", + "poultry": "Geflügel", + "sausage": "Wurst & Aufschnitt", + "fish": "Fisch", + "dairy": "Milchprodukte", + "cheese": "Käse", + "eggs": "Eier", + "chilled": "Kühlregal", + "frozen": "Tiefkühl", + "pasta_rice": "Nudeln, Reis & Hülsenfrüchte", + "canned": "Konserven & Gläser", + "sauces": "Saucen & Würzpasten", + "spices": "Gewürze", + "oil_vinegar": "Öl & Essig", + "baking": "Backen", + "breakfast": "Frühstück", + "nuts": "Nüsse & Trockenobst", + "sweets": "Süßes & Snacks", + "drinks": "Getränke" + }, + "title": "Neue Zutat", + "create": "„{name}“ als neue Zutat anlegen", + "name": "Name", + "unit": "Einheit", + "group": "Gehört zu", + "noGroup": "keiner Gruppe", + "category": "Regal im Laden", + "save": "Anlegen", + "cancel": "Abbrechen", + "error": "Das hat nicht geklappt. Gibt es die Zutat schon?", + "anyKind": "beliebige Sorte", + "kinds": "{n, plural, one {1 Sorte} other {# Sorten}}", + "ownBadge": "eigene" } } diff --git a/messages/en.json b/messages/en.json index 2bc0f5a..0343a13 100644 --- a/messages/en.json +++ b/messages/en.json @@ -387,7 +387,10 @@ "productPack": "Pack in {unit}", "productCook": "Cooking time (min)", "productHint": "The cooking time becomes the timer of the step that cooks this ingredient; name and pack go on the shopping list.", - "addProduct": "Add product" + "addProduct": "Add product", + "rememberProduct": "Remember for every dish with {name}", + "inheritedProduct": "Your product for every dish: {product}", + "otherProduct": "Different product for this dish" }, "addLinkText": "We read ingredients and steps from the recipe page.", "link": { @@ -969,5 +972,45 @@ "unlockText": "This device will then show the recipes and plan of {household} — large, for reading while cooking. Nothing can be changed here.", "linkExpiredTitle": "Link expired", "linkExpiredText": "This link is no longer valid. An admin can create a new one under “More” › “Kitchen display”." + }, + "ingredients": { + "categories": { + "vegetables": "Vegetables", + "fruit": "Fruit", + "herbs": "Herbs", + "bakery": "Bread & bakery", + "meat": "Meat", + "poultry": "Poultry", + "sausage": "Sausage & cold cuts", + "fish": "Fish", + "dairy": "Dairy", + "cheese": "Cheese", + "eggs": "Eggs", + "chilled": "Chilled", + "frozen": "Frozen", + "pasta_rice": "Pasta, rice & pulses", + "canned": "Tins & jars", + "sauces": "Sauces & pastes", + "spices": "Spices", + "oil_vinegar": "Oil & vinegar", + "baking": "Baking", + "breakfast": "Breakfast", + "nuts": "Nuts & dried fruit", + "sweets": "Sweets & snacks", + "drinks": "Drinks" + }, + "title": "New ingredient", + "create": "Add “{name}” as a new ingredient", + "name": "Name", + "unit": "Unit", + "group": "Belongs to", + "noGroup": "no group", + "category": "Shelf in the store", + "save": "Add", + "cancel": "Cancel", + "error": "That did not work. Does the ingredient exist already?", + "anyKind": "any kind", + "kinds": "{n, plural, one {1 kind} other {# kinds}}", + "ownBadge": "own" } } diff --git a/messages/es.json b/messages/es.json index e9ab7b8..f942621 100644 --- a/messages/es.json +++ b/messages/es.json @@ -387,7 +387,10 @@ "productPack": "Paquete en {unit}", "productCook": "Cocción (min)", "productHint": "El tiempo de cocción pasa a ser el temporizador del paso que cuece el ingrediente; nombre y paquete van a la lista de la compra.", - "addProduct": "Indicar producto" + "addProduct": "Indicar producto", + "rememberProduct": "Remember for every dish with {name}", + "inheritedProduct": "Your product for every dish: {product}", + "otherProduct": "Different product for this dish" }, "addLinkText": "Leemos los ingredientes y los pasos de la página de la receta.", "link": { @@ -969,5 +972,45 @@ "unlockText": "This device will then show the recipes and plan of {household} — large, for reading while cooking. Nothing can be changed here.", "linkExpiredTitle": "Link expired", "linkExpiredText": "This link is no longer valid. An admin can create a new one under “More” › “Kitchen display”." + }, + "ingredients": { + "categories": { + "vegetables": "Vegetables", + "fruit": "Fruit", + "herbs": "Herbs", + "bakery": "Bread & bakery", + "meat": "Meat", + "poultry": "Poultry", + "sausage": "Sausage & cold cuts", + "fish": "Fish", + "dairy": "Dairy", + "cheese": "Cheese", + "eggs": "Eggs", + "chilled": "Chilled", + "frozen": "Frozen", + "pasta_rice": "Pasta, rice & pulses", + "canned": "Tins & jars", + "sauces": "Sauces & pastes", + "spices": "Spices", + "oil_vinegar": "Oil & vinegar", + "baking": "Baking", + "breakfast": "Breakfast", + "nuts": "Nuts & dried fruit", + "sweets": "Sweets & snacks", + "drinks": "Drinks" + }, + "title": "New ingredient", + "create": "Add “{name}” as a new ingredient", + "name": "Name", + "unit": "Unit", + "group": "Belongs to", + "noGroup": "no group", + "category": "Shelf in the store", + "save": "Add", + "cancel": "Cancel", + "error": "That did not work. Does the ingredient exist already?", + "anyKind": "any kind", + "kinds": "{n, plural, one {1 kind} other {# kinds}}", + "ownBadge": "own" } } diff --git a/messages/fr.json b/messages/fr.json index 6132083..a9f1454 100644 --- a/messages/fr.json +++ b/messages/fr.json @@ -387,7 +387,10 @@ "productPack": "Paquet en {unit}", "productCook": "Cuisson (min)", "productHint": "Le temps de cuisson devient le minuteur de l'étape qui cuit l'ingrédient ; nom et paquet vont sur la liste de courses.", - "addProduct": "Indiquer un produit" + "addProduct": "Indiquer un produit", + "rememberProduct": "Remember for every dish with {name}", + "inheritedProduct": "Your product for every dish: {product}", + "otherProduct": "Different product for this dish" }, "addLinkText": "Nous lisons les ingrédients et les étapes sur la page de la recette.", "link": { @@ -969,5 +972,45 @@ "unlockText": "This device will then show the recipes and plan of {household} — large, for reading while cooking. Nothing can be changed here.", "linkExpiredTitle": "Link expired", "linkExpiredText": "This link is no longer valid. An admin can create a new one under “More” › “Kitchen display”." + }, + "ingredients": { + "categories": { + "vegetables": "Vegetables", + "fruit": "Fruit", + "herbs": "Herbs", + "bakery": "Bread & bakery", + "meat": "Meat", + "poultry": "Poultry", + "sausage": "Sausage & cold cuts", + "fish": "Fish", + "dairy": "Dairy", + "cheese": "Cheese", + "eggs": "Eggs", + "chilled": "Chilled", + "frozen": "Frozen", + "pasta_rice": "Pasta, rice & pulses", + "canned": "Tins & jars", + "sauces": "Sauces & pastes", + "spices": "Spices", + "oil_vinegar": "Oil & vinegar", + "baking": "Baking", + "breakfast": "Breakfast", + "nuts": "Nuts & dried fruit", + "sweets": "Sweets & snacks", + "drinks": "Drinks" + }, + "title": "New ingredient", + "create": "Add “{name}” as a new ingredient", + "name": "Name", + "unit": "Unit", + "group": "Belongs to", + "noGroup": "no group", + "category": "Shelf in the store", + "save": "Add", + "cancel": "Cancel", + "error": "That did not work. Does the ingredient exist already?", + "anyKind": "any kind", + "kinds": "{n, plural, one {1 kind} other {# kinds}}", + "ownBadge": "own" } } diff --git a/olares/Chart.yaml b/olares/Chart.yaml index 85d0090..261cd8e 100644 --- a/olares/Chart.yaml +++ b/olares/Chart.yaml @@ -2,5 +2,5 @@ apiVersion: v2 name: lunch description: foodplanhero (Plan. Cook. Smile.) — die Familie entscheidet gemeinsam, was es gibt; aus dem Plan entsteht die Einkaufsliste type: application -version: 26.11.37 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen -appVersion: "26.11.37" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran +version: 26.11.38 # YY.M. wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen +appVersion: "26.11.38" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran diff --git a/olares/OlaresManifest.yaml b/olares/OlaresManifest.yaml index c4a898e..e7757ff 100644 --- a/olares/OlaresManifest.yaml +++ b/olares/OlaresManifest.yaml @@ -1,5 +1,5 @@ # ============================================================================ -# OlaresManifest.yaml — foodplanhero (lunch, bis 26.11.37 „Was gibt's?“) +# OlaresManifest.yaml — foodplanhero (lunch, bis 26.11.34 „Was gibt's?“) # # Linter-Regeln, die hier zwingend gelten (scripts/check-chart.sh): # - metadata.name, metadata.appid, Chart.yaml.name und der Ordnername @@ -21,7 +21,7 @@ metadata: title: foodplanhero description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box. icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png - version: 26.11.37 + version: 26.11.38 categories: - Applications @@ -61,7 +61,7 @@ permission: appData: true spec: - versionName: '26.11.37' + versionName: '26.11.38' featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png promoteImage: diff --git a/olares/markt/26.11.38.md b/olares/markt/26.11.38.md new file mode 100644 index 0000000..f8db262 --- /dev/null +++ b/olares/markt/26.11.38.md @@ -0,0 +1,5 @@ +# Pasta, rice, cheese and pulses as groups +v26.11.38: Ingredients now have umbrella terms. Searching for "Nudeln" shows "Pasta · any kind" first, followed by every kind: spaghetti, penne, fusilli and the rest. The same works for rice, cheese, and lentils and pulses. A dish can call for any pasta, or for a particular kind. Anyone who maintains dishes can add an ingredient that is missing, either inside a group or on a shelf of its own. These ingredients are visible only to your household. Each household can also remember a favourite product, such as "Barilla Spaghetti No. 5". Every dish with that ingredient then puts it on the shopping list, unless a dish names its own product. A group's price is the average of its kinds. + +## Deutsch +v26.11.38: Zutaten haben jetzt Oberbegriffe. Wer „Nudeln“ sucht, sieht zuerst „Pasta · beliebige Sorte“ und darunter alle Sorten: Spaghetti, Penne, Fusilli und die übrigen. Genauso geht es bei Reis, Käse sowie Linsen und Hülsenfrüchten. Ein Gericht kann beliebige Pasta verlangen oder eine bestimmte Sorte. Wer Gerichte pflegt, kann eine fehlende Zutat selbst anlegen, in einer Gruppe oder in einem eigenen Regal. Diese Zutaten sieht nur der eigene Haushalt. Jeder Haushalt kann sich außerdem ein Lieblingsprodukt merken, etwa „Barilla Spaghetti Nr. 5“. Jedes Gericht mit dieser Zutat setzt es dann auf die Einkaufsliste, es sei denn, ein Gericht nennt ein eigenes Produkt. Der Preis einer Gruppe ist der Durchschnitt ihrer Sorten. diff --git a/scripts/seed.mjs b/scripts/seed.mjs index e542a48..7b6e06d 100644 --- a/scripts/seed.mjs +++ b/scripts/seed.mjs @@ -42,15 +42,23 @@ export async function seed(client) { await client.query("select set_config('app.maintenance', 'on', true)"); if (ingredients.length) { await client.query( - `insert into ingredients (id, key, category, default_unit, names, synonyms, freshness, pack_sizes, pantry_default, forms) - select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry, coalesce(x.forms, '{}') + `insert into ingredients (id, key, category, default_unit, names, synonyms, freshness, pack_sizes, pantry_default, forms, is_group) + select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry, coalesce(x.forms, '{}'), coalesce(x."group", false) from jsonb_to_recordset($1::jsonb) as x(id uuid, key text, category text, unit text, names jsonb, - synonyms text[], freshness smallint, packs numeric[], pantry boolean, forms jsonb) + synonyms text[], freshness smallint, packs numeric[], pantry boolean, forms jsonb, "group" boolean) on conflict (key) do update set category = excluded.category, default_unit = excluded.default_unit, names = excluded.names, synonyms = excluded.synonyms, freshness = excluded.freshness, - pack_sizes = excluded.pack_sizes, pantry_default = excluded.pantry_default, forms = excluded.forms`, + pack_sizes = excluded.pack_sizes, pantry_default = excluded.pantry_default, forms = excluded.forms, + is_group = excluded.is_group`, [JSON.stringify(ingredients.map((i) => ({ ...i, id: idByKey.get(i.key) })))], ); + // Produktgruppen (26.11.38): Sorten zeigen auf ihren Oberbegriff („spaghetti“ → „pasta“). + await client.query( + `update ingredients i set parent_id = g.id + from jsonb_to_recordset($1::jsonb) as x(key text, parent text) join ingredients g on g.key = x.parent + where i.key = x.key and i.parent_id is distinct from g.id`, + [JSON.stringify(ingredients.filter((i) => i.parent).map((i) => ({ key: i.key, parent: i.parent })))], + ); } // Richtpreise: Euro je übliche Menge → je Basiseinheit der Zutat. @@ -63,6 +71,16 @@ export async function seed(client) { join ingredients i on i.key = x.key`, [JSON.stringify(pricesDe.prices), pricesDe.currency], ); + // Ein Oberbegriff kostet im Schnitt seiner Sorten (gleiche Einheit), bis ein Bon mehr weiß. + await client.query( + `insert into default_prices (ingredient_id, currency, price_per_unit, unit) + select g.id, $1, avg(dp.price_per_unit), g.default_unit + from ingredients g join ingredients m on m.parent_id = g.id + join default_prices dp on dp.ingredient_id = m.id and dp.currency = $1 and dp.unit = g.default_unit + where g.is_group and not exists (select 1 from default_prices x where x.ingredient_id = g.id and x.currency = $1) + group by g.id, g.default_unit`, + [pricesDe.currency], + ); } await client.query("delete from starter_dishes where not (key = any($1::text[]))", [starters.map((s) => s.key)]); diff --git a/tests/fixture.ts b/tests/fixture.ts index 20ae6ae..d4be581 100644 --- a/tests/fixture.ts +++ b/tests/fixture.ts @@ -7,7 +7,7 @@ export const SEEDED_TABLES = [ "households", "members", "passkeys", "sessions", "invitations", "stores", "store_aisles", "dishes", "dish_ingredients", "dish_steps", "dish_translations", "rounds", "wishes", "slots", "shopping_items", "pantry_staples", "receipts", "receipt_lines", "ingredient_aliases", "price_points", "ratings", "kudos", - "helper_points", "achievements", "household_ai", "kid_devices", "dish_photos", + "helper_points", "achievements", "household_ai", "kid_devices", "dish_photos", "ingredients", "household_products", ]; /** Eine globale Zutat, wie sie eine Seed-Migration anlegt. */ @@ -86,6 +86,8 @@ export async function seedHousehold(client: pg.Client | pg.PoolClient, h: string await q("insert into helper_points (household_id, member_id, points, granted_by) values ($1, $2, 1, $2)", [h, member]); await q("insert into achievements (household_id, key) values ($1, 'first_round')", [h]); await q("insert into kid_devices (household_id, label, token_hash, created_by) values ($1, 'Tablet', sha256(convert_to($2, 'utf8')), $3)", [h, `kid-${h}`, member]); + const own = (await q("insert into ingredients (key, category, default_unit, names, household_id) values ($1, 'pasta_rice', 'g', '{\"de\":\"Gnocchi\"}', $2) returning id", [`own_${h.replace(/-/g, "")}`, h])).rows[0].id; + await q("insert into household_products (household_id, ingredient_id, product) values ($1, $2, 'Barilla Nr. 5')", [h, own]); await q("insert into household_ai (household_id, endpoint, vision_model, updated_by) values ($1, 'http://llm.test/v1', 'vision', $2)", [h, member]); await q("commit"); return { dish, member }; diff --git a/tests/ingredient-groups.test.ts b/tests/ingredient-groups.test.ts new file mode 100644 index 0000000..f9a3a3f --- /dev/null +++ b/tests/ingredient-groups.test.ts @@ -0,0 +1,94 @@ +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", () => ({})); + +// Produktgruppen und eigene Zutaten (26.11.38): Pasta, Reis, Käse, Hülsenfrüchte +// sind Oberbegriffe mit Sorten. Eigene Zutaten sieht nur der eigene Haushalt, +// ein gemerktes Produkt gilt für alle Gerichte des Haushalts. +const url = process.env.TEST_DATABASE_URL; + +describe.skipIf(!url)("ingredient groups", () => { + const client = new pg.Client({ connectionString: url }); + const a = randomUUID(); + const b = randomUUID(); + let member = ""; + const ing: Record = {}; + let ingredients: typeof import("@/lib/ingredients"); + let dishes: typeof import("@/lib/dishes"); + + async function as(h: string, fn: () => Promise): Promise { + 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 ('pasta','spaghetti','penne','gouda','ground_beef')")).rows) ing[r.key] = r.id; + ingredients = await import("@/lib/ingredients"); + dishes = 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(); + }); + + it("the seed knows the groups and their kinds", async () => { + const r = await client.query("select key from ingredients where parent_id = $1 order by key", [ing.pasta]); + expect(r.rows.map((x) => x.key)).toEqual(expect.arrayContaining(["spaghetti", "penne", "fusilli"])); + expect((await client.query("select is_group from ingredients where id = $1", [ing.pasta])).rows[0].is_group).toBe(true); + }); + + it("an own ingredient is seen only by its household and refuses duplicates and non-groups", async () => { + const name = `Gnocchi ${a.slice(0, 6)}`; + const own = await as(a, () => ingredients.createOwnIngredient(client as never, a, { name, unit: "g", parentId: ing.pasta!, category: "other" })); + expect(own).toMatchObject({ parentId: ing.pasta, own: true }); + expect(own.category).toBe("pasta_rice"); + const mine = await as(a, () => ingredients.allIngredients(client as never)); + expect(mine.some((i) => i.id === own.id)).toBe(true); + const theirs = await as(b, () => ingredients.allIngredients(client as never)); + expect(theirs.some((i) => i.id === own.id)).toBe(false); + await expect(as(a, () => ingredients.createOwnIngredient(client as never, a, { name: name.toUpperCase(), unit: "g", parentId: null, category: "other" }))).rejects.toThrow("exists"); + await expect(as(a, () => ingredients.createOwnIngredient(client as never, a, { name: "Etwas", unit: "g", parentId: ing.spaghetti!, category: "other" }))).rejects.toThrow("group"); + // Eine Gruppe anlegen darf ein Haushalt nicht, auch nicht an der Bibliothek vorbei. + await expect( + as(a, () => client.query("insert into ingredients (key, category, default_unit, names, household_id, is_group) values ($1, 'other', 'g', '{}', $2, true)", [`own_x${a.slice(0, 8)}`, a])), + ).rejects.toThrow(); + }); + + it("a remembered product is used by every other dish of the household, not by others", async () => { + const dish = (product: object | null) => ({ + title: "Nudeln mit Soße", + portions: 4, + base: null, + tags: [], + effortMinutes: 20, + isTrial: false, + ingredients: [{ ingredientId: ing.spaghetti!, qty: 500, unit: "g" as const, product }], + steps: [{ text: "Nudeln kochen.", timerMinutes: null }], + }); + await as(a, () => dishes.saveDish(client as never, a, member, dish({ name: "Barilla Spaghetti Nr. 5", pack: 500, cookMinutes: 9, remember: true }) as never)); + const other = await as(a, () => dishes.saveDish(client as never, a, member, dish(null) as never)); + const got = await as(a, () => dishes.getDish(client as never, other, "de")); + expect(got!.ingredients[0]!.product).toMatchObject({ name: "Barilla Spaghetti Nr. 5", fromHousehold: true, cookMinutes: 9 }); + // Ein eigenes Produkt am Gericht schlägt das gemerkte. + const own = await as(a, () => dishes.saveDish(client as never, a, member, dish({ name: "De Cecco", pack: 500, cookMinutes: 11 }) as never)); + expect((await as(a, () => dishes.getDish(client as never, own, "de")))!.ingredients[0]!.product).toMatchObject({ name: "De Cecco" }); + expect((await as(a, () => dishes.getDish(client as never, own, "de")))!.ingredients[0]!.product!.fromHousehold).toBeFalsy(); + expect((await as(b, () => client.query("select count(*)::int as n from household_products where ingredient_id = $1", [ing.spaghetti]))).rows[0].n).toBe(0); + }); +}); diff --git a/tests/ingredient-search.test.ts b/tests/ingredient-search.test.ts index 744e77c..db96897 100644 --- a/tests/ingredient-search.test.ts +++ b/tests/ingredient-search.test.ts @@ -3,7 +3,12 @@ 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; synonyms: string[] }) => ({ ...i, id: i.key }), + (i: { key: string; unit: "g"; category: string; names: Record; synonyms: string[]; group?: boolean; parent?: string }) => ({ + ...i, + id: i.key, + isGroup: !!i.group, + parentId: i.parent ?? null, + }), ); const keys = (q: string, l = "de") => searchIngredients(list, q, l).map((i) => i.key); @@ -28,4 +33,22 @@ describe("ingredient search", () => { expect(keys("")).toEqual([]); expect(searchIngredients(list, "e", "de", 5)).toHaveLength(5); }); + + it("a group term brings the group first and every kind under it (26.11.38)", () => { + const hits = keys("Nudeln"); + expect(hits[0]).toBe("pasta"); + // Spaghetti und Penne heißen nicht „Nudeln“ und kommen trotzdem. + for (const k of ["spaghetti", "penne", "fusilli", "macaroni", "lasagne_sheets"]) expect(hits).toContain(k); + // Asiatische Nudeln bleiben als Treffer, nach den Sorten der Gruppe. + expect(hits.indexOf("egg_noodles")).toBeGreaterThan(hits.indexOf("spaghetti")); + expect(keys("Käse")[0]).toBe("cheese"); + expect(keys("Linsen")).toEqual(expect.arrayContaining(["legumes", "red_lentils", "chickpeas"])); + expect(keys("Reis")[0]).toBe("rice"); + }); + + it("a single kind is still found directly", () => { + expect(keys("spagh")[0]).toBe("spaghetti"); + expect(keys("Fusilli")[0]).toBe("fusilli"); + }); }); + diff --git a/tests/pricing.test.ts b/tests/pricing.test.ts index a79a867..46dce40 100644 --- a/tests/pricing.test.ts +++ b/tests/pricing.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { currentPrices, dishCost, expensiveAllowed, priceClasses, traffic, type PricePoint } from "@/lib/pricing"; +import { currentPrices, withGroupPrices, dishCost, expensiveAllowed, priceClasses, traffic, type PricePoint } from "@/lib/pricing"; const p = (id: string, price: number, over: Partial = {}): PricePoint => ({ ingredientId: id, pricePerUnit: price, unit: "g", source: "default", observedAt: "2026-11-01", mainStore: false, ...over, @@ -55,3 +55,19 @@ describe("pricing", () => { expect(expensiveAllowed(2, 4)).toBe(1); }); }); + +describe("group prices (26.11.38)", () => { + const p = (ingredientId: string, pricePerUnit: number, source: "receipt" | "default", observedAt = "2026-11-01"): PricePoint => ({ + ingredientId, pricePerUnit, unit: "g", source, observedAt, mainStore: false, + }); + it("a group without a better price takes the mean of its kinds' best prices", () => { + const prices = new Map([["pasta", p("pasta", 0.003, "default")], ["spaghetti", p("spaghetti", 0.0036, "receipt", "2026-11-06")], ["penne", p("penne", 0.0024, "receipt")], ["fusilli", p("fusilli", 0.01, "default")]]); + const out = withGroupPrices(prices, new Map([["pasta", ["spaghetti", "penne", "fusilli"]]])); + expect(out.get("pasta")).toMatchObject({ source: "receipt", observedAt: "2026-11-06" }); + expect(out.get("pasta")!.pricePerUnit).toBeCloseTo(0.003, 6); + }); + it("keeps a group's own receipt price", () => { + const prices = new Map([["pasta", p("pasta", 0.005, "receipt")], ["spaghetti", p("spaghetti", 0.002, "receipt")]]); + expect(withGroupPrices(prices, new Map([["pasta", ["spaghetti"]]])).get("pasta")!.pricePerUnit).toBe(0.005); + }); +}); diff --git a/tests/rls.test.ts b/tests/rls.test.ts index ab78431..0b47047 100644 --- a/tests/rls.test.ts +++ b/tests/rls.test.ts @@ -100,7 +100,9 @@ describe.skipIf(!url)("row level security", () => { it("without a household nothing is visible", async () => { for (const table of [...tables, "households"]) { - const { rows } = await as(null, () => client.query(`select count(*)::int as n from ${table}`)); + // ingredients mischt globale Zeilen (für alle sichtbar) und eigene je Haushalt (26.11.38). + const where = table === "ingredients" ? "where household_id is not null" : ""; + const { rows } = await as(null, () => client.query(`select count(*)::int as n from ${table} ${where}`)); expect([table, rows[0].n]).toEqual([table, 0]); } }); -- 2.54.0