131 lines
6.3 KiB
TypeScript
131 lines
6.3 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
import { aggregate, withPacks, type PlanSlotInput } from "./aggregate";
|
|
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;
|
|
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. */
|
|
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.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
|
|
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
|
|
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[]>();
|
|
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);
|
|
packs.set(r.ingredient_id, r.packs ?? []);
|
|
}
|
|
const lines = withPacks(aggregate([...bySlot.values()], await defaultAisles(client)), (id) => packs.get(id) ?? []);
|
|
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)
|
|
values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)
|
|
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, 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, l.name, l.qty, l.needed, l.unit, l.pack?.count ?? null, l.pack?.size ?? null,
|
|
l.dishes, l.aislePosition, l.pantry ? "ask" : 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.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;
|
|
}
|