314 lines
16 KiB
TypeScript
314 lines
16 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
import { z } from "zod";
|
|
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 { COUNT_UNITS, FIXED_UNITS, impliedKitchenUnit, isKitchenUnit, isMetric, isPackKind, needsSize, sizeKey, sizeOf, toBase, type BaseUnit, type DisplayUnit, 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(…).
|
|
|
|
// Seit 26.11.39 auch Gebinde, seit 26.11.49 alle Küchenmaße (lib/units.ts): Tasse, Schuss,
|
|
// Msp., Becher, Stück, Würfel, Zehe, Scheibe — Zählmaße mit Größe je Zutat.
|
|
export const INPUT_UNITS = ["g", "kg", "ml", "l", ...FIXED_UNITS, ...COUNT_UNITS] as const;
|
|
|
|
export const dishInput = z.object({
|
|
title: z.string().trim().min(1).max(120),
|
|
portions: z.number().int().min(1).max(30),
|
|
base: z.enum(BASES).nullable(),
|
|
tags: z.array(z.enum(TAGS)).max(TAGS.length),
|
|
effortMinutes: z.number().int().min(1).max(1440).nullable(),
|
|
isTrial: z.boolean(),
|
|
sourceUrl: z.string().url().max(2000).nullable().optional(),
|
|
// Bild der importierten Rezeptseite; wird beim Anlegen geholt und als Foto gespeichert.
|
|
imageUrl: z.string().url().max(2000).nullable().optional(),
|
|
ingredients: z
|
|
.array(
|
|
z.object({
|
|
ingredientId: z.string().uuid(),
|
|
qty: z.number().positive().max(100000),
|
|
unit: z.enum(INPUT_UNITS),
|
|
note: z.string().trim().max(120).nullable().optional(),
|
|
// Größe eines Zählmaßes in der Basiseinheit, wenn der Haushalt sie noch nicht kennt (26.11.49).
|
|
size: z.number().positive().max(100000).nullable().optional(),
|
|
// Produkt, das man nimmt; Packung in der Einheit der Zeile, Kochzeit laut Packung.
|
|
product: 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(),
|
|
}),
|
|
)
|
|
.max(60),
|
|
steps: z
|
|
.array(
|
|
z.object({
|
|
text: z.string().trim().min(1).max(2000),
|
|
timerMinutes: z.number().int().min(1).max(1440).nullable().optional(),
|
|
section: z.enum(SECTIONS).optional(),
|
|
}),
|
|
)
|
|
.max(40),
|
|
});
|
|
export type DishInput = z.infer<typeof dishInput>;
|
|
|
|
export type DishSummary = {
|
|
id: string;
|
|
title: string;
|
|
base: string | null;
|
|
tags: string[];
|
|
effortMinutes: number | null;
|
|
isTrial: boolean;
|
|
photo: string | null;
|
|
starterKey: string | null;
|
|
};
|
|
|
|
export type DishDetail = DishSummary & {
|
|
sourceUrl: string | null;
|
|
/** Für wie viele Portionen das Rezept eingegeben wurde (26.11.49); null bei älteren Gerichten. */
|
|
recipePortions: number | null;
|
|
ingredients: {
|
|
ingredientId: string;
|
|
name: string;
|
|
// Einzahl/Mehrzahl bei Stück („1 Zwiebel“, „2 Zwiebeln“), lib/ingredient-name.ts
|
|
forms: { one: string; other: string } | null;
|
|
qtyPerPortion: number;
|
|
unit: BaseUnit;
|
|
note: string | null;
|
|
isStaple: boolean;
|
|
product: Product | null;
|
|
/** Eingegebenes Küchenmaß („2 EL“, „1 Dose“), sonst null (26.11.39). */
|
|
displayUnit: DisplayUnit | 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;
|
|
kindSize: number | null;
|
|
sizes: Partial<Record<string, number>>;
|
|
}[];
|
|
// timerFrom: Name des Produkts, wenn der Timer von seiner Packung stammt.
|
|
steps: { section: Section; text: string; timerSeconds: number | null; ingredientIds: string[]; timerFrom?: string }[];
|
|
};
|
|
|
|
/** Produkt an einer Zutat des Gerichts; pack in der Basiseinheit der Zutat. */
|
|
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 {
|
|
const forms = Object.values(e.forms ?? {}).flatMap((f) => (f ? [f.one, f.other] : []));
|
|
return { id: e.id, names: [...Object.values(e.names), ...forms, ...e.synonyms] };
|
|
}
|
|
|
|
const summaryColumns = `id, title, base, tags, effort_minutes as "effortMinutes", is_trial as "isTrial",
|
|
photo_path as photo, starter_key as "starterKey"`;
|
|
|
|
export async function listDishes(client: PoolClient): Promise<DishSummary[]> {
|
|
const { rows } = await client.query(`select ${summaryColumns} from dishes where archived_at is null order by lower(title)`);
|
|
return rows;
|
|
}
|
|
|
|
export async function getDish(client: PoolClient, id: string, locale: string): Promise<DishDetail | null> {
|
|
const dish = (await client.query(`select ${summaryColumns}, source_url as "sourceUrl", recipe_portions as "recipePortions" from dishes where id = $1 and archived_at is null`, [id]))
|
|
.rows[0];
|
|
if (!dish) return null;
|
|
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, 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`,
|
|
[id],
|
|
)
|
|
).rows.map((r) => ({
|
|
ingredientId: r.ingredient_id,
|
|
name: entries.get(r.ingredient_id)?.names[locale] ?? entries.get(r.ingredient_id)?.names.en ?? "",
|
|
forms: entries.get(r.ingredient_id)?.forms?.[locale] ?? entries.get(r.ingredient_id)?.forms?.en ?? null,
|
|
qtyPerPortion: Number(r.qty_per_portion),
|
|
unit: r.unit,
|
|
note: r.note,
|
|
isStaple: r.is_staple,
|
|
// 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,
|
|
displayUnit: r.display_unit as DisplayUnit | null,
|
|
packKind: entries.get(r.ingredient_id)?.packKind ?? null,
|
|
// Größe zum eingegebenen Maß (26.11.49): beim Gebinde Produkt, sonst Haushalt bzw. Zutat.
|
|
packSize: sizeForDisplay(r, entries.get(r.ingredient_id)),
|
|
kitchenUnit: entries.get(r.ingredient_id)?.kitchenUnit ?? null,
|
|
// Fürs Bearbeiten (26.11.49): Gebindegröße der Zutat und alle Größen des Haushalts.
|
|
kindSize: entries.get(r.ingredient_id)?.packSize ?? null,
|
|
sizes: entries.get(r.ingredient_id)?.sizes ?? {},
|
|
})).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])
|
|
).rows as { section: Section | null; text: string; timer_seconds: number | null; ingredient_ids: string[] }[];
|
|
// Eingeordnet gespeichert: so nehmen; sonst (ältere Gerichte, Vorlagen) beim Lesen einordnen.
|
|
const own = ingredients.map((i) => entries.get(i.ingredientId)).filter((e): e is IngredientEntry => !!e).map(stepIngredient);
|
|
const steps = rows.every((r) => r.section)
|
|
? orderSections(
|
|
rows.map((r) => ({
|
|
section: r.section!,
|
|
text: r.text,
|
|
timerSeconds: r.timer_seconds,
|
|
ingredientIds: r.ingredient_ids.length ? r.ingredient_ids : linkIngredients(r.text, own),
|
|
})),
|
|
)
|
|
: styleByRules(
|
|
rows.map((r) => ({ text: r.text, timerSeconds: r.timer_seconds })),
|
|
own,
|
|
);
|
|
return { ...dish, ingredients, steps: withProductTimers(steps, ingredients) };
|
|
}
|
|
|
|
/**
|
|
* Kochzeit laut Packung: Ein Kochschritt, der eine Zutat mit Produkt-Kochzeit nennt,
|
|
* bekommt diese Zeit als Timer („Barilla Nr. 5: 9 Min.“) — sie gilt vor der Zeit im Text.
|
|
*/
|
|
export function withProductTimers<S extends { section: Section; timerSeconds: number | null; ingredientIds: string[] }>(
|
|
steps: S[],
|
|
ingredients: { ingredientId: string; product: Product | null }[],
|
|
): (S & { timerFrom?: string })[] {
|
|
return steps.map((s) => {
|
|
if (s.section !== "cook") return s;
|
|
const hit = s.ingredientIds.map((id) => ingredients.find((i) => i.ingredientId === id)?.product).find((p) => p?.cookMinutes);
|
|
return hit ? { ...s, timerSeconds: hit.cookMinutes! * 60, timerFrom: hit.name } : s;
|
|
});
|
|
}
|
|
|
|
function sizeForDisplay(
|
|
r: { display_unit: string | null; unit: BaseUnit; product: string | null; product_pack: number | null; house_pack: number | null },
|
|
entry: IngredientEntry | undefined,
|
|
): number | null {
|
|
const productPack = (r.product ? r.product_pack : r.house_pack) ?? null;
|
|
const d = r.display_unit;
|
|
if (!d || isPackKind(d)) return productPack ?? (d ? sizeOf(d, r.unit, entry ?? {}) : (entry?.packSize ?? null));
|
|
return needsSize(d, r.unit) ? sizeOf(d, r.unit, entry ?? {}) : null;
|
|
}
|
|
|
|
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 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 entry = byId.get(i.ingredientId);
|
|
if (!entry) throw new InvalidAmount(i.ingredientId);
|
|
const base = entry.unit;
|
|
const unit = i.unit as InputUnit;
|
|
const counted = needsSize(unit, base);
|
|
// Packung des Produkts: bei einem Zählmaß in der Basiseinheit („400“ g), sonst in der Einheit der Zeile.
|
|
const pack = i.product?.pack ? toBase(i.product.pack, counted ? base : unit, base) : null;
|
|
// Größe eines Zählmaßes (26.11.49): beim Gebinde zuerst das Produkt bzw. Lieblingsprodukt,
|
|
// dann was der Haushalt für Zutat und Maß kennt, dann das Gebinde der Zutat, zuletzt die
|
|
// im Formular eingetragene Größe — die wird dann für den Haushalt gemerkt.
|
|
const known = counted ? ((isPackKind(unit) ? ((i.product ? pack : null) ?? house.get(i.ingredientId) ?? null) : null) ?? sizeOf(unit, base, entry)) : null;
|
|
const size = known ?? (counted ? (i.size ?? null) : null);
|
|
const total = toBase(i.qty, unit, base, size);
|
|
if (total === null) throw new InvalidAmount(i.ingredientId);
|
|
// Eingegebenes Maß merken: Küchenmaße, und Gewicht/Volumen einer anderen Familie
|
|
// („200 ml“ Joghurt, „750 ml“ Brühwürfel, 26.11.50); kg bei g und l bei ml nicht.
|
|
const family = (u: string) => (u === "g" || u === "kg" ? "g" : u === "ml" || u === "l" ? "ml" : u);
|
|
const displayUnit = (unit !== base && isKitchenUnit(unit)) || (isMetric(unit) && family(unit) !== base) ? (unit as DisplayUnit) : null;
|
|
const rememberSize = counted && known === null && size ? { unit: sizeKey(unit), size } : null;
|
|
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position, pack, displayUnit, rememberSize };
|
|
});
|
|
const values = [
|
|
input.title,
|
|
input.base,
|
|
input.tags,
|
|
input.effortMinutes,
|
|
input.isTrial,
|
|
input.sourceUrl ?? null,
|
|
input.portions, // recipe_portions (26.11.49): Bearbeiten zeigt die Mengen wieder so
|
|
];
|
|
let dishId = id;
|
|
if (dishId) {
|
|
const updated = await client.query(
|
|
`update dishes set title = $2, base = $3, tags = $4, effort_minutes = $5, is_trial = $6, source_url = $7, recipe_portions = $8, updated_at = now()
|
|
where id = $1 and archived_at is null`,
|
|
[dishId, ...values],
|
|
);
|
|
if (updated.rowCount !== 1) throw new Error("not found");
|
|
await client.query("delete from dish_ingredients where dish_id = $1", [dishId]);
|
|
await client.query("delete from dish_steps where dish_id = $1", [dishId]);
|
|
} else {
|
|
dishId = (
|
|
await client.query(
|
|
`insert into dishes (household_id, title, base, tags, effort_minutes, is_trial, source_url, recipe_portions, created_by)
|
|
values ($1, $2, $3, $4, $5, $6, $7, $8, $9) returning id`,
|
|
[householdId, ...values, memberId],
|
|
)
|
|
).rows[0].id as string;
|
|
}
|
|
for (const r of rows) {
|
|
await client.query(
|
|
`insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, note, position,
|
|
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.displayUnit],
|
|
);
|
|
if (r.rememberSize) {
|
|
await client.query(
|
|
`insert into household_pack_sizes (household_id, ingredient_id, unit, pack_size) values ($1, $2, $3, $4)
|
|
on conflict (household_id, ingredient_id, unit) do nothing`,
|
|
[householdId, r.ingredientId, r.rememberSize.unit, r.rememberSize.size],
|
|
);
|
|
}
|
|
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);
|
|
const ruled = sectionsByRules(input.steps.map((s) => s.text));
|
|
const steps = orderSections(
|
|
input.steps.map((s, i) => ({
|
|
section: s.section ?? ruled[i]!,
|
|
text: s.text,
|
|
timerSeconds: s.timerMinutes ? s.timerMinutes * 60 : null,
|
|
ingredientIds: linkIngredients(s.text, own),
|
|
i,
|
|
})),
|
|
);
|
|
for (const [position, s] of steps.entries()) {
|
|
await client.query(
|
|
"insert into dish_steps (household_id, dish_id, position, section, text, timer_seconds, ingredient_ids) values ($1, $2, $3, $4, $5, $6, $7)",
|
|
[householdId, dishId, position, s.section, s.text, s.timerSeconds, s.ingredientIds],
|
|
);
|
|
}
|
|
return dishId;
|
|
}
|
|
|
|
/** Nachsichtig statt vorsichtig (Leitprinzip 4): Entfernen archiviert, Rückgängig holt zurück. */
|
|
export async function setArchived(client: PoolClient, id: string, archived: boolean): Promise<boolean> {
|
|
const r = await client.query(`update dishes set archived_at = ${archived ? "now()" : "null"} where id = $1`, [id]);
|
|
return r.rowCount === 1;
|
|
}
|