// 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 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) select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry 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) 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`, [JSON.stringify(ingredients.map((i) => ({ ...i, id: idByKey.get(i.key) })))], ); } 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()) { await client.query("insert into starter_dish_steps (starter_key, position, text, timer_seconds) values ($1, $2, $3, $4)", [ s.key, p, step.text, step.timer_seconds ?? 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 }; }