237 lines
10 KiB
TypeScript
237 lines
10 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 { toBase, type BaseUnit, type InputUnit } from "./units";
|
|
|
|
// Gerichte des Haushalts lesen und schreiben. Mengen kommen so, wie man sie
|
|
// für das ganze Rezept eintippt (z. B. „500 g für 4 Portionen“), und werden
|
|
// hier in Basiseinheiten pro Portion umgerechnet (CLAUDE.md, Regel 2).
|
|
// Alle Funktionen laufen in withHousehold(…).
|
|
|
|
export const INPUT_UNITS = ["g", "kg", "ml", "l", "piece", "tbsp", "tsp", "pinch"] as const;
|
|
|
|
export const dishInput = z.object({
|
|
title: z.string().trim().min(1).max(120),
|
|
portions: z.number().int().min(1).max(30),
|
|
base: z.enum(BASES).nullable(),
|
|
tags: z.array(z.enum(TAGS)).max(TAGS.length),
|
|
effortMinutes: z.number().int().min(1).max(1440).nullable(),
|
|
isTrial: z.boolean(),
|
|
sourceUrl: z.string().url().max(2000).nullable().optional(),
|
|
// Bild der importierten Rezeptseite; wird beim Anlegen geholt und als Foto gespeichert.
|
|
imageUrl: z.string().url().max(2000).nullable().optional(),
|
|
ingredients: z
|
|
.array(
|
|
z.object({
|
|
ingredientId: z.string().uuid(),
|
|
qty: z.number().positive().max(100000),
|
|
unit: z.enum(INPUT_UNITS),
|
|
note: z.string().trim().max(120).nullable().optional(),
|
|
// 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(),
|
|
})
|
|
.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;
|
|
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;
|
|
}[];
|
|
// 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 };
|
|
|
|
/** 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" from dishes where id = $1 and archived_at is null`, [id]))
|
|
.rows[0];
|
|
if (!dish) return null;
|
|
const entries = new Map((await allIngredients()).map((i) => [i.id, i]));
|
|
const ingredients = (
|
|
await client.query(
|
|
`select ingredient_id, qty_per_portion, unit, note, is_staple, product, product_pack::float as product_pack, product_cook_minutes
|
|
from dish_ingredients where dish_id = $1 order by position`,
|
|
[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,
|
|
product: r.product ? { name: r.product, pack: r.product_pack, cookMinutes: r.product_cook_minutes } : null,
|
|
}));
|
|
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;
|
|
});
|
|
}
|
|
|
|
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();
|
|
const units = new Map(all.map((i) => [i.id, i.unit]));
|
|
const rows = input.ingredients.map((i, position) => {
|
|
const base = units.get(i.ingredientId);
|
|
if (!base) throw new InvalidAmount(i.ingredientId);
|
|
const total = toBase(i.qty, i.unit as InputUnit, base);
|
|
if (total === null) throw new InvalidAmount(i.ingredientId);
|
|
// 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 values = [
|
|
input.title,
|
|
input.base,
|
|
input.tags,
|
|
input.effortMinutes,
|
|
input.isTrial,
|
|
input.sourceUrl ?? null,
|
|
];
|
|
let dishId = id;
|
|
if (dishId) {
|
|
const updated = await client.query(
|
|
`update dishes set title = $2, base = $3, tags = $4, effort_minutes = $5, is_trial = $6, source_url = $7, updated_at = now()
|
|
where id = $1 and archived_at is null`,
|
|
[dishId, ...values],
|
|
);
|
|
if (updated.rowCount !== 1) throw new Error("not found");
|
|
await client.query("delete from dish_ingredients where dish_id = $1", [dishId]);
|
|
await client.query("delete from dish_steps where dish_id = $1", [dishId]);
|
|
} else {
|
|
dishId = (
|
|
await client.query(
|
|
`insert into dishes (household_id, title, base, tags, effort_minutes, is_trial, source_url, created_by)
|
|
values ($1, $2, $3, $4, $5, $6, $7, $8) returning id`,
|
|
[householdId, ...values, memberId],
|
|
)
|
|
).rows[0].id as string;
|
|
}
|
|
for (const r of rows) {
|
|
await client.query(
|
|
`insert into dish_ingredients (household_id, dish_id, ingredient_id, qty_per_portion, unit, note, position,
|
|
product, product_pack, product_cook_minutes)
|
|
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
|
|
[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],
|
|
);
|
|
}
|
|
// 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;
|
|
}
|