Default prices seeded per ingredient, own prices per ingredient, cost per portion with confidence dots, price classes from the household's terciles, round total in the plan with an optional guide amount, and at most one pricey dish per N slots in the suggestion. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HUc2nv7rJVU2gp3Bgtha3q
119 lines
5.9 KiB
JavaScript
119 lines
5.9 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)
|
|
select x.id, x.key, x.category, x.unit, x.names, x.synonyms, x.freshness, x.packs, x.pantry, coalesce(x.forms, '{}')
|
|
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)
|
|
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`,
|
|
[JSON.stringify(ingredients.map((i) => ({ ...i, id: idByKey.get(i.key) })))],
|
|
);
|
|
}
|
|
|
|
// 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],
|
|
);
|
|
}
|
|
|
|
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 };
|
|
}
|