Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d875fa02e |
No files matched your search
@@ -7,7 +7,7 @@
|
||||
> **Plattform:** Olares One (Kubernetes), Repo und CI auf Gitea — kein Supabase,
|
||||
> kein Vercel (E-0001). Eigene Gestaltung, nicht AImighty (E-0002).
|
||||
> Verteilung über den Markt, Repo öffentlich (E-0005).
|
||||
> **Status:** 26.11.38 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
|
||||
> **Status:** 26.11.39 — alle neun Arbeitspakete aus `docs/PROJEKTSTART.md` sind gebaut:
|
||||
> Anmeldung (Passkeys, Kinder mit Gerät + PIN), Gerichte (Link, Kochbuchfoto, AI über den
|
||||
> Olares Router), Wünschen, Plan, Einkaufsliste (Echtzeit, offline), Kochmodus mit
|
||||
> Bewertung, Web-App; Einzahl bei Stück-Mengen (26.11.15), Preise und Kosten mit Ampel
|
||||
@@ -18,7 +18,8 @@
|
||||
> Führung (26.11.27), Präsentationsmodus und Küchendisplay (26.11.28),
|
||||
> lange Bons und Aldi (26.11.29), „Mein Gericht“ (26.11.30), Bons „nicht zum Kochen“
|
||||
> (26.11.33), foodplanhero für Maike (26.11.35), eine Schrift (26.11.37), Produktgruppen,
|
||||
> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015). Offen ist der
|
||||
> eigene Zutaten und Lieblingsprodukt je Haushalt (26.11.38, E-0015), Löffel und Gebinde
|
||||
> (26.11.39, E-0016). Offen ist der
|
||||
> Magic Link (braucht SMTP).
|
||||
> **Letzte Aktualisierung:** 7. November 2026
|
||||
|
||||
|
||||
+2
-2
@@ -21,7 +21,7 @@ metadata:
|
||||
title: foodplanhero
|
||||
description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
|
||||
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
version: 26.11.38
|
||||
version: 26.11.39
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -61,7 +61,7 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.38'
|
||||
versionName: '26.11.39'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
|
||||
@@ -4,12 +4,18 @@ import { DishForm } from "@/components/dishes/dish-form";
|
||||
import { requireSession } from "@/lib/auth/session";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { getDish } from "@/lib/dishes";
|
||||
import { fromBase, type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
// Bearbeiten zeigt die Mengen für vier Portionen (oder was man dort einträgt).
|
||||
const PORTIONS = 4;
|
||||
|
||||
function amountIn(qty: number, unit: BaseUnit, display: KitchenUnit | null, packSize: number | null) {
|
||||
const n = display ? fromBase(qty, display, unit, packSize) : null;
|
||||
return n === null ? { qty, unit } : { qty: Math.round(n * 100) / 100, unit: display as string };
|
||||
}
|
||||
|
||||
export default async function EditDishPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
if (!/^[0-9a-f-]{36}$/.test(id)) notFound();
|
||||
@@ -36,8 +42,9 @@ export default async function EditDishPage({ params }: { params: Promise<{ id: s
|
||||
isTrial: dish.isTrial,
|
||||
sourceUrl: dish.sourceUrl,
|
||||
ingredients: dish.ingredients.map((i) => ({
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit },
|
||||
qty: i.qtyPerPortion * PORTIONS,
|
||||
ingredient: { id: i.ingredientId, name: i.name, unit: i.unit, kitchenUnit: i.kitchenUnit, packKind: i.packKind, packSize: i.packSize },
|
||||
// Im Maß, in dem sie eingegeben wurde: „2 EL“, „1 Dose“ (26.11.39).
|
||||
...amountIn(i.qtyPerPortion * PORTIONS, i.unit, i.displayUnit, i.packSize),
|
||||
note: i.note,
|
||||
product: i.product,
|
||||
})),
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { z } from "zod";
|
||||
import { guardWrite, isResponse } from "@/lib/auth/guard";
|
||||
import { fail, json, readJson } from "@/lib/auth/http";
|
||||
import { PLANNERS } from "@/lib/auth/roles";
|
||||
import { withHousehold } from "@/lib/db";
|
||||
import { setPackSize } from "@/lib/ingredients";
|
||||
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
const body = z.object({ size: z.number().positive().max(100000) });
|
||||
|
||||
// Gebindegröße für den Haushalt (26.11.39): „bei uns hat die Dose 500 g“ — gilt für
|
||||
// alle Gerichte des Haushalts; ein Produkt mit Packung am Gericht geht vor.
|
||||
export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const session = await guardWrite(request, [...PLANNERS]);
|
||||
if (isResponse(session)) return session;
|
||||
const parsed = body.safeParse(await readJson(request));
|
||||
if (!parsed.success || !/^[0-9a-f-]{36}$/.test(id)) return fail("invalid", 400);
|
||||
const size = Math.round(parsed.data.size * 1000) / 1000;
|
||||
const ok = await withHousehold(session.householdId, (c) => setPackSize(c, session.householdId, id, size));
|
||||
return ok ? json({ size }) : fail("noPack", 404);
|
||||
}
|
||||
@@ -20,6 +20,10 @@ const view = (i: IngredientEntry, locale: string, all: IngredientEntry[], produc
|
||||
own: !!i.own,
|
||||
// Gemerktes Produkt des Haushalts — das Formular zeigt es gleich beim Wählen.
|
||||
product: products.get(i.id) ?? null,
|
||||
// Küchenmaß und Gebinde (26.11.39); die Größe mit der des Haushalts verrechnet.
|
||||
kitchenUnit: i.kitchenUnit ?? null,
|
||||
packKind: i.packKind ?? null,
|
||||
packSize: i.packSize ?? null,
|
||||
});
|
||||
|
||||
// Zutaten-Suche beim Tippen, in der Sprache der Person — mit den eigenen des
|
||||
|
||||
@@ -1,19 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { Pause, Play, Timer as TimerIcon } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import type { Section } from "@/lib/recipe-style";
|
||||
import { timerFromText } from "@/lib/timer";
|
||||
import { formatQuantity, type BaseUnit } from "@/lib/units";
|
||||
import { type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
// Gemeinsames von Kochmodus und Präsentation (26.11.28): Display an lassen,
|
||||
// Timer gegen die Uhr, Mengen in der Portionszahl.
|
||||
|
||||
export type Ingredient = { ingredientId: string; name: string; forms: { one: string; other: string } | null; qtyPerPortion: number; unit: BaseUnit; note: string | null };
|
||||
export type Ingredient = {
|
||||
ingredientId: string;
|
||||
name: string;
|
||||
forms: { one: string; other: string } | null;
|
||||
qtyPerPortion: number;
|
||||
unit: BaseUnit;
|
||||
note: string | null;
|
||||
displayUnit?: KitchenUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
export type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
export type Running = { step: number; endsAt: number | null; left: number; done: boolean };
|
||||
|
||||
@@ -98,12 +108,10 @@ export const withTextTimer = (s: Step): Step => ({ ...s, timerSeconds: s.timerSe
|
||||
|
||||
/** „250 g“ in der Portionszahl, und der passende Name (Einzahl/Mehrzahl). */
|
||||
export function useAmount(portions: number) {
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
return {
|
||||
amount: (i: Ingredient) => {
|
||||
const f = formatQuantity(i.qtyPerPortion * portions, i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
},
|
||||
// „2 EL (30 ml)“, „400 g (1 Dose)“ — lib/units.ts formatKitchen (26.11.39).
|
||||
amount: (i: Ingredient) => kitchen.text(i, i.qtyPerPortion * portions),
|
||||
label: (i: Ingredient) => labelFor(i, i.qtyPerPortion * portions),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,18 +2,19 @@
|
||||
|
||||
import { ArrowDown, ArrowUp, Plus, Sparkles, X, Package, Wand2 } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { BASES, TAGS } from "@/lib/categories";
|
||||
import { parseNumber, type BaseUnit } from "@/lib/units";
|
||||
import { formatQuantity, isPackKind, parseNumber, type BaseUnit } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
|
||||
import { IngredientPicker, type Picked } from "./ingredient-picker";
|
||||
import { PackSize } from "./pack-size";
|
||||
export { IngredientPicker, type Picked };
|
||||
// Produkt (optional): Name, Packung in der Einheit der Zeile, Kochzeit laut Packung.
|
||||
// inherited: Lieblingsprodukt des Haushalts für diese Zutat (26.11.38); remember: dieses Produkt für alle Gerichte merken.
|
||||
@@ -53,6 +54,19 @@ const UNITS_FOR: Record<BaseUnit, string[]> = {
|
||||
piece: ["piece"],
|
||||
};
|
||||
|
||||
/** Maße für eine Zutat: die ihrer Basiseinheit und, wenn sie eins hat, ihr Gebinde (26.11.39). */
|
||||
const unitsFor = (p: Picked | null) => {
|
||||
const list = UNITS_FOR[p?.unit ?? "g"];
|
||||
return p?.packKind && p.packSize ? [...list, p.packKind] : list;
|
||||
};
|
||||
|
||||
/**
|
||||
* Vorgewählte Einheit beim Wählen einer Zutat: ihr Löffelmaß (Olivenöl in EL), sonst
|
||||
* die Basiseinheit. Ein Gebinde wird angeboten, aber nie vorgewählt — wer nach
|
||||
* „Kokosmilch“ gleich „400“ tippt, meint Milliliter, nicht 400 Dosen.
|
||||
*/
|
||||
const preferredUnit = (p: Picked) => (p.kitchenUnit && unitsFor(p).includes(p.kitchenUnit) ? p.kitchenUnit : p.unit);
|
||||
|
||||
let counter = 0;
|
||||
const next = () => ++counter;
|
||||
|
||||
@@ -63,6 +77,11 @@ const formatQty = (n: number) => String(Math.round(n * 100) / 100).replace(".",
|
||||
// Portion um (lib/dishes.ts).
|
||||
export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
const t = useTranslations("dishes");
|
||||
const locale = useLocale();
|
||||
const sizeText = (size: number, unit: BaseUnit) => {
|
||||
const f = formatQuantity(size, unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""}`;
|
||||
};
|
||||
const router = useRouter();
|
||||
const [title, setTitle] = useState(initial?.title ?? "");
|
||||
const [portions, setPortions] = useState(String(initial?.portions ?? 4));
|
||||
@@ -76,7 +95,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
key: next(),
|
||||
ingredient: i.ingredient,
|
||||
qty: i.qty !== null ? formatQty(i.qty) : "",
|
||||
unit: i.unit && UNITS_FOR[i.ingredient.unit].includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
unit: i.unit && unitsFor(i.ingredient).includes(i.unit) ? i.unit : i.ingredient.unit,
|
||||
note: i.note ?? "",
|
||||
// Ein geerbtes Lieblingsprodukt füllt die Felder nicht — leer heißt: es gilt weiter.
|
||||
product: i.product && !i.product.fromHousehold ? i.product.name : "",
|
||||
@@ -282,7 +301,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
{rows.map((row) => (
|
||||
<li key={row.key} className="flex flex-col gap-2 rounded-2xl bg-muted p-3">
|
||||
<div className="flex items-start gap-2">
|
||||
<IngredientPicker canCreate value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: p.unit, inherited: row.product ? row.inherited : (p.product ?? null) })} />
|
||||
<IngredientPicker canCreate value={row.ingredient} onPick={(p) => update(row.key, { ingredient: p, unit: preferredUnit(p), inherited: row.product ? row.inherited : (p.product ?? null) })} />
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
@@ -308,13 +327,26 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
onChange={(e) => update(row.key, { unit: e.target.value })}
|
||||
className="min-h-11 rounded-xl border border-border bg-background px-3 text-base"
|
||||
>
|
||||
{UNITS_FOR[row.ingredient?.unit ?? "g"].map((u) => (
|
||||
{unitsFor(row.ingredient).map((u) => (
|
||||
<option key={u} value={u}>
|
||||
{t(`form.units.${u}`)}
|
||||
{/* Ein Gebinde nennt seine Größe gleich mit: „Dose (400 g)“. */}
|
||||
{isPackKind(u) && row.ingredient?.packSize
|
||||
? t("form.unitWithSize", { unit: t(`form.units.${u}`), size: sizeText(row.ingredient.packSize, row.ingredient.unit) })
|
||||
: t(`form.units.${u}`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
{row.ingredient && isPackKind(row.unit) && row.ingredient.packSize ? (
|
||||
<PackSize
|
||||
ingredient={row.ingredient}
|
||||
kind={row.unit}
|
||||
sizeText={sizeText}
|
||||
onSaved={(size) =>
|
||||
setRows((rs) => rs.map((r) => (r.ingredient?.id === row.ingredient!.id ? { ...r, ingredient: { ...r.ingredient!, packSize: size } } : r)))
|
||||
}
|
||||
/>
|
||||
) : null}
|
||||
<Input
|
||||
aria-label={t("form.note")}
|
||||
placeholder={t("form.notePlaceholder")}
|
||||
@@ -338,7 +370,7 @@ export function DishForm({ initial }: { initial?: DishFormValue }) {
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex flex-col gap-1">
|
||||
<Label htmlFor={`pack-${row.key}`} className="text-sm">
|
||||
{t("form.productPack", { unit: t(`form.units.${row.unit}`) })}
|
||||
{t("form.productPack", { unit: t(`form.units.${isPackKind(row.unit) ? (row.ingredient?.unit ?? "g") : row.unit}`) })}
|
||||
</Label>
|
||||
<Input id={`pack-${row.key}`} inputMode="decimal" value={row.pack} onChange={(e) => update(row.key, { pack: e.target.value })} />
|
||||
</div>
|
||||
|
||||
@@ -9,10 +9,19 @@ import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { CATEGORIES } from "@/lib/categories";
|
||||
import { normalize } from "@/lib/ingredient-search";
|
||||
import type { BaseUnit } from "@/lib/units";
|
||||
import type { BaseUnit, KitchenUnit, PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Picked = { id: string; name: string; unit: BaseUnit; group?: boolean; product?: string | null };
|
||||
export type Picked = {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: BaseUnit;
|
||||
group?: boolean;
|
||||
product?: string | null;
|
||||
kitchenUnit?: KitchenUnit | null;
|
||||
packKind?: PackKind | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
type Hit = Picked & { kinds: number; parentId: string | null; own: boolean };
|
||||
|
||||
// Zutat suchen und wählen (26.11.38): Ein Oberbegriff („Pasta“) steht oben als
|
||||
@@ -26,6 +35,8 @@ export function IngredientPicker({ value, onPick, canCreate = false }: { value:
|
||||
const [hits, setHits] = useState<Hit[]>([]);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [creating, setCreating] = useState(false);
|
||||
// Für welche Eingabe die Treffer gelten — „anlegen“ erst, wenn die Suche geantwortet hat.
|
||||
const [answered, setAnswered] = useState("");
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -36,19 +47,22 @@ export function IngredientPicker({ value, onPick, canCreate = false }: { value:
|
||||
if (timer.current) clearTimeout(timer.current);
|
||||
timer.current = setTimeout(async () => {
|
||||
const res = await fetch(`/api/ingredients?q=${encodeURIComponent(query)}`);
|
||||
if (res.ok) setHits(await res.json());
|
||||
if (res.ok) {
|
||||
setHits(await res.json());
|
||||
setAnswered(query);
|
||||
}
|
||||
}, 150);
|
||||
}, [query, open, value?.name]);
|
||||
|
||||
const pick = (h: Picked) => {
|
||||
onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null });
|
||||
onPick({ id: h.id, name: h.name, unit: h.unit, group: h.group, product: h.product ?? null, kitchenUnit: h.kitchenUnit, packKind: h.packKind, packSize: h.packSize });
|
||||
setQuery(h.name);
|
||||
setOpen(false);
|
||||
setCreating(false);
|
||||
};
|
||||
const groupIds = new Set(hits.filter((h) => h.group).map((h) => h.id));
|
||||
const exact = hits.some((h) => normalize(h.name) === normalize(query));
|
||||
const offerCreate = canCreate && query.trim().length >= 2 && !exact;
|
||||
const offerCreate = canCreate && query.trim().length >= 2 && !exact && answered === query;
|
||||
|
||||
return (
|
||||
<div className="relative flex-1">
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useId, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { ErrorNotice } from "@/components/ui/notice";
|
||||
import { parseNumber, type BaseUnit, type PackKind } from "@/lib/units";
|
||||
|
||||
// Größe eines Gebindes (26.11.39): „1 Dose = 400 g“ — wer Gerichte pflegt, kann sie
|
||||
// für den Haushalt ändern („unsere Dose hat 500 g“). Gilt für alle Gerichte.
|
||||
export function PackSize({
|
||||
ingredient,
|
||||
kind,
|
||||
sizeText,
|
||||
onSaved,
|
||||
}: {
|
||||
ingredient: { id: string; unit: BaseUnit; packSize?: number | null };
|
||||
kind: PackKind;
|
||||
sizeText: (size: number, unit: BaseUnit) => string;
|
||||
onSaved: (size: number) => void;
|
||||
}) {
|
||||
const t = useTranslations("dishes.form");
|
||||
const id = useId();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [value, setValue] = useState(String(ingredient.packSize ?? ""));
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState(false);
|
||||
const unit = t(`units.${kind}`);
|
||||
|
||||
async function save() {
|
||||
const size = parseNumber(value);
|
||||
if (!size || size <= 0) return setError(true);
|
||||
setBusy(true);
|
||||
setError(false);
|
||||
const res = await fetch(`/api/ingredients/${ingredient.id}/pack`, {
|
||||
method: "PUT",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ size }),
|
||||
}).catch(() => null);
|
||||
setBusy(false);
|
||||
if (!res?.ok) return setError(true);
|
||||
onSaved((await res.json()).size);
|
||||
setOpen(false);
|
||||
}
|
||||
|
||||
if (!open) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-x-3 text-sm text-muted-foreground">
|
||||
<span>{t("packSize", { unit, size: sizeText(ingredient.packSize ?? 0, ingredient.unit) })}</span>
|
||||
<Button type="button" variant="ghost" className="min-h-11" onClick={() => setOpen(true)}>
|
||||
{t("packChange")}
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className="flex flex-col gap-2 rounded-xl border border-border p-3">
|
||||
<Label htmlFor={id} className="text-sm">
|
||||
{t("packSizeLabel", { unit, base: t(`units.${ingredient.unit}`) })}
|
||||
</Label>
|
||||
<div className="flex gap-2">
|
||||
<Input id={id} inputMode="decimal" value={value} onChange={(e) => setValue(e.target.value)} className="flex-1" />
|
||||
<Button type="button" disabled={busy} onClick={save}>
|
||||
{t("packSave")}
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">{t("packHint")}</p>
|
||||
{error ? <ErrorNotice>{t("packError")}</ErrorNotice> : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,13 @@
|
||||
"use client";
|
||||
|
||||
import { Minus, Plus, Timer } from "lucide-react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { labelFor } from "@/lib/ingredient-name";
|
||||
import { SECTIONS, type Section } from "@/lib/recipe-style";
|
||||
import { formatQuantity, scale, type BaseUnit } from "@/lib/units";
|
||||
import { scale, type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
import { useKitchenAmount } from "@/lib/use-kitchen-amount";
|
||||
|
||||
type Ingredient = {
|
||||
ingredientId: string;
|
||||
@@ -17,6 +18,8 @@ type Ingredient = {
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
product?: { name: string } | null;
|
||||
displayUnit?: KitchenUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
type Step = { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string };
|
||||
|
||||
@@ -24,14 +27,11 @@ type Step = { section: Section; text: string; timerSeconds: number | null; ingre
|
||||
// rechnet lib/units.ts — gespeichert ist immer „pro Portion“.
|
||||
export function PortionScaler({ ingredients, steps, initialPortions }: { ingredients: Ingredient[]; steps: Step[]; initialPortions: number }) {
|
||||
const t = useTranslations("dishes.detail");
|
||||
const locale = useLocale();
|
||||
const kitchen = useKitchenAmount();
|
||||
const [portions, setPortions] = useState(initialPortions);
|
||||
const ts = useTranslations("dishes.sections");
|
||||
const byId = new Map(ingredients.map((i) => [i.ingredientId, i]));
|
||||
const amountOf = (i: Ingredient) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
return `${f.amount}${f.unit ? ` ${f.unit}` : ""} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
};
|
||||
const amountOf = (i: Ingredient) => `${kitchen.text(i, scale(i.qtyPerPortion, portions))} ${labelFor(i, scale(i.qtyPerPortion, portions))}`;
|
||||
// Durchgehend nummeriert, gegliedert nach Abschnitten (lib/recipe-style.ts).
|
||||
const numbered = steps.map((s, n) => ({ ...s, n: n + 1 }));
|
||||
|
||||
@@ -54,14 +54,12 @@ export function PortionScaler({ ingredients, steps, initialPortions }: { ingredi
|
||||
</div>
|
||||
<ul className="flex flex-col divide-y divide-border">
|
||||
{ingredients.map((i) => {
|
||||
const f = formatQuantity(scale(i.qtyPerPortion, portions), i.unit, locale);
|
||||
const f = kitchen.parts(i, scale(i.qtyPerPortion, portions));
|
||||
return (
|
||||
<li key={i.ingredientId} className="flex min-h-11 items-baseline gap-3 py-2">
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">
|
||||
{f.amount}
|
||||
{f.unit ? ` ${f.unit}` : ""}
|
||||
</span>
|
||||
<span className="w-20 shrink-0 text-right font-semibold tabular-nums">{f.main}</span>
|
||||
<span className="flex-1">
|
||||
{f.extra ? <span className="text-muted-foreground tabular-nums">({f.extra}) </span> : null}
|
||||
{labelFor(i, scale(i.qtyPerPortion, portions))}
|
||||
{i.note ? <span className="text-muted-foreground">, {i.note}</span> : null}
|
||||
{i.product ? <span className="block text-sm text-muted-foreground">{i.product.name}</span> : null}
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useLocale, useTranslations } from "next-intl";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { formatQuantity } from "@/lib/units";
|
||||
import { formatQuantity, type PackKind } from "@/lib/units";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type Item = {
|
||||
@@ -16,6 +16,8 @@ export type Item = {
|
||||
unit: "g" | "ml" | "piece" | null;
|
||||
packCount: number | null;
|
||||
packSize: number | null;
|
||||
/** Gebinde („2 Dosen à 400 g“), seit 26.11.39. */
|
||||
packKind?: PackKind | null;
|
||||
dishes: string[];
|
||||
aislePosition: number | null;
|
||||
manual: boolean;
|
||||
@@ -46,6 +48,7 @@ function writeQueue(ops: Op[]) {
|
||||
// Warteschlange im Browser und gehen raus, sobald wieder Netz da ist.
|
||||
export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles: Aisle[]; me: string }) {
|
||||
const t = useTranslations("shopping");
|
||||
const tm = useTranslations("measure");
|
||||
const locale = useLocale();
|
||||
const [items, setItems] = useState(initial);
|
||||
const [queue, setQueue] = useState<Op[]>([]);
|
||||
@@ -135,6 +138,7 @@ export function ShoppingList({ initial, aisles, me }: { initial: Item[]; aisles:
|
||||
if (i.unit === "piece") return t("pieces", { n: i.qty });
|
||||
if (i.packCount && i.packSize) {
|
||||
const f = formatQuantity(i.packSize, i.unit, locale);
|
||||
if (i.packKind) return t("packOf", { count: i.packCount, word: tm(i.packKind, { n: i.packCount }), size: `${f.amount} ${f.unit}` });
|
||||
return i.packCount > 1 ? `${i.packCount} × ${f.amount} ${f.unit}` : `${f.amount} ${f.unit}`;
|
||||
}
|
||||
const f = formatQuantity(i.qty, i.unit, locale);
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
-- Löffel und Gebinde (Kai, 7.11.2026, 26.11.39).
|
||||
--
|
||||
-- Mengen bleiben in der Basiseinheit pro Portion gespeichert (CLAUDE.md, Regel 2).
|
||||
-- Dazu kommt, in welchem Küchenmaß sie eingegeben wurden (display_unit), damit
|
||||
-- das Rezept „2 EL (30 ml)“ zeigt statt nur „30 ml“, und „400 g (1 Dose)“.
|
||||
--
|
||||
-- An der Zutat: das übliche Küchenmaß (kitchen_unit, vorgewählt im Formular)
|
||||
-- und das übliche Gebinde mit Größe in der Basiseinheit (pack_kind, pack_size).
|
||||
-- Ein Haushalt kann die Größe ändern (household_pack_sizes); ein Produkt mit
|
||||
-- Packungsgröße am Gericht geht vor.
|
||||
|
||||
alter table ingredients add column kitchen_unit text
|
||||
check (kitchen_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
alter table ingredients add column pack_size numeric(12, 3) check (pack_size is null or pack_size > 0);
|
||||
|
||||
alter table dish_ingredients add column display_unit text
|
||||
check (display_unit in ('tbsp', 'tsp', 'pinch', 'can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
alter table shopping_items add column pack_kind text check (pack_kind in ('can', 'jar', 'pack', 'bunch'));
|
||||
|
||||
create table household_pack_sizes (
|
||||
household_id uuid not null references households (id) on delete cascade,
|
||||
ingredient_id uuid not null references ingredients (id) on delete cascade,
|
||||
pack_size numeric(12, 3) not null check (pack_size > 0),
|
||||
updated_at timestamptz not null default now(),
|
||||
primary key (household_id, ingredient_id)
|
||||
);
|
||||
alter table household_pack_sizes enable row level security;
|
||||
alter table household_pack_sizes force row level security;
|
||||
create policy household_pack_sizes_household on household_pack_sizes
|
||||
using (household_id = app_household_id())
|
||||
with check (household_id = app_household_id());
|
||||
+492
-130
File diff suppressed because it is too large.
Load diff
@@ -275,3 +275,29 @@ abgewiesen. Eigene Zutaten gehen in die Sicherung.
|
||||
**Lieblingsprodukt.** Es gilt je Zutat für den ganzen Haushalt (`household_products`) und
|
||||
wird mit dem Haken „Für alle Gerichte mit … merken“ gesetzt. Ein Produkt, das am Gericht
|
||||
selbst steht, geht immer vor.
|
||||
|
||||
## E-0016 · Löffel und Gebinde als Mengeneinheiten
|
||||
|
||||
*7.11.2026 · Kai („Teelöffel, Esslöffel … eine Dose als Einheit … natürlich muss auch die Grammzahl dort stehen“)*
|
||||
|
||||
**Gespeichert** wird weiter in der Basiseinheit pro Portion (Regel 2). Dazu hält
|
||||
`dish_ingredients.display_unit` fest, in welchem Maß die Menge eingegeben wurde:
|
||||
EL, TL, Prise, Dose, Glas, Packung oder Bund. Hochrechnen, Einkaufsliste und
|
||||
Preise rechnen also unverändert.
|
||||
|
||||
**Anzeige** (Kais Wahl):
|
||||
- Löffel stehen vorn, die Gramm in Klammern: „2 EL (30 ml)“. Die Prise hat keine Klammer.
|
||||
- Gebinde zeigen die Gramm zuerst: „400 g (1 Dose)“, hochgerechnet in Küchenbrüchen.
|
||||
- Weniger als eine Viertel Packung zeigt nur Gramm.
|
||||
- Ältere Gerichte und Vorlagen ohne Maß bekommen Löffel, wenn es ½ bis 8 sind, und
|
||||
ein Gebinde ab einer Viertel Packung. Prisen bekommen sie nie von selbst.
|
||||
|
||||
**An der Zutat:**
|
||||
- Das übliche Löffelmaß wird im Formular vorgewählt (Olivenöl in EL, Kreuzkümmel in TL, Salz in Prisen).
|
||||
- Das übliche Gebinde und seine Größe (gehackte Tomaten: Dose, 400 g) werden angeboten, mit der Größe in der Auswahl.
|
||||
- Ein Gebinde wird **nie vorgewählt**: Wer nach „Kokosmilch“ gleich „400“ tippt, meint Milliliter.
|
||||
|
||||
**Größe eines Gebindes:** Es gilt zuerst das Produkt am Gericht, dann das Lieblingsprodukt
|
||||
des Haushalts, dann die Haushaltsgröße (`household_pack_sizes`, ändern darf, wer Gerichte
|
||||
pflegt), zuletzt die Vorgabe. Beim Einlesen von Rezepten kommt die Größe aus der Zutat,
|
||||
nie aus dem Text oder einem Modell.
|
||||
+69
-5
@@ -153,7 +153,7 @@ test.describe("recipe link", () => {
|
||||
recipeYield: "4 Portionen",
|
||||
totalTime: "PT45M",
|
||||
image: "/bild.jpg",
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Handvoll Glück"],
|
||||
recipeIngredient: ["250 g rote Linsen", "2 Zwiebeln", "1 Becher Sahne", "1 Schuss Milch", "1 Handvoll Glück"],
|
||||
recipeInstructions: [{ "@type": "HowToStep", text: "Zwiebeln anschwitzen." }, { "@type": "HowToStep", text: "Linsen dazu und weich kochen." }],
|
||||
},
|
||||
],
|
||||
@@ -195,14 +195,17 @@ test.describe("recipe link", () => {
|
||||
await expect(page.getByRole("note").filter({ hasText: "Nach Regeln in Abschnitte eingeordnet" })).toBeVisible();
|
||||
await expect(page.getByLabel("Abschnitt von Schritt 1")).toHaveValue("cook");
|
||||
const amounts = page.getByRole("textbox", { name: "Menge", exact: true });
|
||||
await expect(amounts).toHaveCount(3);
|
||||
await expect(amounts).toHaveCount(4);
|
||||
await expect(amounts.nth(0)).toHaveValue("250");
|
||||
await expect(amounts.nth(1)).toHaveValue("2");
|
||||
await expect(amounts.nth(2)).toHaveValue("");
|
||||
// Sahne im Becher: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
// Becher ist das Gebinde der Sahne (26.11.39): 1 Packung zu 200 ml.
|
||||
await expect(amounts.nth(2)).toHaveValue("1");
|
||||
await expect(page.getByRole("combobox", { name: "Einheit" }).nth(2).locator("option:checked")).toHaveText("Packung (200 ml)");
|
||||
await expect(amounts.nth(3)).toHaveValue("");
|
||||
// Ein Schuss Milch: Menge fehlt — Speichern sagt es, statt die Zeile wegzulassen.
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.locator("main [role=alert]")).toContainText("fehlt die Menge");
|
||||
await amounts.nth(2).fill("200");
|
||||
await amounts.nth(3).fill("50");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Linsensuppe vom Blog");
|
||||
await expect(page.locator("main img").first()).toHaveAttribute("src", /\/api\/fotos\//);
|
||||
@@ -403,3 +406,64 @@ test("a group term shows the group with its kinds; an own ingredient and a remem
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
}
|
||||
});
|
||||
|
||||
// Löffel und Gebinde (26.11.39, Kai: „Teelöffel, Esslöffel … eine Dose als Einheit“).
|
||||
test("spoons and cans: the ingredient preselects its measure, the dish shows spoons and grams", async ({ page }) => {
|
||||
await page.goto("/gerichte/neu");
|
||||
await page.fill("#title", "Tomatensoße vom Blech");
|
||||
const search = page.getByRole("combobox", { name: "Zutat suchen" });
|
||||
const unit = page.getByRole("combobox", { name: "Einheit" });
|
||||
await search.first().fill("Olivenöl");
|
||||
await page.getByRole("option", { name: "Olivenöl", exact: true }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).first().fill("2");
|
||||
|
||||
await page.getByRole("button", { name: "Zutaten" }).click();
|
||||
await search.nth(1).fill("gehackte Tomaten");
|
||||
await page.getByRole("option", { name: /Gehackte Tomaten/ }).first().click();
|
||||
// Die Dose wird angeboten, mit Größe, aber nicht vorgewählt.
|
||||
await expect(unit.nth(1)).toHaveValue("g");
|
||||
await unit.nth(1).selectOption("can");
|
||||
await expect(unit.nth(1).locator("option:checked")).toHaveText("Dose (400 g)");
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
// Unsere Dose hat 500 g.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Größe einer Dose in g").fill("500");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 500 g")).toBeVisible();
|
||||
await page.getByRole("textbox", { name: "Menge", exact: true }).nth(1).fill("1");
|
||||
await page.getByLabel("Schritt 1", { exact: true }).fill("Tomaten mit Öl aufs Blech.");
|
||||
await page.getByRole("button", { name: "Speichern" }).click();
|
||||
await expect(page.getByRole("heading", { level: 1 })).toHaveText("Tomatensoße vom Blech");
|
||||
|
||||
// Auf vier Portionen: „2 EL (30 ml) Olivenöl“, „500 g (1 Dose) Gehackte Tomaten“.
|
||||
const list = page.locator("main ul").first();
|
||||
const portions = page.locator("output");
|
||||
for (let i = 0; i < 8 && !(await portions.innerText()).startsWith("4 "); i++) {
|
||||
const n = Number((await portions.innerText()).match(/\d+/)![0]);
|
||||
await page.getByRole("button", { name: n > 4 ? "Eine Portion weniger" : "Eine Portion mehr" }).click();
|
||||
}
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/2 EL\s*\(30 ml\) Olivenöl/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/500 g\s*\(1 Dose\) Gehackte Tomaten/);
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await page.getByRole("button", { name: "Eine Portion weniger" }).click();
|
||||
await expect(list.locator("li", { hasText: "Olivenöl" })).toContainText(/1 EL\s*\(15 ml\)/);
|
||||
await expect(list.locator("li", { hasText: "Gehackte Tomaten" })).toContainText(/250 g\s*\(½ Dose\)/);
|
||||
|
||||
// Bearbeiten zeigt die Mengen im eingegebenen Maß.
|
||||
await page.getByRole("link", { name: "Bearbeiten" }).click();
|
||||
await expect(unit.first()).toHaveValue("tbsp");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).first()).toHaveValue("2");
|
||||
await expect(unit.nth(1)).toHaveValue("can");
|
||||
await expect(page.getByRole("textbox", { name: "Menge", exact: true }).nth(1)).toHaveValue("1");
|
||||
|
||||
// Aufräumen: Größe zurück, Gericht aus dem Pool — damit Plan und Einkauf gleich bleiben.
|
||||
await page.getByRole("button", { name: "Größe ändern" }).click();
|
||||
await page.getByLabel("Größe einer Dose in g").fill("400");
|
||||
await page.getByRole("button", { name: "Übernehmen" }).click();
|
||||
await expect(page.getByText("1 Dose = 400 g")).toBeVisible();
|
||||
await page.goto("/gerichte");
|
||||
await page.getByRole("link", { name: /Tomatensoße vom Blech/ }).click();
|
||||
await page.getByRole("button", { name: "Entfernen" }).click();
|
||||
await expect(page).toHaveURL(/entfernt=/);
|
||||
});
|
||||
@@ -24,6 +24,7 @@ export const TABLES = [
|
||||
"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",
|
||||
"household_pack_sizes",
|
||||
"stores",
|
||||
"store_aisles",
|
||||
"dishes",
|
||||
|
||||
+38
-13
@@ -5,14 +5,15 @@ import { BASES, TAGS } from "./categories";
|
||||
import type { IngredientEntry } from "./ingredient-search";
|
||||
import { allIngredients } from "./ingredients";
|
||||
import { linkIngredients, orderSections, SECTIONS, sectionsByRules, styleByRules, type Section, type StepIngredient } from "./recipe-style";
|
||||
import { toBase, type BaseUnit, type InputUnit } from "./units";
|
||||
import { impliedKitchenUnit, isKitchenUnit, isPackKind, toBase, type BaseUnit, type InputUnit, type KitchenUnit, type PackKind } from "./units";
|
||||
|
||||
// Gerichte des Haushalts lesen und schreiben. Mengen kommen so, wie man sie
|
||||
// für das ganze Rezept eintippt (z. B. „500 g für 4 Portionen“), und werden
|
||||
// hier in Basiseinheiten pro Portion umgerechnet (CLAUDE.md, Regel 2).
|
||||
// Alle Funktionen laufen in withHousehold(…).
|
||||
|
||||
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch"] as const;
|
||||
// Seit 26.11.39 auch Gebinde: Dose, Glas, Packung, Bund — Größe aus der Zutat oder dem Produkt.
|
||||
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch", "can", "jar", "pack", "bunch"] as const;
|
||||
|
||||
export const dishInput = z.object({
|
||||
title: z.string().trim().min(1).max(120),
|
||||
@@ -80,6 +81,12 @@ export type DishDetail = DishSummary & {
|
||||
note: string | null;
|
||||
isStaple: boolean;
|
||||
product: Product | null;
|
||||
/** Eingegebenes Küchenmaß („2 EL“, „1 Dose“), sonst null (26.11.39). */
|
||||
displayUnit: KitchenUnit | null;
|
||||
/** Gebinde der Zutat und seine Größe in der Basiseinheit: Produkt, sonst Haushalt, sonst Vorgabe. */
|
||||
packKind: PackKind | null;
|
||||
packSize: number | null;
|
||||
kitchenUnit: KitchenUnit | null;
|
||||
}[];
|
||||
// timerFrom: Name des Produkts, wenn der Timer von seiner Packung stammt.
|
||||
steps: { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string }[];
|
||||
@@ -109,7 +116,7 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
const entries = new Map((await allIngredients(client)).map((i) => [i.id, i]));
|
||||
const ingredients = (
|
||||
await client.query(
|
||||
`select di.ingredient_id, di.qty_per_portion, di.unit, di.note, di.is_staple, di.product, di.product_pack::float as product_pack,
|
||||
`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.display_unit,
|
||||
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`,
|
||||
@@ -129,6 +136,14 @@ export async function getDish(client: PoolClient, id: string, locale: string): P
|
||||
: r.house_product
|
||||
? { name: r.house_product, pack: r.house_pack, cookMinutes: r.house_cook, fromHousehold: true }
|
||||
: null,
|
||||
displayUnit: r.display_unit as KitchenUnit | null,
|
||||
packKind: entries.get(r.ingredient_id)?.packKind ?? null,
|
||||
packSize: ((r.product ? r.product_pack : r.house_pack) ?? entries.get(r.ingredient_id)?.packSize ?? null) as number | null,
|
||||
kitchenUnit: entries.get(r.ingredient_id)?.kitchenUnit ?? null,
|
||||
})).map((i) => ({
|
||||
...i,
|
||||
// Ohne eingegebenes Maß (ältere Gerichte, Vorlagen): Löffel oder Gebinde, wo es passt (26.11.39).
|
||||
displayUnit: i.displayUnit ?? impliedKitchenUnit(i.qtyPerPortion * 4, i.unit, i.kitchenUnit, i.packKind, i.packSize),
|
||||
}));
|
||||
const rows = (
|
||||
await client.query("select section, text, timer_seconds, ingredient_ids from dish_steps where dish_id = $1 order by position", [id])
|
||||
@@ -171,15 +186,25 @@ export class InvalidAmount extends Error {}
|
||||
/** Legt an (id leer) oder ersetzt Inhalt, Zutaten und Schritte. Gibt die Kennung zurück. */
|
||||
export async function saveDish(client: PoolClient, householdId: string, memberId: string, input: DishInput, id?: string): Promise<string> {
|
||||
const all = await allIngredients(client);
|
||||
const units = new Map(all.map((i) => [i.id, i.unit]));
|
||||
const byId = new Map(all.map((i) => [i.id, i]));
|
||||
const house = new Map(
|
||||
(await client.query("select ingredient_id, product_pack::float as pack from household_products")).rows.map((r) => [r.ingredient_id as string, r.pack as number | null]),
|
||||
);
|
||||
const rows = input.ingredients.map((i, position) => {
|
||||
const base = units.get(i.ingredientId);
|
||||
if (!base) throw new InvalidAmount(i.ingredientId);
|
||||
const total = toBase(i.qty, i.unit as InputUnit, base);
|
||||
const entry = byId.get(i.ingredientId);
|
||||
if (!entry) throw new InvalidAmount(i.ingredientId);
|
||||
const base = entry.unit;
|
||||
const unit = i.unit as InputUnit;
|
||||
// Ein Gebinde nur, wenn die Zutat eines hat — „1 Dose Zwiebeln“ gibt es nicht.
|
||||
if (isPackKind(unit) && entry.packKind !== unit) throw new InvalidAmount(i.ingredientId);
|
||||
// Packung des Produkts: bei einem Gebinde in der Basiseinheit („400“ g), sonst in der Einheit der Zeile.
|
||||
const pack = i.product?.pack ? toBase(i.product.pack, isPackKind(unit) ? base : unit, base) : null;
|
||||
// Größe des Gebindes: Produkt am Gericht, sonst Lieblingsprodukt, sonst Haushalt bzw. Vorgabe.
|
||||
const size = (i.product ? pack : null) ?? house.get(i.ingredientId) ?? entry.packSize ?? null;
|
||||
const total = toBase(i.qty, unit, base, size);
|
||||
if (total === null) throw new InvalidAmount(i.ingredientId);
|
||||
// Packung in der Einheit der Zeile → Basiseinheit („500 g“, „1 kg“ → 1000).
|
||||
const pack = i.product?.pack ? toBase(i.product.pack, i.unit as InputUnit, base) : null;
|
||||
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position, pack };
|
||||
const displayUnit = isKitchenUnit(unit) ? unit : null;
|
||||
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position, pack, displayUnit };
|
||||
});
|
||||
const values = [
|
||||
input.title,
|
||||
@@ -211,10 +236,10 @@ export async function saveDish(client: PoolClient, householdId: string, memberId
|
||||
for (const r of rows) {
|
||||
await client.query(
|
||||
`insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, note, position,
|
||||
product, product_pack, product_cook_minutes)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
||||
product, product_pack, product_cook_minutes, display_unit)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
|
||||
[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],
|
||||
r.product?.name ?? null, r.product ? r.pack : null, r.product?.cookMinutes ?? null, r.displayUnit],
|
||||
);
|
||||
if (r.product?.remember) {
|
||||
await client.query(
|
||||
|
||||
@@ -9,8 +9,16 @@ export type Nameable = { names: Record<string, string>; forms?: Forms | null; un
|
||||
/** Einzahl bis einschließlich 1 — also auch für ½ und ¼. */
|
||||
export const isOne = (qty: number) => qty > 0 && qty <= 1 + 1e-9;
|
||||
|
||||
// „Gehackte Tomaten (Dose)“ neben „400 g (1 Dose)“ wäre doppelt: Steht das Gebinde
|
||||
// schon in der Menge (26.11.39), fällt der Hinweis am Namen weg.
|
||||
const PACK_HINT = /\s*\((dose|glas|tin|can|jar|bocal|boîte|lata|tarro)\)$/i;
|
||||
|
||||
/** Für Anzeigen, die Name und Formen schon in der Sprache haben (Gerichtsseite, Kochmodus). */
|
||||
export function labelFor(i: { name: string; forms: { one: string; other: string } | null; unit: string }, qty: number): string {
|
||||
export function labelFor(
|
||||
i: { name: string; forms: { one: string; other: string } | null; unit: string; displayUnit?: string | null },
|
||||
qty: number,
|
||||
): string {
|
||||
if (i.displayUnit && ["can", "jar", "pack"].includes(i.displayUnit)) return i.name.replace(PACK_HINT, "");
|
||||
if (i.unit !== "piece" || !i.forms) return i.name;
|
||||
return isOne(qty) ? i.forms.one : i.forms.other;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
// ohne Rücksicht auf Groß-/Kleinschreibung und Akzente („creme“ findet
|
||||
// „Crème fraîche“). Rein, ohne Datenbank — lib/ingredients.ts lädt die Liste.
|
||||
|
||||
import type { KitchenUnit, PackKind } from "./units";
|
||||
|
||||
export type IngredientEntry = {
|
||||
id: string;
|
||||
key: string;
|
||||
@@ -16,6 +18,11 @@ export type IngredientEntry = {
|
||||
parentId?: string | null;
|
||||
/** Eigene Zutat des Haushalts. */
|
||||
own?: boolean;
|
||||
/** Übliches Küchenmaß, vorgewählt im Formular (26.11.39). */
|
||||
kitchenUnit?: KitchenUnit | null;
|
||||
/** Übliches Gebinde und seine Größe in der Basiseinheit (Haushaltsgröße schon eingerechnet). */
|
||||
packKind?: PackKind | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
|
||||
export function normalize(text: string): string {
|
||||
|
||||
+23
-3
@@ -8,7 +8,8 @@ import type { IngredientEntry } from "./ingredient-search";
|
||||
// (26.11.38) kommen je Anfrage dazu — mit einem Client in seinem Kontext.
|
||||
let cache: Promise<IngredientEntry[]> | null = null;
|
||||
|
||||
const COLUMNS = `id, key, default_unit as unit, category, names, synonyms, forms, is_group as "isGroup", parent_id as "parentId"`;
|
||||
const COLUMNS = `id, key, default_unit as unit, category, names, synonyms, forms, is_group as "isGroup", parent_id as "parentId",
|
||||
kitchen_unit as "kitchenUnit", pack_kind as "packKind", pack_size::float as "packSize"`;
|
||||
|
||||
function globalIngredients(): Promise<IngredientEntry[]> {
|
||||
cache ??= pool
|
||||
@@ -21,12 +22,31 @@ function globalIngredients(): Promise<IngredientEntry[]> {
|
||||
return cache;
|
||||
}
|
||||
|
||||
/** Alle Zutaten; mit client (withHousehold) auch die eigenen des Haushalts. */
|
||||
/**
|
||||
* Alle Zutaten; mit client (withHousehold) auch die eigenen des Haushalts und
|
||||
* seine Gebindegrößen (26.11.39: „bei uns hat die Dose 500 g“).
|
||||
*/
|
||||
export async function allIngredients(client?: PoolClient): Promise<IngredientEntry[]> {
|
||||
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;
|
||||
const sizes = new Map(
|
||||
(await client.query("select ingredient_id, pack_size::float as size from household_pack_sizes")).rows.map((r) => [r.ingredient_id as string, r.size as number]),
|
||||
);
|
||||
const all = own.length ? [...global, ...own] : global;
|
||||
return sizes.size ? all.map((i) => (sizes.has(i.id) && i.packKind ? { ...i, packSize: sizes.get(i.id)! } : i)) : all;
|
||||
}
|
||||
|
||||
/** Gebindegröße für den Haushalt setzen (wer Gerichte pflegt). Nur für Zutaten mit Gebinde. */
|
||||
export async function setPackSize(client: PoolClient, householdId: string, ingredientId: string, size: number): Promise<boolean> {
|
||||
const entry = (await allIngredients(client)).find((i) => i.id === ingredientId);
|
||||
if (!entry?.packKind) return false;
|
||||
await client.query(
|
||||
`insert into household_pack_sizes (household_id, ingredient_id, pack_size) values ($1, $2, $3)
|
||||
on conflict (household_id, ingredient_id) do update set pack_size = excluded.pack_size, updated_at = now()`,
|
||||
[householdId, ingredientId, size],
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function ingredientName(id: string, locale: string, client?: PoolClient): Promise<string> {
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ export async function draftFromRecipe(
|
||||
.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: toBase(l.qty, l.unit, l.ingredient!.unit, l.ingredient!.packSize), unit: l.ingredient!.unit, note: l.note };
|
||||
}
|
||||
return { ingredient: l.ingredient, qty: l.qty, unit: l.unit, note: l.note };
|
||||
}),
|
||||
|
||||
+27
-5
@@ -4,7 +4,7 @@
|
||||
// lib/fetch-safe.ts, das Zuordnen der Zutaten lib/ingredient-search.ts.
|
||||
|
||||
import { searchIngredients, type IngredientEntry } from "./ingredient-search";
|
||||
import { parseNumber, toBase, type InputUnit } from "./units";
|
||||
import { isPackKind, parseNumber, toBase, type InputUnit, type KitchenUnit, type PackKind } from "./units";
|
||||
|
||||
export type RawRecipe = {
|
||||
title: string;
|
||||
@@ -128,7 +128,12 @@ const UNIT_WORDS: [RegExp, InputUnit, number?][] = [
|
||||
[/^(cups?|tassen?|tazas?)$/i, "cup"],
|
||||
[/^(oz|ounces?)$/i, "g", 28.35],
|
||||
[/^(lbs?|pounds?)$/i, "g", 453.6],
|
||||
[/^(st(ü|ue)ck|stk\.?|pieces?|pi[eè]ces?|unidad(es)?|zehen?|cloves?|gousses?|dientes?|bund|bunch(es)?|bouquets?|manojos?|dosen?|cans?|tins?|bo[iî]tes?|latas?|scheiben?|slices?|tranches?|rebanadas?)$/i, "piece"],
|
||||
// Gebinde (26.11.39): Größe kommt aus der Zutat, nie aus dem Text oder einem Modell.
|
||||
[/^(dosen?|cans?|tins?|bo[iî]tes?|latas?)$/i, "can"],
|
||||
[/^(gl(a|ä)s(er)?|jars?|bocal|bocaux|tarros?|frascos?)$/i, "jar"],
|
||||
[/^(pck|pkg|pack(ung(en)?|s)?|p(a|ä)ckchen|becher|paquets?|paquetes?|sachets?|sobres?|w(ü|ue)rfel|kugeln?)$/i, "pack"],
|
||||
[/^(bund|bunch(es)?|bouquets?|bottes?|manojos?)$/i, "bunch"],
|
||||
[/^(st(ü|ue)ck|stk\.?|pieces?|pi[eè]ces?|unidad(es)?|zehen?|cloves?|gousses?|dientes?|scheiben?|slices?|tranches?|rebanadas?)$/i, "piece"],
|
||||
];
|
||||
|
||||
export type ParsedLine = { raw: string; qty: number | null; unit: InputUnit | null; factor: number; name: string };
|
||||
@@ -168,7 +173,14 @@ export function parseIngredientLine(raw: string): ParsedLine {
|
||||
|
||||
export type MatchedLine = {
|
||||
raw: string;
|
||||
ingredient: { id: string; name: string; unit: "g" | "ml" | "piece" } | null;
|
||||
ingredient: {
|
||||
id: string;
|
||||
name: string;
|
||||
unit: "g" | "ml" | "piece";
|
||||
kitchenUnit?: KitchenUnit | null;
|
||||
packKind?: PackKind | null;
|
||||
packSize?: number | null;
|
||||
} | null;
|
||||
qty: number | null;
|
||||
unit: InputUnit | null;
|
||||
note: string | null;
|
||||
@@ -183,10 +195,20 @@ export function matchLines(lines: string[], list: IngredientEntry[], locale: str
|
||||
const p = parseIngredientLine(raw);
|
||||
const hit = p.name ? searchIngredients(list, p.name, locale, 1)[0] ?? searchIngredients(list, p.name.split(" ").at(-1) ?? "", locale, 1)[0] : undefined;
|
||||
if (!hit) return { raw, ingredient: null, qty: null, unit: null, note: null };
|
||||
const ingredient = { id: hit.id, name: hit.names[locale] ?? hit.names.en ?? "", unit: hit.unit };
|
||||
const ingredient = {
|
||||
id: hit.id,
|
||||
name: hit.names[locale] ?? hit.names.en ?? "",
|
||||
unit: hit.unit,
|
||||
kitchenUnit: hit.kitchenUnit ?? null,
|
||||
packKind: hit.packKind ?? null,
|
||||
packSize: hit.packSize ?? null,
|
||||
};
|
||||
let qty = p.qty !== null ? p.qty * p.factor : null;
|
||||
let unit = p.unit;
|
||||
if (qty !== null && unit && toBase(qty, unit, hit.unit) === null) {
|
||||
// Ein Gebinde ist das der Zutat („1 Becher Sahne“ → ihre Packung); ohne Gebinde
|
||||
// zählt bei Stück-Zutaten das Stück („1 Bund Petersilie“ ist ein Stück Petersilie).
|
||||
if (unit && isPackKind(unit)) unit = hit.packKind && hit.packSize ? hit.packKind : hit.unit === "piece" ? "piece" : unit;
|
||||
if (qty !== null && unit && toBase(qty, unit, hit.unit, hit.packSize) === null) {
|
||||
qty = null;
|
||||
unit = null;
|
||||
}
|
||||
|
||||
+12
-7
@@ -17,6 +17,7 @@ export type Item = {
|
||||
unit: "g" | "ml" | "piece" | null;
|
||||
packCount: number | null;
|
||||
packSize: number | null;
|
||||
packKind: "can" | "jar" | "pack" | "bunch" | null;
|
||||
dishes: string[];
|
||||
aislePosition: number | null;
|
||||
manual: boolean;
|
||||
@@ -54,7 +55,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
const rows = (
|
||||
await client.query(
|
||||
`select s.id as slot, d.title, s.portions, di.ingredient_id, di.qty_per_portion::float as q, di.unit,
|
||||
i.category, i.pack_sizes::float[] as packs,
|
||||
i.category, i.pack_sizes::float[] as packs, i.pack_kind, hps.pack_size::float as house_size,
|
||||
(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,
|
||||
@@ -65,6 +66,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
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
|
||||
left join household_pack_sizes hps on hps.ingredient_id = di.ingredient_id
|
||||
where s.round_id = $1 and s.cooked_at is null
|
||||
order by s.position`,
|
||||
[round.id, locale],
|
||||
@@ -73,6 +75,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
const bySlot = new Map<string, PlanSlotInput>();
|
||||
const packs = new Map<string, number[]>();
|
||||
const forms = new Map<string, { one: string; other: string }>();
|
||||
const kinds = new Map<string, string>();
|
||||
// Produkte je Zutat aus den Gerichten der Runde: Name auf die Liste, Packung statt der Standardgrößen.
|
||||
const products = new Map<string, Set<string>>();
|
||||
const productPacks = new Map<string, number[]>();
|
||||
@@ -80,7 +83,9 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
const slot: PlanSlotInput = bySlot.get(r.slot) ?? { dishTitle: r.title, portions: r.portions, ingredients: [] };
|
||||
slot.ingredients.push({ ingredientId: r.ingredient_id, name: r.name, unit: r.unit, qtyPerPortion: r.q, category: r.category, packs: r.packs, pantry: r.pantry });
|
||||
bySlot.set(r.slot, slot);
|
||||
packs.set(r.ingredient_id, r.packs ?? []);
|
||||
// Eigene Gebindegröße des Haushalts (26.11.39) statt der üblichen Packungen.
|
||||
packs.set(r.ingredient_id, r.house_size ? [r.house_size] : (r.packs ?? []));
|
||||
if (r.pack_kind) kinds.set(r.ingredient_id, r.pack_kind);
|
||||
if (r.form) forms.set(r.ingredient_id, r.form);
|
||||
if (r.product) {
|
||||
products.set(r.ingredient_id, (products.get(r.ingredient_id) ?? new Set()).add(r.product));
|
||||
@@ -92,15 +97,15 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
for (const l of lines) {
|
||||
await client.query(
|
||||
`insert into shopping_items (household_id, round_id, ingredient_id, label, qty, needed, unit, pack_count, pack_size,
|
||||
dishes, aisle_position, pantry_state)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
||||
dishes, aisle_position, pantry_state, pack_kind)
|
||||
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
|
||||
on conflict (round_id, ingredient_id) where not added_manually do update
|
||||
set label = excluded.label, qty = excluded.qty, needed = excluded.needed, unit = excluded.unit,
|
||||
pack_count = excluded.pack_count, pack_size = excluded.pack_size, dishes = excluded.dishes,
|
||||
pack_count = excluded.pack_count, pack_size = excluded.pack_size, pack_kind = excluded.pack_kind, dishes = excluded.dishes,
|
||||
aisle_position = excluded.aisle_position,
|
||||
pantry_state = case when excluded.pantry_state is null then null else coalesce(shopping_items.pantry_state, 'ask') end`,
|
||||
[householdId, round.id, l.ingredientId, label(l), l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
|
||||
l.dishes, l.aislePosition, l.pantry ? "ask" : null],
|
||||
l.dishes, l.aislePosition, l.pantry ? "ask" : null, l.pack ? (kinds.get(l.ingredientId) ?? null) : null],
|
||||
);
|
||||
}
|
||||
await client.query(
|
||||
@@ -113,7 +118,7 @@ export async function syncList(client: PoolClient, householdId: string, round: R
|
||||
export async function listItems(client: PoolClient, roundId: string): Promise<Item[]> {
|
||||
const { rows } = await client.query(
|
||||
`select i.id, i.ingredient_id as "ingredientId", i.label, i.qty::float, i.needed::float, i.unit,
|
||||
i.pack_count as "packCount", i.pack_size::float as "packSize", i.dishes, i.aisle_position as "aislePosition",
|
||||
i.pack_count as "packCount", i.pack_size::float as "packSize", i.pack_kind as "packKind", i.dishes, i.aisle_position as "aislePosition",
|
||||
i.added_manually as manual, i.pantry_state as "pantryState", m.display_name as "checkedBy", i.checked_at::text as "checkedAt"
|
||||
from shopping_items i left join members m on m.id = i.checked_by
|
||||
where i.round_id = $1
|
||||
|
||||
+87
-2
@@ -4,8 +4,19 @@
|
||||
|
||||
export type BaseUnit = "g" | "ml" | "piece";
|
||||
|
||||
/** Gebinde, in denen man kauft: Dose, Glas, Packung, Bund (26.11.39). */
|
||||
export const PACK_KINDS = ["can", "jar", "pack", "bunch"] as const;
|
||||
export type PackKind = (typeof PACK_KINDS)[number];
|
||||
|
||||
/** Küchenmaße, die ein Rezept so anzeigt, wie sie eingegeben wurden (26.11.39). */
|
||||
export const KITCHEN_UNITS = ["tbsp", "tsp", "pinch", ...PACK_KINDS] as const;
|
||||
export type KitchenUnit = (typeof KITCHEN_UNITS)[number];
|
||||
|
||||
export const isPackKind = (u: string): u is PackKind => (PACK_KINDS as readonly string[]).includes(u);
|
||||
export const isKitchenUnit = (u: string): u is KitchenUnit => (KITCHEN_UNITS as readonly string[]).includes(u);
|
||||
|
||||
/** Maße, die man tippt oder in Rezepten liest. */
|
||||
export type InputUnit = BaseUnit | "kg" | "l" | "cl" | "tbsp" | "tsp" | "pinch" | "cup";
|
||||
export type InputUnit = BaseUnit | "kg" | "l" | "cl" | "tbsp" | "tsp" | "pinch" | "cup" | PackKind;
|
||||
|
||||
/** Hochrechnen: Menge pro Portion × Portionen. */
|
||||
export function scale(qtyPerPortion: number, portions: number): number {
|
||||
@@ -21,9 +32,11 @@ const SOLID_G: Partial<Record<InputUnit, number>> = { g: 1, kg: 1000, tbsp: 12,
|
||||
/**
|
||||
* Eingabe in die Basiseinheit der Zutat bringen. Gibt null zurück, wenn die
|
||||
* Maße nicht zusammenpassen (z. B. „200 g“ Eier) — dann fragt die Oberfläche nach.
|
||||
* Ein Gebinde braucht seine Größe in der Basiseinheit („1 Dose“ × 400 g).
|
||||
*/
|
||||
export function toBase(qty: number, unit: InputUnit, base: BaseUnit): number | null {
|
||||
export function toBase(qty: number, unit: InputUnit, base: BaseUnit, packSize?: number | null): number | null {
|
||||
if (!Number.isFinite(qty) || qty < 0) return null;
|
||||
if (isPackKind(unit)) return packSize && packSize > 0 ? qty * packSize : null;
|
||||
if (base === "piece") return unit === "piece" ? qty : null;
|
||||
if (unit === "piece") return null;
|
||||
if (base === "ml") {
|
||||
@@ -77,6 +90,78 @@ export function formatQuantity(qty: number, unit: BaseUnit, locale = "de"): Form
|
||||
return { amount: nf(rounded, 1), unit };
|
||||
}
|
||||
|
||||
/** Menge in Basiseinheit zurück in das Küchenmaß, in dem sie eingegeben wurde (fürs Bearbeiten). */
|
||||
export function fromBase(qty: number, unit: KitchenUnit, base: BaseUnit, packSize?: number | null): number | null {
|
||||
if (isPackKind(unit)) return packSize && packSize > 0 ? qty / packSize : null;
|
||||
const f = base === "ml" ? VOLUME_ML[unit] : base === "g" ? SOLID_G[unit] : undefined;
|
||||
return f ? qty / f : null;
|
||||
}
|
||||
|
||||
/** Löffel und Prisen in Küchenbrüchen; ein Löffel wird nicht genauer als ein halber. */
|
||||
function spoons(qty: number, locale: string): string {
|
||||
return pieces(qty < 0.5 ? qty : Math.round(qty * 2) / 2, locale);
|
||||
}
|
||||
|
||||
export type KitchenFormatted = {
|
||||
/** Vorn stehende Zahl mit Maß: „2 EL“, „400 g“, „6“. */
|
||||
main: string;
|
||||
/** In Klammern dahinter: „30 ml“, „1 Dose“ — leer, wenn nichts zu sagen ist. */
|
||||
extra: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Anzeige mit Küchenmaß (Kai, 26.11.39): Löffel vorn, Gramm in Klammern —
|
||||
* „2 EL (30 ml)“; Gebinde hinten, Gramm vorn — „400 g (1 Dose)“. Ohne Küchenmaß
|
||||
* oder ohne bekannte Gebindegröße wie bisher. `word` liefert das Wort in der
|
||||
* Sprache („Dose“/„Dosen“), `count` entscheidet über Einzahl oder Mehrzahl.
|
||||
*/
|
||||
export function formatKitchen(
|
||||
qty: number,
|
||||
base: BaseUnit,
|
||||
display: KitchenUnit | null | undefined,
|
||||
packSize: number | null | undefined,
|
||||
locale: string,
|
||||
word: (unit: KitchenUnit, count: number) => string,
|
||||
): KitchenFormatted {
|
||||
const plain = formatQuantity(qty, base, locale);
|
||||
const plainText = `${plain.amount}${plain.unit ? ` ${plain.unit}` : ""}`;
|
||||
if (!display) return { main: plainText, extra: "" };
|
||||
const n = fromBase(qty, display, base, packSize);
|
||||
if (n === null) return { main: plainText, extra: "" };
|
||||
if (isPackKind(display)) {
|
||||
// Ein Achtel Packung Butter hilft niemandem — dann nur Gramm.
|
||||
if (n < 0.25 - 1e-9) return { main: plainText, extra: "" };
|
||||
const count = pieces(n, locale);
|
||||
return { main: plainText, extra: `${count} ${word(display, n)}` };
|
||||
}
|
||||
const count = spoons(n, locale);
|
||||
// Eine Prise wiegt nichts, was man nachwiegen würde — ohne Klammer.
|
||||
return { main: `${count} ${word(display, n)}`, extra: display === "pinch" || base === "piece" ? "" : plainText };
|
||||
}
|
||||
|
||||
/**
|
||||
* Küchenmaß für Mengen ohne eingegebenes Maß (ältere Gerichte, Vorlagen): Gebinde,
|
||||
* wenn es mindestens ein Viertel ist; Löffel, wenn es ½ bis 8 Löffel sind. Prisen
|
||||
* nie von selbst. Entschieden für die Menge des ganzen Rezepts, nicht je Portion.
|
||||
*/
|
||||
export function impliedKitchenUnit(
|
||||
qty: number,
|
||||
base: BaseUnit,
|
||||
kitchenUnit: KitchenUnit | null | undefined,
|
||||
packKind: PackKind | null | undefined,
|
||||
packSize: number | null | undefined,
|
||||
): KitchenUnit | null {
|
||||
if (packKind && packSize) {
|
||||
const n = qty / packSize;
|
||||
if (n >= 0.25 - 1e-9) return packKind;
|
||||
}
|
||||
if (kitchenUnit === "tbsp" || kitchenUnit === "tsp") {
|
||||
const n = fromBase(qty, kitchenUnit, base);
|
||||
if (n !== null && n >= 0.5 - 1e-9 && n <= 8 + 1e-9) return kitchenUnit;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Für die Einkaufsliste: Stück immer aufrunden (½ Zwiebel kauft man nicht). */
|
||||
export function shoppingQuantity(qty: number, unit: BaseUnit): number {
|
||||
return unit === "piece" ? Math.ceil(qty - 1e-9) : qty;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
"use client";
|
||||
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { isOne } from "./ingredient-name";
|
||||
import { formatKitchen, type BaseUnit, type KitchenUnit } from "./units";
|
||||
|
||||
/** Was eine Zutat für die Mengenanzeige mitbringt (lib/dishes.ts, getDish). */
|
||||
export type Measured = {
|
||||
unit: BaseUnit;
|
||||
displayUnit?: KitchenUnit | null;
|
||||
packSize?: number | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Menge mit Küchenmaß in der Sprache der Person (26.11.39): „2 EL (30 ml)“,
|
||||
* „400 g (1 Dose)“. Liefert Hauptteil und Klammer getrennt, damit Listen sie
|
||||
* verschieden setzen können; text() fügt beides zusammen.
|
||||
*/
|
||||
export function useKitchenAmount() {
|
||||
const locale = useLocale();
|
||||
const tm = useTranslations("measure");
|
||||
const word = (u: KitchenUnit, n: number) => tm(u, { n: isOne(n) ? 1 : 2 });
|
||||
const parts = (i: Measured, qty: number) => formatKitchen(qty, i.unit, i.displayUnit, i.packSize, locale, word);
|
||||
const text = (i: Measured, qty: number) => {
|
||||
const p = parts(i, qty);
|
||||
return p.extra ? `${p.main} (${p.extra})` : p.main;
|
||||
};
|
||||
return { parts, text };
|
||||
}
|
||||
+24
-3
@@ -365,7 +365,11 @@
|
||||
"piece": "Stück",
|
||||
"tbsp": "EL",
|
||||
"tsp": "TL",
|
||||
"pinch": "Prise"
|
||||
"pinch": "Prise",
|
||||
"can": "Dose",
|
||||
"jar": "Glas",
|
||||
"pack": "Packung",
|
||||
"bunch": "Bund"
|
||||
},
|
||||
"errors": {
|
||||
"invalid": "Bitte gib einen Titel an und prüfe die Mengen.",
|
||||
@@ -390,7 +394,14 @@
|
||||
"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"
|
||||
"otherProduct": "Anderes Produkt für dieses Gericht",
|
||||
"unitWithSize": "{unit} ({size})",
|
||||
"packSize": "1 {unit} = {size}",
|
||||
"packChange": "Größe ändern",
|
||||
"packSizeLabel": "Größe einer {unit} in {base}",
|
||||
"packSave": "Übernehmen",
|
||||
"packHint": "Gilt für alle Gerichte eures Haushalts.",
|
||||
"packError": "Die Größe ließ sich nicht speichern."
|
||||
},
|
||||
"addLinkText": "Wir lesen Zutaten und Schritte von der Rezeptseite.",
|
||||
"link": {
|
||||
@@ -670,7 +681,8 @@
|
||||
"addPlaceholder": "z. B. Klopapier",
|
||||
"add": "Hinzufügen",
|
||||
"remove": "{name} entfernen",
|
||||
"offline": "{n, plural, =0 {Kein Netz. Die Liste bleibt bedienbar.} one {Kein Netz: 1 Haken wird nachgeholt.} other {Kein Netz: # Haken werden nachgeholt.}}"
|
||||
"offline": "{n, plural, =0 {Kein Netz. Die Liste bleibt bedienbar.} one {Kein Netz: 1 Haken wird nachgeholt.} other {Kein Netz: # Haken werden nachgeholt.}}",
|
||||
"packOf": "{count} {word} à {size}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Kochen",
|
||||
@@ -1012,5 +1024,14 @@
|
||||
"anyKind": "beliebige Sorte",
|
||||
"kinds": "{n, plural, one {1 Sorte} other {# Sorten}}",
|
||||
"ownBadge": "eigene"
|
||||
},
|
||||
"measure": {
|
||||
"tbsp": "{n, plural, one {EL} other {EL}}",
|
||||
"tsp": "{n, plural, one {TL} other {TL}}",
|
||||
"pinch": "{n, plural, one {Prise} other {Prisen}}",
|
||||
"can": "{n, plural, one {Dose} other {Dosen}}",
|
||||
"jar": "{n, plural, one {Glas} other {Gläser}}",
|
||||
"pack": "{n, plural, one {Packung} other {Packungen}}",
|
||||
"bunch": "{n, plural, one {Bund} other {Bund}}"
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -365,7 +365,11 @@
|
||||
"piece": "pcs",
|
||||
"tbsp": "tbsp",
|
||||
"tsp": "tsp",
|
||||
"pinch": "pinch"
|
||||
"pinch": "pinch",
|
||||
"can": "Can",
|
||||
"jar": "Jar",
|
||||
"pack": "Pack",
|
||||
"bunch": "Bunch"
|
||||
},
|
||||
"errors": {
|
||||
"invalid": "Please give a title and check the amounts.",
|
||||
@@ -390,7 +394,14 @@
|
||||
"addProduct": "Add product",
|
||||
"rememberProduct": "Remember for every dish with {name}",
|
||||
"inheritedProduct": "Your product for every dish: {product}",
|
||||
"otherProduct": "Different product for this dish"
|
||||
"otherProduct": "Different product for this dish",
|
||||
"unitWithSize": "{unit} ({size})",
|
||||
"packSize": "1 {unit} = {size}",
|
||||
"packChange": "Change size",
|
||||
"packSizeLabel": "Size of one {unit} in {base}",
|
||||
"packSave": "Apply",
|
||||
"packHint": "Applies to all dishes of your household.",
|
||||
"packError": "The size could not be saved."
|
||||
},
|
||||
"addLinkText": "We read ingredients and steps from the recipe page.",
|
||||
"link": {
|
||||
@@ -670,7 +681,8 @@
|
||||
"addPlaceholder": "e.g. toilet paper",
|
||||
"add": "Add",
|
||||
"remove": "Remove {name}",
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}"
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
|
||||
"packOf": "{count} {word} of {size}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
@@ -1012,5 +1024,14 @@
|
||||
"anyKind": "any kind",
|
||||
"kinds": "{n, plural, one {1 kind} other {# kinds}}",
|
||||
"ownBadge": "own"
|
||||
},
|
||||
"measure": {
|
||||
"tbsp": "{n, plural, one {tbsp} other {tbsp}}",
|
||||
"tsp": "{n, plural, one {tsp} other {tsp}}",
|
||||
"pinch": "{n, plural, one {pinch} other {pinches}}",
|
||||
"can": "{n, plural, one {can} other {cans}}",
|
||||
"jar": "{n, plural, one {jar} other {jars}}",
|
||||
"pack": "{n, plural, one {pack} other {packs}}",
|
||||
"bunch": "{n, plural, one {bunch} other {bunches}}"
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -365,7 +365,11 @@
|
||||
"piece": "pcs",
|
||||
"tbsp": "tbsp",
|
||||
"tsp": "tsp",
|
||||
"pinch": "pinch"
|
||||
"pinch": "pinch",
|
||||
"can": "Lata",
|
||||
"jar": "Tarro",
|
||||
"pack": "Paquete",
|
||||
"bunch": "Manojo"
|
||||
},
|
||||
"errors": {
|
||||
"invalid": "Please give a title and check the amounts.",
|
||||
@@ -390,7 +394,14 @@
|
||||
"addProduct": "Indicar producto",
|
||||
"rememberProduct": "Remember for every dish with {name}",
|
||||
"inheritedProduct": "Your product for every dish: {product}",
|
||||
"otherProduct": "Different product for this dish"
|
||||
"otherProduct": "Different product for this dish",
|
||||
"unitWithSize": "{unit} ({size})",
|
||||
"packSize": "1 {unit} = {size}",
|
||||
"packChange": "Cambiar tamaño",
|
||||
"packSizeLabel": "Tamaño de un(a) {unit} en {base}",
|
||||
"packSave": "Aplicar",
|
||||
"packHint": "Vale para todos los platos de tu hogar.",
|
||||
"packError": "No se pudo guardar el tamaño."
|
||||
},
|
||||
"addLinkText": "Leemos los ingredientes y los pasos de la página de la receta.",
|
||||
"link": {
|
||||
@@ -670,7 +681,8 @@
|
||||
"addPlaceholder": "e.g. toilet paper",
|
||||
"add": "Add",
|
||||
"remove": "Remove {name}",
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}"
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
|
||||
"packOf": "{count} {word} de {size}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
@@ -1012,5 +1024,14 @@
|
||||
"anyKind": "any kind",
|
||||
"kinds": "{n, plural, one {1 kind} other {# kinds}}",
|
||||
"ownBadge": "own"
|
||||
},
|
||||
"measure": {
|
||||
"tbsp": "{n, plural, one {cda.} other {cdas.}}",
|
||||
"tsp": "{n, plural, one {cdta.} other {cdtas.}}",
|
||||
"pinch": "{n, plural, one {pizca} other {pizcas}}",
|
||||
"can": "{n, plural, one {lata} other {latas}}",
|
||||
"jar": "{n, plural, one {tarro} other {tarros}}",
|
||||
"pack": "{n, plural, one {paquete} other {paquetes}}",
|
||||
"bunch": "{n, plural, one {manojo} other {manojos}}"
|
||||
}
|
||||
}
|
||||
+24
-3
@@ -365,7 +365,11 @@
|
||||
"piece": "pcs",
|
||||
"tbsp": "tbsp",
|
||||
"tsp": "tsp",
|
||||
"pinch": "pinch"
|
||||
"pinch": "pinch",
|
||||
"can": "Boîte",
|
||||
"jar": "Bocal",
|
||||
"pack": "Paquet",
|
||||
"bunch": "Botte"
|
||||
},
|
||||
"errors": {
|
||||
"invalid": "Please give a title and check the amounts.",
|
||||
@@ -390,7 +394,14 @@
|
||||
"addProduct": "Indiquer un produit",
|
||||
"rememberProduct": "Remember for every dish with {name}",
|
||||
"inheritedProduct": "Your product for every dish: {product}",
|
||||
"otherProduct": "Different product for this dish"
|
||||
"otherProduct": "Different product for this dish",
|
||||
"unitWithSize": "{unit} ({size})",
|
||||
"packSize": "1 {unit} = {size}",
|
||||
"packChange": "Modifier la taille",
|
||||
"packSizeLabel": "Taille d’un(e) {unit} en {base}",
|
||||
"packSave": "Appliquer",
|
||||
"packHint": "Vaut pour tous les plats de votre foyer.",
|
||||
"packError": "Impossible d’enregistrer la taille."
|
||||
},
|
||||
"addLinkText": "Nous lisons les ingrédients et les étapes sur la page de la recette.",
|
||||
"link": {
|
||||
@@ -670,7 +681,8 @@
|
||||
"addPlaceholder": "e.g. toilet paper",
|
||||
"add": "Add",
|
||||
"remove": "Remove {name}",
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}"
|
||||
"offline": "{n, plural, =0 {No connection. The list keeps working.} one {No connection: 1 tick will be sent later.} other {No connection: # ticks will be sent later.}}",
|
||||
"packOf": "{count} {word} de {size}"
|
||||
},
|
||||
"cooking": {
|
||||
"eyebrow": "Cooking",
|
||||
@@ -1012,5 +1024,14 @@
|
||||
"anyKind": "any kind",
|
||||
"kinds": "{n, plural, one {1 kind} other {# kinds}}",
|
||||
"ownBadge": "own"
|
||||
},
|
||||
"measure": {
|
||||
"tbsp": "{n, plural, one {c. à s.} other {c. à s.}}",
|
||||
"tsp": "{n, plural, one {c. à c.} other {c. à c.}}",
|
||||
"pinch": "{n, plural, one {pincée} other {pincées}}",
|
||||
"can": "{n, plural, one {boîte} other {boîtes}}",
|
||||
"jar": "{n, plural, one {bocal} other {bocaux}}",
|
||||
"pack": "{n, plural, one {paquet} other {paquets}}",
|
||||
"bunch": "{n, plural, one {botte} other {bottes}}"
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -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.38 # YY.M.<n> 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
|
||||
version: 26.11.39 # YY.M.<n> wie im AImighty-Markt — bei jeder Chart-Änderung erhöhen
|
||||
appVersion: "26.11.39" # MUSS gleich version sein: der Linter prüft es, und der Image-Tag hängt daran
|
||||
@@ -21,7 +21,7 @@ metadata:
|
||||
title: foodplanhero
|
||||
description: Plan. Cook. Smile. The family decides together what's for dinner — and the shopping list writes itself. Runs entirely on your own box.
|
||||
icon: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
version: 26.11.38
|
||||
version: 26.11.39
|
||||
categories:
|
||||
- Applications
|
||||
|
||||
@@ -61,7 +61,7 @@ permission:
|
||||
appData: true
|
||||
|
||||
spec:
|
||||
versionName: '26.11.38'
|
||||
versionName: '26.11.39'
|
||||
|
||||
featuredImage: https://git.aimighty.olares.de/aimighty/bilder/raw/branch/main/lunch/icon.png
|
||||
promoteImage:
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Spoons and cans
|
||||
v26.11.39: Recipes keep the measure you typed. Two tablespoons of olive oil now show as "2 tbsp (30 ml)" instead of only "30 ml", and they scale in kitchen fractions such as "1½ tsp". Ingredients that come in containers can be entered as a can, jar, pack or bunch. The recipe then shows the weight first, for example "400 g (1 can)". Each ingredient brings a usual size, such as 400 g for a can of chopped tomatoes. Your household can change that size for all its dishes, and a product with its own pack size on a dish takes precedence. Olive oil, spices and similar ingredients start with their usual spoon. Recipe links and photos read "1 can", "1 jar", "1 pack" and "1 bunch". The shopping list says "2 cans of 400 g".
|
||||
|
||||
## Deutsch
|
||||
v26.11.39: Rezepte behalten das Maß, in dem man sie eingibt. Zwei Esslöffel Olivenöl stehen jetzt als „2 EL (30 ml)“ da statt nur „30 ml“ und werden in Küchenbrüchen hochgerechnet, etwa „1½ TL“. Zutaten, die es im Gebinde gibt, lassen sich als Dose, Glas, Packung oder Bund eingeben. Das Rezept zeigt dann die Gramm zuerst, etwa „400 g (1 Dose)“. Jede Zutat bringt eine übliche Größe mit, zum Beispiel 400 g für gehackte Tomaten. Euer Haushalt kann diese Größe für alle seine Gerichte ändern, und ein Produkt mit eigener Packungsgröße am Gericht geht vor. Olivenöl, Gewürze und Ähnliches starten mit ihrem üblichen Löffel. Rezept-Links und Fotos lesen „1 Dose“, „1 Glas“, „1 Pck.“ und „1 Bund“. Auf der Einkaufsliste steht „2 Dosen à 400 g“.
|
||||
+8
-4
@@ -42,14 +42,18 @@ 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, 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)
|
||||
`insert into ingredients (id, key, category, default_unit, names, synonyms, freshness, pack_sizes, pantry_default, forms, is_group,
|
||||
kitchen_unit, pack_kind, pack_size)
|
||||
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),
|
||||
x.kitchen, x.pack ->> 'kind', (x.pack ->> 'size')::numeric
|
||||
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, "group" boolean)
|
||||
synonyms text[], freshness smallint, packs numeric[], pantry boolean, forms jsonb, "group" boolean,
|
||||
kitchen text, pack jsonb)
|
||||
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,
|
||||
is_group = excluded.is_group`,
|
||||
is_group = excluded.is_group, kitchen_unit = excluded.kitchen_unit, pack_kind = excluded.pack_kind,
|
||||
pack_size = excluded.pack_size`,
|
||||
[JSON.stringify(ingredients.map((i) => ({ ...i, id: idByKey.get(i.key) })))],
|
||||
);
|
||||
// Produktgruppen (26.11.38): Sorten zeigen auf ihren Oberbegriff („spaghetti“ → „pasta“).
|
||||
|
||||
+2
-1
@@ -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", "ingredients", "household_products",
|
||||
"helper_points", "achievements", "household_ai", "kid_devices", "dish_photos", "ingredients", "household_products", "household_pack_sizes",
|
||||
];
|
||||
|
||||
/** Eine globale Zutat, wie sie eine Seed-Migration anlegt. */
|
||||
@@ -88,6 +88,7 @@ export async function seedHousehold(client: pg.Client | pg.PoolClient, h: string
|
||||
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_pack_sizes (household_id, ingredient_id, pack_size) select $1, id, 500 from ingredients where key = 'chopped_tomatoes'", [h]);
|
||||
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 };
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { ingredientLabel, type Nameable } from "@/lib/ingredient-name";
|
||||
import { ingredientLabel, labelFor, type Nameable } from "@/lib/ingredient-name";
|
||||
|
||||
const seed: (Nameable & { key: string })[] = JSON.parse(readFileSync("db/seed/ingredients.json", "utf8"));
|
||||
const byKey = (k: string) => seed.find((i) => i.key === k)!;
|
||||
@@ -29,3 +29,12 @@ describe("ingredient names with amounts", () => {
|
||||
expect(missing).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pack hint in the name (26.11.39)", () => {
|
||||
it("drops „(Dose)“ when the amount already says it", () => {
|
||||
const tomatoes = { name: "Gehackte Tomaten (Dose)", forms: null, unit: "g" };
|
||||
expect(labelFor({ ...tomatoes, displayUnit: "can" }, 400)).toBe("Gehackte Tomaten");
|
||||
expect(labelFor({ ...tomatoes, displayUnit: null }, 400)).toBe("Gehackte Tomaten (Dose)");
|
||||
expect(labelFor({ name: "Erbsen (TK)", forms: null, unit: "g", displayUnit: "pack" }, 400)).toBe("Erbsen (TK)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
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", () => ({}));
|
||||
|
||||
// Löffel und Gebinde (26.11.39): Das Gericht merkt sich das eingegebene Maß, die
|
||||
// Menge bleibt in der Basiseinheit. Gebindegröße: Produkt am Gericht, sonst
|
||||
// Haushalt, sonst Vorgabe der Zutat — und kein Haushalt sieht die des anderen.
|
||||
const url = process.env.TEST_DATABASE_URL;
|
||||
|
||||
describe.skipIf(!url)("kitchen units", () => {
|
||||
const client = new pg.Client({ connectionString: url });
|
||||
const a = randomUUID();
|
||||
const b = randomUUID();
|
||||
let member = "";
|
||||
const ing: Record<string, string> = {};
|
||||
let dishes: typeof import("@/lib/dishes");
|
||||
let ingredients: typeof import("@/lib/ingredients");
|
||||
let db: typeof import("@/lib/db");
|
||||
|
||||
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 ('olive_oil','chopped_tomatoes','onion','ground_beef')")).rows) ing[r.key] = r.id;
|
||||
dishes = await import("@/lib/dishes");
|
||||
ingredients = await import("@/lib/ingredients");
|
||||
db = await import("@/lib/db");
|
||||
member = (await seedHousehold(client, a, ing.ground_beef!)).member;
|
||||
await seedHousehold(client, b, ing.ground_beef!);
|
||||
// Das Fixture setzt eine Haushaltsgröße für Dosentomaten; hier gilt erst die Vorgabe.
|
||||
for (const h of [a, b]) await db.withHousehold(h, (c) => c.query("delete from household_pack_sizes"));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await db.pool.end();
|
||||
await client.end();
|
||||
});
|
||||
|
||||
const dish = (list: { ingredientId: string; qty: number; unit: string; product?: object | null }[]) =>
|
||||
({ title: "Tomatensoße", portions: 4, base: null, tags: [], effortMinutes: 20, isTrial: false, ingredients: list, steps: [] }) as never;
|
||||
|
||||
it("keeps the typed spoon and can; amounts stay in base units", async () => {
|
||||
const got = await db.withHousehold(a, async (c) => {
|
||||
const id = await dishes.saveDish(c, a, member, dish([
|
||||
{ ingredientId: ing.olive_oil!, qty: 2, unit: "tbsp" },
|
||||
{ ingredientId: ing.chopped_tomatoes!, qty: 1, unit: "can" },
|
||||
]));
|
||||
return dishes.getDish(c, id, "de");
|
||||
});
|
||||
expect(got!.ingredients[0]).toMatchObject({ displayUnit: "tbsp", unit: "ml", qtyPerPortion: 7.5 });
|
||||
expect(got!.ingredients[1]).toMatchObject({ displayUnit: "can", unit: "g", qtyPerPortion: 100, packKind: "can", packSize: 400 });
|
||||
});
|
||||
|
||||
it("refuses a can for an ingredient that has none", async () => {
|
||||
await expect(db.withHousehold(a, (c) => dishes.saveDish(c, a, member, dish([{ ingredientId: ing.onion!, qty: 1, unit: "can" }])))).rejects.toThrow();
|
||||
});
|
||||
|
||||
it("household size beats the default, a product pack beats both; other households keep the default", async () => {
|
||||
expect(await db.withHousehold(a, (c) => ingredients.setPackSize(c, a, ing.chopped_tomatoes!, 500))).toBe(true);
|
||||
expect(await db.withHousehold(a, (c) => ingredients.setPackSize(c, a, ing.onion!, 500))).toBe(false);
|
||||
const [house, product] = await db.withHousehold(a, async (c) => {
|
||||
const one = await dishes.saveDish(c, a, member, dish([{ ingredientId: ing.chopped_tomatoes!, qty: 1, unit: "can" }]));
|
||||
const two = await dishes.saveDish(c, a, member, dish([{ ingredientId: ing.chopped_tomatoes!, qty: 1, unit: "can", product: { name: "Mutti", pack: 280 } }]));
|
||||
return [await dishes.getDish(c, one, "de"), await dishes.getDish(c, two, "de")];
|
||||
});
|
||||
expect(house!.ingredients[0]).toMatchObject({ qtyPerPortion: 125, packSize: 500 });
|
||||
expect(product!.ingredients[0]).toMatchObject({ qtyPerPortion: 70, packSize: 280 });
|
||||
const theirs = await db.withHousehold(b, (c) => ingredients.allIngredients(c));
|
||||
expect(theirs.find((i) => i.id === ing.chopped_tomatoes)!.packSize).toBe(400);
|
||||
});
|
||||
|
||||
it("an old dish without a typed unit shows spoons where they fit", async () => {
|
||||
const got = await db.withHousehold(a, async (c) => {
|
||||
const id = await dishes.saveDish(c, a, member, dish([{ ingredientId: ing.olive_oil!, qty: 30, unit: "ml" }]));
|
||||
await c.query("update dish_ingredients set display_unit = null where dish_id = $1", [id]);
|
||||
return dishes.getDish(c, id, "de");
|
||||
});
|
||||
expect(got!.ingredients[0]!.displayUnit).toBe("tbsp");
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,13 @@ import type { IngredientEntry } from "@/lib/ingredient-search";
|
||||
import { durationMinutes, extractRecipe, matchLines, parseIngredientLine } from "@/lib/recipe-import";
|
||||
|
||||
const list: IngredientEntry[] = JSON.parse(readFileSync("db/seed/ingredients.json", "utf8")).map(
|
||||
(i: IngredientEntry & { key: string }) => ({ ...i, id: i.key }),
|
||||
(i: IngredientEntry & { key: string; kitchen?: string; pack?: { kind: string; size: number } }) => ({
|
||||
...i,
|
||||
id: i.key,
|
||||
kitchenUnit: i.kitchen ?? null,
|
||||
packKind: i.pack?.kind ?? null,
|
||||
packSize: i.pack?.size ?? null,
|
||||
}),
|
||||
);
|
||||
|
||||
// Eine Seite wie viele deutsche Rezeptportale: JSON-LD im @graph, Anweisungen als HowToStep.
|
||||
@@ -51,11 +57,23 @@ describe("recipe import", () => {
|
||||
});
|
||||
|
||||
it("matches lines to canonical ingredients and keeps unfitting amounts for the person", () => {
|
||||
const m = matchLines(["750 g Rindergulasch", "3 Zwiebeln", "1 Becher Sahne", "2 EL Tomatenmark"], list, "de");
|
||||
const m = matchLines(["750 g Rindergulasch", "3 Zwiebeln", "1 Becher Sahne", "2 EL Tomatenmark", "1 Dose Zwiebeln"], list, "de");
|
||||
expect(m[0]).toMatchObject({ ingredient: { id: "beef_stew" }, qty: 750, unit: "g" });
|
||||
expect(m[1]).toMatchObject({ ingredient: { id: "onion" }, qty: 3, unit: "piece" });
|
||||
expect(m[2]!.ingredient?.id).toBe("cream");
|
||||
expect(m[2]!.qty).toBeNull();
|
||||
// Becher ist das Gebinde der Sahne (26.11.39), Größe aus der Zutat.
|
||||
expect(m[2]).toMatchObject({ ingredient: { id: "cream", packSize: 200 }, qty: 1, unit: "pack" });
|
||||
expect(m[3]).toMatchObject({ ingredient: { id: "tomato_paste" }, qty: 2, unit: "tbsp" });
|
||||
// Zwiebeln gibt es nicht in Dosen: die Menge zählt als Stück.
|
||||
expect(m[4]).toMatchObject({ ingredient: { id: "onion" }, qty: 1, unit: "piece" });
|
||||
});
|
||||
|
||||
it("reads cans, jars and bunches; their size comes from the ingredient (26.11.39)", () => {
|
||||
const m = matchLines(["2 Dosen gehackte Tomaten", "1 Glas Pesto", "1 Bund Petersilie", "1 Bund Frühlingszwiebeln"], list, "de");
|
||||
expect(m[0]).toMatchObject({ ingredient: { id: "chopped_tomatoes", packSize: 400 }, qty: 2, unit: "can" });
|
||||
expect(m[1]).toMatchObject({ ingredient: { id: "pesto", packSize: 190 }, qty: 1, unit: "jar" });
|
||||
// Petersilie zählt schon im Bund.
|
||||
expect(m[2]).toMatchObject({ ingredient: { id: "parsley" }, qty: 1, unit: "piece" });
|
||||
expect(m[3]).toMatchObject({ ingredient: { id: "spring_onion", packSize: 6 }, qty: 1, unit: "bunch" });
|
||||
expect(parseIngredientLine("1 Pck. Blätterteig")).toMatchObject({ qty: 1, unit: "pack", name: "Blätterteig" });
|
||||
});
|
||||
});
|
||||
+48
-1
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { formatQuantity, parseNumber, scale, shoppingQuantity, toBase } from "@/lib/units";
|
||||
import { formatKitchen, formatQuantity, fromBase, impliedKitchenUnit, parseNumber, scale, shoppingQuantity, toBase, type BaseUnit, type KitchenUnit } from "@/lib/units";
|
||||
|
||||
describe("units", () => {
|
||||
it("scales per-portion amounts", () => {
|
||||
@@ -52,3 +52,50 @@ describe("units", () => {
|
||||
expect(parseNumber("etwas")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("spoons and packs (26.11.39)", () => {
|
||||
const de: Record<string, [string, string]> = { tbsp: ["EL", "EL"], tsp: ["TL", "TL"], pinch: ["Prise", "Prisen"], can: ["Dose", "Dosen"], jar: ["Glas", "Gläser"], pack: ["Packung", "Packungen"], bunch: ["Bund", "Bund"] };
|
||||
const word = (u: KitchenUnit, n: number) => de[u]![n <= 1 + 1e-9 ? 0 : 1]!;
|
||||
const show = (qty: number, base: BaseUnit, display: KitchenUnit | null, size: number | null = null) => {
|
||||
const f = formatKitchen(qty, base, display, size, "de", word);
|
||||
return f.extra ? `${f.main} (${f.extra})` : f.main;
|
||||
};
|
||||
|
||||
it("a pack needs its size; without one it is not an amount", () => {
|
||||
expect(toBase(1, "can", "g", 400)).toBe(400);
|
||||
expect(toBase(1.5, "jar", "g", 190)).toBe(285);
|
||||
expect(toBase(1, "can", "g")).toBeNull();
|
||||
expect(toBase(1, "bunch", "piece", 6)).toBe(6);
|
||||
});
|
||||
|
||||
it("spoons first with the weight in brackets, packs the other way round", () => {
|
||||
expect(show(30, "ml", "tbsp")).toBe("2 EL (30 ml)");
|
||||
expect(show(6, "g", "tsp")).toBe("1½ TL (6 g)");
|
||||
expect(show(0.5, "g", "pinch")).toBe("1 Prise");
|
||||
expect(show(400, "g", "can", 400)).toBe("400 g (1 Dose)");
|
||||
expect(show(800, "g", "can", 400)).toBe("800 g (2 Dosen)");
|
||||
expect(show(6, "piece", "bunch", 6)).toBe("6 (1 Bund)");
|
||||
});
|
||||
|
||||
it("scales with kitchen fractions", () => {
|
||||
// 1 Dose für 4 Portionen → 2 Portionen
|
||||
expect(show((400 / 4) * 2, "g", "can", 400)).toBe("200 g (½ Dose)");
|
||||
expect(show((45 / 4) * 2, "ml", "tbsp")).toBe("1½ EL (23 ml)");
|
||||
// ein Achtel Packung Butter: nur Gramm
|
||||
expect(show(30, "g", "pack", 250)).toBe("30 g");
|
||||
});
|
||||
|
||||
it("back to the unit that was typed, for editing", () => {
|
||||
expect(fromBase(30, "tbsp", "ml")).toBe(2);
|
||||
expect(fromBase(800, "can", "g", 400)).toBe(2);
|
||||
expect(fromBase(30, "tbsp", "piece")).toBeNull();
|
||||
});
|
||||
|
||||
it("old dishes get spoons or packs where they fit, never pinches", () => {
|
||||
expect(impliedKitchenUnit(30, "ml", "tbsp", null, null)).toBe("tbsp");
|
||||
expect(impliedKitchenUnit(500, "ml", "tbsp", null, null)).toBeNull();
|
||||
expect(impliedKitchenUnit(400, "g", "can", "can", 400)).toBe("can");
|
||||
expect(impliedKitchenUnit(20, "g", null, "pack", 250)).toBeNull();
|
||||
expect(impliedKitchenUnit(2, "g", "pinch", null, null)).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user