Dishes remember the measure an amount was typed in (tbsp, tsp, pinch, can, jar, pack, bunch) while quantities stay in base units per portion. Spoons show first with the weight in brackets, packs show the weight first. Each ingredient brings its usual spoon (preselected) and pack size (offered, never preselected); households can change a pack size and a product pack on a dish wins. Recipe imports read cans, jars, packs and bunches, and the shopping list names the pack. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q
143 lines
7.6 KiB
JavaScript
143 lines
7.6 KiB
JavaScript
// Spielt die Vorlagen aus db/seed/*.json ein (Arbeitspaket 3): kanonische
|
|
// Zutaten, Startergerichte, Gangfolgen der Ketten. Läuft nach den Migrationen
|
|
// bei jedem Start (scripts/migrate.mjs) und ist idempotent.
|
|
//
|
|
// - Zutaten bekommen eine feste Kennung aus ihrem Schlüssel (UUID aus SHA-1).
|
|
// Haushaltsdaten und Sicherungen verweisen darauf; eine Neuinstallation
|
|
// muss dieselbe Kennung wieder vergeben. Zutaten werden nie gelöscht.
|
|
// - Startergerichte und Ketten sind Vorlagen: Was nicht mehr in den Dateien
|
|
// steht, verschwindet; was ein Haushalt übernommen hat, ist seine Kopie.
|
|
import { createHash } from "node:crypto";
|
|
import { readFile } from "node:fs/promises";
|
|
import path from "node:path";
|
|
import { fileURLToPath } from "node:url";
|
|
|
|
const DIR = process.env.SEED_DIR ?? path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "db", "seed");
|
|
|
|
/** Feste UUID (Version 5-Form) aus einem Schlüssel. */
|
|
export function stableId(kind, key) {
|
|
const h = createHash("sha1").update(`lunch:${kind}:${key}`).digest("hex");
|
|
const variant = ((parseInt(h[16], 16) & 0x3) | 0x8).toString(16);
|
|
return `${h.slice(0, 8)}-${h.slice(8, 12)}-5${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;
|
|
}
|
|
|
|
async function load(file) {
|
|
try {
|
|
return JSON.parse(await readFile(path.join(DIR, file), "utf8"));
|
|
} catch (error) {
|
|
if (error.code === "ENOENT") return [];
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
export async function seed(client) {
|
|
const ingredients = await load("ingredients.json");
|
|
const starters = [...(await load("starters.de.json")), ...(await load("starters.en.json")), ...(await load("starters.fr.json")), ...(await load("starters.es.json"))];
|
|
const chains = await load("chains.json");
|
|
const pricesDe = await load("prices.de.json");
|
|
const idByKey = new Map(ingredients.map((i) => [i.key, stableId("ingredient", i.key)]));
|
|
|
|
await client.query("begin");
|
|
try {
|
|
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,
|
|
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,
|
|
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, 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“).
|
|
await client.query(
|
|
`update ingredients i set parent_id = g.id
|
|
from jsonb_to_recordset($1::jsonb) as x(key text, parent text) join ingredients g on g.key = x.parent
|
|
where i.key = x.key and i.parent_id is distinct from g.id`,
|
|
[JSON.stringify(ingredients.filter((i) => i.parent).map((i) => ({ key: i.key, parent: i.parent })))],
|
|
);
|
|
}
|
|
|
|
// Richtpreise: Euro je übliche Menge → je Basiseinheit der Zutat.
|
|
if (pricesDe.prices?.length) {
|
|
await client.query("delete from default_prices where currency = $1", [pricesDe.currency]);
|
|
await client.query(
|
|
`insert into default_prices (ingredient_id, currency, price_per_unit, unit)
|
|
select i.id, $2, x.eur / x.per, i.default_unit
|
|
from jsonb_to_recordset($1::jsonb) as x(key text, eur numeric, per numeric)
|
|
join ingredients i on i.key = x.key`,
|
|
[JSON.stringify(pricesDe.prices), pricesDe.currency],
|
|
);
|
|
// Ein Oberbegriff kostet im Schnitt seiner Sorten (gleiche Einheit), bis ein Bon mehr weiß.
|
|
await client.query(
|
|
`insert into default_prices (ingredient_id, currency, price_per_unit, unit)
|
|
select g.id, $1, avg(dp.price_per_unit), g.default_unit
|
|
from ingredients g join ingredients m on m.parent_id = g.id
|
|
join default_prices dp on dp.ingredient_id = m.id and dp.currency = $1 and dp.unit = g.default_unit
|
|
where g.is_group and not exists (select 1 from default_prices x where x.ingredient_id = g.id and x.currency = $1)
|
|
group by g.id, g.default_unit`,
|
|
[pricesDe.currency],
|
|
);
|
|
}
|
|
|
|
await client.query("delete from starter_dishes where not (key = any($1::text[]))", [starters.map((s) => s.key)]);
|
|
for (const [position, s] of starters.entries()) {
|
|
await client.query(
|
|
`insert into starter_dishes (key, locale, position, title, base, tags, effort_minutes) values ($1, $2, $3, $4, $5, $6, $7)
|
|
on conflict (key) do update set locale = excluded.locale, position = excluded.position, title = excluded.title,
|
|
base = excluded.base, tags = excluded.tags, effort_minutes = excluded.effort_minutes`,
|
|
[s.key, s.locale, position, s.title, s.base, s.tags, s.effort_minutes],
|
|
);
|
|
await client.query("delete from starter_dish_ingredients where starter_key = $1", [s.key]);
|
|
await client.query("delete from starter_dish_steps where starter_key = $1", [s.key]);
|
|
for (const [p, i] of s.ingredients.entries()) {
|
|
const id = idByKey.get(i.key);
|
|
if (!id) throw new Error(`${s.key}: unknown ingredient ${i.key}`);
|
|
await client.query(
|
|
"insert into starter_dish_ingredients (starter_key, position, ingredient_id, qty_per_portion, unit, note, is_staple) values ($1, $2, $3, $4, $5, $6, $7)",
|
|
[s.key, p, id, i.qty, i.unit, i.note ?? null, i.staple ?? false],
|
|
);
|
|
}
|
|
for (const [p, step] of s.steps.entries()) {
|
|
// Abschnitt nur, wenn die Vorlage ihn nennt; sonst ordnet lib/recipe-style.ts beim Lesen ein.
|
|
await client.query("insert into starter_dish_steps (starter_key, position, text, timer_seconds, section) values ($1, $2, $3, $4, $5)", [
|
|
s.key,
|
|
p,
|
|
step.text,
|
|
step.timer_seconds ?? null,
|
|
step.section ?? null,
|
|
]);
|
|
}
|
|
}
|
|
|
|
await client.query("delete from store_chains where not (key = any($1::text[]))", [chains.map((c) => c.key)]);
|
|
for (const [position, c] of chains.entries()) {
|
|
await client.query(
|
|
"insert into store_chains (key, name, position) values ($1, $2, $3) on conflict (key) do update set name = excluded.name, position = excluded.position",
|
|
[c.key, c.name, position],
|
|
);
|
|
await client.query("delete from chain_aisles where chain_key = $1", [c.key]);
|
|
for (const [p, a] of c.aisles.entries()) {
|
|
await client.query("insert into chain_aisles (chain_key, position, names, ingredient_categories) values ($1, $2, $3, $4)", [
|
|
c.key,
|
|
p,
|
|
JSON.stringify(a.names),
|
|
a.categories,
|
|
]);
|
|
}
|
|
}
|
|
await client.query("commit");
|
|
} catch (error) {
|
|
await client.query("rollback");
|
|
throw error;
|
|
}
|
|
return { ingredients: ingredients.length, starters: starters.length, chains: chains.length };
|
|
}
|