Files
kai 2f56f3a479
release / which version (push) Successful in 9s
release / olares chart · sanity (push) Successful in 7s
release / app (push) Successful in 1m5s
release / tag and release (push) Successful in 3s
26.11.38: Produktgruppen, eigene Zutaten, Lieblingsprodukt (#39)
2026-11-07 14:22:02 +00:00

83 lines
4.5 KiB
TypeScript

import "server-only";
import type { PoolClient } from "pg";
import { currentPrices, dishCost, priceClasses, withGroupPrices, type DishCost, type PriceClass, type PricePoint } from "./pricing";
import { toBase, type BaseUnit, type InputUnit } from "./units";
// Preise und Kosten aus der Datenbank (Rechnen in lib/pricing.ts).
/** Grundvorrat für die Kosten: was die 5-%-Pauschale abdeckt (Gewürze, Öl und Essig,
* Backzutaten) oder am Gericht als Grundvorrat markiert ist. Nicht `pantry_default` —
* das steuert nur die Frage „Hast du noch?“; Nudeln und Dosentomaten kosten Geld. */
export const STAPLE_SQL = "(di.is_staple or i.category in ('spices', 'oil_vinegar', 'baking'))";
export async function householdCurrency(client: PoolClient): Promise<string> {
return ((await client.query("select currency from households")).rows[0]?.currency as string | undefined) ?? "EUR";
}
/** Alle Preispunkte des Haushalts plus Richtpreise in seiner Währung. */
export async function loadPrices(client: PoolClient, currency: string): Promise<Map<string, PricePoint>> {
const { rows } = await client.query(
`select ingredient_id as "ingredientId", price_per_unit::float as "pricePerUnit", unit, source,
observed_at::text as "observedAt", coalesce(store_id = (select id from stores where is_default limit 1), false) as "mainStore"
from price_points
union all
select ingredient_id, price_per_unit::float, unit, 'default', '1970-01-01', false
from default_prices where currency = $1`,
[currency],
);
const members = new Map<string, string[]>();
for (const r of (await client.query("select id, parent_id from ingredients where parent_id is not null")).rows as { id: string; parent_id: string }[])
members.set(r.parent_id, [...(members.get(r.parent_id) ?? []), r.id]);
return withGroupPrices(currentPrices(rows), members);
}
/** Kosten pro Portion je Gericht (alle oder die genannten). */
export async function dishCosts(client: PoolClient, prices: Map<string, PricePoint>, dishIds?: string[]): Promise<Map<string, DishCost>> {
const { rows } = await client.query(
`select di.dish_id, di.ingredient_id, di.qty_per_portion::float as q, di.unit, ${STAPLE_SQL} as staple
from dish_ingredients di join ingredients i on i.id = di.ingredient_id join dishes d on d.id = di.dish_id
where d.archived_at is null and ($1::uuid[] is null or di.dish_id = any($1))`,
[dishIds ?? null],
);
const lines = new Map<string, { ingredientId: string; qtyPerPortion: number; unit: "g" | "ml" | "piece"; staple: boolean }[]>();
for (const r of rows) {
lines.set(r.dish_id, [...(lines.get(r.dish_id) ?? []), { ingredientId: r.ingredient_id, qtyPerPortion: r.q, unit: r.unit, staple: r.staple }]);
}
return new Map([...lines].map(([id, l]) => [id, dishCost(l, prices)]));
}
/** Kosten und Preisklasse aller Gerichte des Haushalts (Klassen aus den Terzilen). */
export async function costOverview(client: PoolClient): Promise<{ currency: string; costs: Map<string, DishCost>; classes: Map<string, PriceClass> }> {
const currency = await householdCurrency(client);
const costs = await dishCosts(client, await loadPrices(client, currency));
const classes = priceClasses(new Map([...costs].map(([id, c]) => [id, c.perPortion])));
return { currency, costs, classes };
}
export class PriceRefused extends Error {}
/** Eigener Preis: „2,49 € für 500 g“ → je Basiseinheit der Zutat. */
export async function setManualPrice(
client: PoolClient,
householdId: string,
ingredientId: string,
price: number,
amount: number,
unit: InputUnit,
): Promise<void> {
// Basis folgt der eingegebenen Einheit (kg → g, l → ml), sonst der Zutat:
// ein Gericht kann Knoblauch in Stück und ein anderes in Gramm führen.
const family: Partial<Record<InputUnit, BaseUnit>> = { g: "g", kg: "g", ml: "ml", l: "ml", cl: "ml", piece: "piece" };
const known = (await client.query("select default_unit from ingredients where id = $1", [ingredientId])).rows[0]?.default_unit as BaseUnit | undefined;
if (!known) throw new PriceRefused("ingredient");
const base = family[unit] ?? known;
const qty = toBase(amount, unit, base);
if (!qty || qty <= 0 || price < 0) throw new PriceRefused("amount");
const store = (await client.query("select id from stores where is_default limit 1")).rows[0]?.id ?? null;
await client.query(
`insert into price_points (household_id, ingredient_id, store_id, price_per_unit, unit, source)
values ($1, $2, $3, $4, $5, 'manual')`,
[householdId, ingredientId, store, price / qty, base],
);
}