153 lines
6.1 KiB
TypeScript
153 lines
6.1 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
import { z } from "zod";
|
|
import { BASES, TAGS } from "./categories";
|
|
import { allIngredients } from "./ingredients";
|
|
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(),
|
|
}),
|
|
)
|
|
.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() }))
|
|
.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; qtyPerPortion: number; unit: BaseUnit; note: string | null; isStaple: boolean }[];
|
|
steps: { text: string; timerSeconds: number | null }[];
|
|
};
|
|
|
|
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 names = new Map((await allIngredients()).map((i) => [i.id, i.names[locale] ?? i.names.en ?? ""]));
|
|
const ingredients = (
|
|
await client.query(
|
|
"select ingredient_id, qty_per_portion, unit, note, is_staple from dish_ingredients where dish_id = $1 order by position",
|
|
[id],
|
|
)
|
|
).rows.map((r) => ({
|
|
ingredientId: r.ingredient_id,
|
|
name: names.get(r.ingredient_id) ?? "",
|
|
qtyPerPortion: Number(r.qty_per_portion),
|
|
unit: r.unit,
|
|
note: r.note,
|
|
isStaple: r.is_staple,
|
|
}));
|
|
const steps = (await client.query("select text, timer_seconds from dish_steps where dish_id = $1 order by position", [id])).rows.map(
|
|
(r) => ({ text: r.text, timerSeconds: r.timer_seconds }),
|
|
);
|
|
return { ...dish, ingredients, steps };
|
|
}
|
|
|
|
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 units = new Map((await allIngredients()).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);
|
|
return { ...i, base, perPortion: Math.round((total / input.portions) * 1000) / 1000, position };
|
|
});
|
|
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)
|
|
values ($1, $2, $3, $4, $5, $6, $7)`,
|
|
[householdId, dishId, r.ingredientId, r.perPortion, r.base, r.note ?? null, r.position],
|
|
);
|
|
}
|
|
for (const [position, s] of input.steps.entries()) {
|
|
await client.query("insert into dish_steps (household_id, dish_id, position, text, timer_seconds) values ($1, $2, $3, $4, $5)", [
|
|
householdId,
|
|
dishId,
|
|
position,
|
|
s.text,
|
|
s.timerMinutes ? s.timerMinutes * 60 : null,
|
|
]);
|
|
}
|
|
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;
|
|
}
|