97 lines
4.7 KiB
TypeScript
97 lines
4.7 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
import { pool } from "@/lib/db";
|
|
import type { IngredientEntry } from "./ingredient-search";
|
|
import { needsSize, type CountUnit } from "./units";
|
|
|
|
/** Maß einer Haushaltsgröße: ein Zählmaß, oder g/ml je Stück einer Stück-Zutat (26.11.50). */
|
|
export type SizeUnit = CountUnit | "g" | "ml";
|
|
|
|
// Die kanonischen Zutaten sind global und ändern sich nur beim Einspielen
|
|
// (Neustart). Einmal laden, im Speicher halten. Eigene Zutaten eines Haushalts
|
|
// (26.11.38) kommen je Anfrage dazu — mit einem Client in seinem Kontext.
|
|
let cache: Promise<IngredientEntry[]> | null = null;
|
|
|
|
const COLUMNS = `id, key, default_unit as unit, category, names, synonyms, forms, is_group as "isGroup", parent_id as "parentId",
|
|
kitchen_unit as "kitchenUnit", pack_kind as "packKind", pack_size::float as "packSize"`;
|
|
|
|
function globalIngredients(): Promise<IngredientEntry[]> {
|
|
cache ??= pool
|
|
.query(`select ${COLUMNS} from ingredients where household_id is null order by key`)
|
|
.then((r) => r.rows as IngredientEntry[])
|
|
.catch((error) => {
|
|
cache = null;
|
|
throw error;
|
|
});
|
|
return cache;
|
|
}
|
|
|
|
/**
|
|
* Alle Zutaten; mit client (withHousehold) auch die eigenen des Haushalts und
|
|
* seine Gebindegrößen (26.11.39: „bei uns hat die Dose 500 g“).
|
|
*/
|
|
export async function allIngredients(client?: PoolClient): Promise<IngredientEntry[]> {
|
|
const global = await globalIngredients();
|
|
if (!client) return global;
|
|
const own = (await client.query(`select ${COLUMNS}, true as own from ingredients where household_id is not null order by key`)).rows as IngredientEntry[];
|
|
// Größen je Zutat und Maß (26.11.49): „1 Packung Hackfleisch = 500 g“.
|
|
const sizes = new Map<string, Record<string, number>>();
|
|
for (const r of (await client.query("select ingredient_id, unit, pack_size::float as size from household_pack_sizes")).rows) {
|
|
sizes.set(r.ingredient_id, { ...sizes.get(r.ingredient_id), [r.unit]: r.size });
|
|
}
|
|
const all = own.length ? [...global, ...own] : global;
|
|
if (!sizes.size) return all;
|
|
return all.map((i) => {
|
|
const own = sizes.get(i.id);
|
|
if (!own) return i;
|
|
// Das Gebinde der Zutat nimmt die Haushaltsgröße gleich mit (Einkaufsliste, Anzeige).
|
|
return { ...i, sizes: own, packSize: i.packKind && own[i.packKind] ? own[i.packKind] : i.packSize };
|
|
});
|
|
}
|
|
|
|
/** Größe eines Zählmaßes für den Haushalt setzen (wer Gerichte pflegt). Ohne Maß: das Gebinde der Zutat. */
|
|
export async function setPackSize(client: PoolClient, householdId: string, ingredientId: string, size: number, unit?: SizeUnit): Promise<boolean> {
|
|
const entry = (await allIngredients(client)).find((i) => i.id === ingredientId);
|
|
const kind = unit ?? entry?.packKind;
|
|
if (!entry || !kind || !needsSize(kind, entry.unit)) return false;
|
|
await client.query(
|
|
`insert into household_pack_sizes (household_id, ingredient_id, unit, pack_size) values ($1, $2, $3, $4)
|
|
on conflict (household_id, ingredient_id, unit) do update set pack_size = excluded.pack_size, updated_at = now()`,
|
|
[householdId, ingredientId, kind, size],
|
|
);
|
|
return true;
|
|
}
|
|
|
|
export async function ingredientName(id: string, locale: string, client?: PoolClient): Promise<string> {
|
|
const entry = (await allIngredients(client)).find((i) => i.id === id);
|
|
return entry?.names[locale] ?? entry?.names.en ?? "";
|
|
}
|
|
|
|
export class OwnIngredientRefused extends Error {}
|
|
|
|
/**
|
|
* Eigene Zutat für den Haushalt anlegen (26.11.38). Gehört sie zu einer Gruppe,
|
|
* steht sie im Regal der Gruppe; sonst im gewählten. Den Namen gibt es danach in
|
|
* jeder Sprache gleich — der Haushalt hat ihn so geschrieben.
|
|
*/
|
|
export async function createOwnIngredient(
|
|
client: PoolClient,
|
|
householdId: string,
|
|
input: { name: string; unit: "g" | "ml" | "piece"; parentId: string | null; category: string },
|
|
): Promise<IngredientEntry> {
|
|
const name = input.name.trim();
|
|
const all = await allIngredients(client);
|
|
const lower = name.toLocaleLowerCase("de");
|
|
if (all.some((e) => Object.values(e.names).some((n) => n.toLocaleLowerCase("de") === lower))) throw new OwnIngredientRefused("exists");
|
|
const parent = input.parentId ? all.find((e) => e.id === input.parentId && e.isGroup) : null;
|
|
if (input.parentId && !parent) throw new OwnIngredientRefused("group");
|
|
const names = { de: name, en: name, fr: name, es: name };
|
|
const { rows } = await client.query(
|
|
`insert into ingredients (key, category, default_unit, names, synonyms, household_id, parent_id)
|
|
values ('own_' || replace(gen_random_uuid()::text, '-', ''), $1, $2, $3, '{}', $4, $5)
|
|
returning ${COLUMNS}, true as own`,
|
|
[parent?.category ?? input.category, input.unit, JSON.stringify(names), householdId, parent?.id ?? null],
|
|
);
|
|
return rows[0] as IngredientEntry;
|
|
}
|