Files
kai 582b4a0fca
release / which version (push) Successful in 3s
release / olares chart · sanity (push) Successful in 4s
release / app (push) Successful in 1m3s
release / tag and release (push) Successful in 2s
26.11.49: Portionen rechnen mit, mehr Maße (#50)
2026-11-08 16:55:49 +00:00

162 lines
8.7 KiB
TypeScript

import "server-only";
import type { PoolClient } from "pg";
import { aggregate, withPacks, type PlanSlotInput } from "./aggregate";
import { labelFor } from "./ingredient-name";
import type { Round } from "./rounds";
// Einkaufsliste einer Runde: aus dem Plan abgeglichen, abgehakt von allen,
// die einkaufen. Jede Änderung meldet sich über NOTIFY (lib/shopping-events.ts),
// damit „Kai hat Milch“ sofort bei allen steht.
export type Item = {
id: string;
ingredientId: string | null;
label: string;
qty: number | null;
needed: number | null;
unit: "g" | "ml" | "piece" | null;
packCount: number | null;
packSize: number | null;
packKind: "can" | "jar" | "pack" | "tub" | "bunch" | null;
dishes: string[];
aislePosition: number | null;
manual: boolean;
pantryState: "ask" | "have" | "need" | null;
checkedBy: string | null;
checkedAt: string | null;
};
export async function notifyShopping(client: PoolClient, householdId: string) {
await client.query("select pg_notify('lunch_shopping', $1)", [householdId]);
}
export async function defaultAisles(client: PoolClient) {
return (
await client.query(
`select a.position, a.name, a.ingredient_categories as categories from store_aisles a
join stores s on s.id = a.store_id where s.is_default order by a.position`,
)
).rows as { position: number; name: string; categories: string[] }[];
}
/** Liste an den Plan angleichen: Mengen nachführen, Neues dazu, Weggefallenes (nicht Abgehaktes) raus. */
/** „Barilla Spaghetti Nr. 5“ statt „Spaghetti“; mehrere Produkte: „Spaghetti (Barilla Nr. 5 / De Cecco Nr. 12)“. */
export function productLabel(name: string, products: Set<string> | undefined): string {
const list = [...(products ?? [])];
if (!list.length) return name;
if (list.length > 1) return `${name} (${list.join(" / ")})`;
// Nennt das Produkt die Zutat schon („Barilla Spaghetti Nr. 5“), reicht es; sonst „Spaghetti · Barilla Nr. 5“.
const stem = name.toLocaleLowerCase("de").slice(0, Math.max(4, name.length - 2));
return list[0]!.toLocaleLowerCase("de").includes(stem) ? list[0]! : `${name} · ${list[0]}`;
}
export async function syncList(client: PoolClient, householdId: string, round: Round, locale: string): Promise<void> {
await client.query("select pg_advisory_xact_lock(hashtext('shopping:' || $1))", [round.id]);
const rows = (
await client.query(
`select s.id as slot, d.title, s.portions, di.ingredient_id, di.qty_per_portion::float as q, di.unit,
i.category, i.pack_sizes::float[] as packs, i.pack_kind, hps.pack_size::float as house_size,
(i.pantry_default or exists (select 1 from pantry_staples p where p.ingredient_id = i.id)) as pantry,
coalesce(i.names ->> $2, i.names ->> 'de', i.key) as name,
coalesce(i.forms -> $2, i.forms -> 'en') as form,
-- Produkt am Gericht, sonst das Lieblingsprodukt des Haushalts (26.11.38).
coalesce(di.product, hp.product) as product,
(case when di.product is not null then di.product_pack else hp.product_pack end)::float as product_pack
from slots s join dishes d on d.id = s.dish_id
join dish_ingredients di on di.dish_id = d.id
join ingredients i on i.id = di.ingredient_id
left join household_products hp on hp.ingredient_id = di.ingredient_id
left join household_pack_sizes hps on hps.ingredient_id = di.ingredient_id and hps.unit = i.pack_kind
where s.round_id = $1 and s.cooked_at is null
order by s.position`,
[round.id, locale],
)
).rows;
const bySlot = new Map<string, PlanSlotInput>();
const packs = new Map<string, number[]>();
const forms = new Map<string, { one: string; other: string }>();
const kinds = new Map<string, string>();
// Produkte je Zutat aus den Gerichten der Runde: Name auf die Liste, Packung statt der Standardgrößen.
const products = new Map<string, Set<string>>();
const productPacks = new Map<string, number[]>();
for (const r of rows) {
const slot: PlanSlotInput = bySlot.get(r.slot) ?? { dishTitle: r.title, portions: r.portions, ingredients: [] };
slot.ingredients.push({ ingredientId: r.ingredient_id, name: r.name, unit: r.unit, qtyPerPortion: r.q, category: r.category, packs: r.packs, pantry: r.pantry });
bySlot.set(r.slot, slot);
// Eigene Gebindegröße des Haushalts (26.11.39) statt der üblichen Packungen.
packs.set(r.ingredient_id, r.house_size ? [r.house_size] : (r.packs ?? []));
if (r.pack_kind) kinds.set(r.ingredient_id, r.pack_kind);
if (r.form) forms.set(r.ingredient_id, r.form);
if (r.product) {
products.set(r.ingredient_id, (products.get(r.ingredient_id) ?? new Set()).add(r.product));
if (r.product_pack) productPacks.set(r.ingredient_id, [...(productPacks.get(r.ingredient_id) ?? []), r.product_pack]);
}
}
const lines = withPacks(aggregate([...bySlot.values()], await defaultAisles(client)), (id) => productPacks.get(id) ?? packs.get(id) ?? []);
const label = (l: (typeof lines)[number]) => productLabel(labelFor({ name: l.name, forms: forms.get(l.ingredientId) ?? null, unit: l.unit }, l.qty), products.get(l.ingredientId));
for (const l of lines) {
await client.query(
`insert into shopping_items (household_id, round_id, ingredient_id, label, qty, needed, unit, pack_count, pack_size,
dishes, aisle_position, pantry_state, pack_kind)
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
on conflict (round_id, ingredient_id) where not added_manually do update
set label = excluded.label, qty = excluded.qty, needed = excluded.needed, unit = excluded.unit,
pack_count = excluded.pack_count, pack_size = excluded.pack_size, pack_kind = excluded.pack_kind, dishes = excluded.dishes,
aisle_position = excluded.aisle_position,
pantry_state = case when excluded.pantry_state is null then null else coalesce(shopping_items.pantry_state, 'ask') end`,
[householdId, round.id, l.ingredientId, label(l), l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
l.dishes, l.aislePosition, l.pantry ? "ask" : null, l.pack ? (kinds.get(l.ingredientId) ?? null) : null],
);
}
await client.query(
`delete from shopping_items where round_id = $1 and not added_manually and checked_at is null
and not (ingredient_id = any($2::uuid[]))`,
[round.id, lines.map((l) => l.ingredientId)],
);
}
export async function listItems(client: PoolClient, roundId: string): Promise<Item[]> {
const { rows } = await client.query(
`select i.id, i.ingredient_id as "ingredientId", i.label, i.qty::float, i.needed::float, i.unit,
i.pack_count as "packCount", i.pack_size::float as "packSize", i.pack_kind as "packKind", i.dishes, i.aisle_position as "aislePosition",
i.added_manually as manual, i.pantry_state as "pantryState", m.display_name as "checkedBy", i.checked_at::text as "checkedAt"
from shopping_items i left join members m on m.id = i.checked_by
where i.round_id = $1
order by i.aisle_position nulls last, lower(i.label)`,
[roundId],
);
return rows;
}
/** Abhaken oder zurücknehmen; der erste Haken setzt die Runde auf „Einkauf“. */
export async function setChecked(client: PoolClient, round: Round, id: string, memberId: string, checked: boolean): Promise<boolean> {
const { rowCount } = await client.query(
`update shopping_items set checked_by = case when $3 then $4::uuid end, checked_at = case when $3 then now() end
where id = $1 and round_id = $2`,
[id, round.id, checked, memberId],
);
if (rowCount && checked && round.status === "planned") await client.query("update rounds set status = 'shopping' where id = $1", [round.id]);
return rowCount === 1;
}
/** Vorrats-Check: „Hast du noch Öl?“ — ja: nicht kaufen, nein: auf die Liste. */
export async function answerPantry(client: PoolClient, roundId: string, id: string, have: boolean): Promise<boolean> {
const { rowCount } = await client.query(
"update shopping_items set pantry_state = $3 where id = $1 and round_id = $2 and pantry_state is not null",
[id, roundId, have ? "have" : "need"],
);
return rowCount === 1;
}
export async function addManual(client: PoolClient, householdId: string, roundId: string, label: string): Promise<void> {
await client.query(
"insert into shopping_items (household_id, round_id, label, added_manually) values ($1, $2, $3, true)",
[householdId, roundId, label.trim()],
);
}
export async function removeManual(client: PoolClient, roundId: string, id: string): Promise<boolean> {
const { rowCount } = await client.query("delete from shopping_items where id = $1 and round_id = $2 and added_manually", [id, roundId]);
return rowCount === 1;
}