import "server-only"; import type { PoolClient } from "pg"; import type { Round } from "./rounds"; import { costOverview } from "./costs"; import { freshnessOf, suggest, type Candidate, type Reason } from "./suggest"; import { lastMine } from "./wishes"; // Der Plan einer Runde: Slots in Reihenfolge, je mit Gericht, Portionen, Koch // und Grund. Der Vorschlag kommt aus lib/suggest.ts; gesperrte Slots bleiben. export type SlotView = { id: string; position: number; dishId: string | null; title: string | null; photo: string | null; base: string | null; portions: number; cookMemberId: string | null; cookName: string | null; locked: boolean; cookedAt: string | null; reason: Reason | null; /** Wochentag, von Hand gesetzt (26.11.45), sonst null. */ plannedDay: string | null; }; function parseReason(text: string | null): Reason | null { if (!text) return null; try { return JSON.parse(text) as Reason; } catch { return null; } } export async function planSlots(client: PoolClient, roundId: string): Promise { const { rows } = await client.query( `select s.id, s.position, s.dish_id as "dishId", d.title, d.photo_path as photo, d.base, s.portions, s.cook_member_id as "cookMemberId", m.display_name as "cookName", s.locked, s.cooked_at::text as "cookedAt", s.reason, to_char(s.planned_day, 'YYYY-MM-DD') as "plannedDay" from slots s left join dishes d on d.id = s.dish_id left join members m on m.id = s.cook_member_id where s.round_id = $1 order by s.position`, [roundId], ); return rows.map((r) => ({ ...r, reason: parseReason(r.reason) })); } async function candidates(client: PoolClient): Promise { const { rows } = await client.query( `select d.id, d.title, d.base, d.is_trial as "isTrial", p.share_up::float as "shareUp", (select max(s.cooked_at) from slots s where s.dish_id = d.id)::text as "lastCooked", coalesce((select array_agg(distinct i.category) from dish_ingredients di join ingredients i on i.id = di.ingredient_id where di.dish_id = d.id), '{}') as categories from dishes d left join dish_popularity p on p.dish_id = d.id where d.archived_at is null`, ); const { classes } = await costOverview(client); return rows.map(({ categories, ...r }) => ({ ...r, freshness: freshnessOf(categories), priceClass: classes.get(r.id) ?? null })); } /** Vorschlag erstellen: ungesperrte Slots ersetzen, gesperrte behalten. */ export async function makeSuggestion(client: PoolClient, householdId: string, round: Round): Promise { await client.query("select pg_advisory_xact_lock(hashtext('plan:' || $1))", [round.id]); await client.query("delete from slots where round_id = $1 and not locked and cooked_at is null", [round.id]); const kept = (await client.query("select position, dish_id from slots where round_id = $1", [round.id])).rows as { position: number; dish_id: string | null; }[]; const wishes = ( await client.query( `select w.dish_id as "dishId", w.member_id as "memberId", m.display_name as "memberName", w.is_veto as "isVeto", w.wants_to_cook as "wantsToCook", w.is_mine as "isMine" from wishes w join members m on m.id = w.member_id where w.round_id = $1 order by w.created_at`, [round.id], ) ).rows; const previous = ( await client.query( `select s.dish_id from slots s where s.dish_id is not null and s.round_id = ( select id from rounds where id <> $1 and created_at < (select created_at from rounds where id = $1) order by created_at desc limit 1)`, [round.id], ) ).rows.map((r) => r.dish_id as string); const planned = suggest({ slots: round.slotsCount, candidates: await candidates(client), wishes, previousRound: new Set(previous), keep: kept.map((k) => k.dish_id).filter((d): d is string => !!d), expensivePerSlots: (await client.query("select expensive_per_slots as n from households")).rows[0]?.n ?? 4, owed: new Set((await lastMine(client, round.id)).filter((m) => !m.served).map((m) => m.memberId)), }); const used = new Set(kept.map((k) => k.position)); let position = 1; for (const p of planned) { while (used.has(position)) position++; await client.query( `insert into slots (household_id, round_id, position, dish_id, portions, cook_member_id, reason) values ($1, $2, $3, $4, $5, $6, $7)`, [householdId, round.id, position, p.dishId, round.defaultPortions, p.cookMemberId, JSON.stringify(p.reason)], ); used.add(position); } } export type SlotChange = { dishId?: string; portions?: number; cookMemberId?: string | null; locked?: boolean; plannedDay?: string | null }; export async function updateSlot(client: PoolClient, roundId: string, id: string, change: SlotChange): Promise { const sets: string[] = []; const values: unknown[] = [id, roundId]; const add = (sql: string, v: unknown) => { values.push(v); sets.push(`${sql} = $${values.length}`); }; if (change.dishId !== undefined) { add("dish_id", change.dishId); sets.push(`reason = '{"k":"manual"}'`); } if (change.portions !== undefined) add("portions", change.portions); if (change.cookMemberId !== undefined) add("cook_member_id", change.cookMemberId); if (change.locked !== undefined) add("locked", change.locked); if (change.plannedDay !== undefined) add("planned_day", change.plannedDay); if (!sets.length) return true; const { rowCount } = await client.query(`update slots set ${sets.join(", ")} where id = $1 and round_id = $2`, values); return rowCount === 1; } /** Ein Gericht als weiteren Slot anhängen (die Runde bekommt einen Slot mehr). */ export async function addSlot(client: PoolClient, householdId: string, round: Round, dishId: string): Promise { await client.query("select pg_advisory_xact_lock(hashtext('plan:' || $1))", [round.id]); const next = (await client.query("select coalesce(max(position), 0) + 1 as p from slots where round_id = $1", [round.id])).rows[0].p; await client.query( `insert into slots (household_id, round_id, position, dish_id, portions, reason) values ($1, $2, $3, $4, $5, '{"k":"manual"}')`, [householdId, round.id, next, dishId, round.defaultPortions], ); await client.query("update rounds set slots_count = least(14, (select count(*) from slots where round_id = $1)) where id = $1", [round.id]); } /** Slot streichen: Die Runde hat dann eine Mahlzeit weniger, ein neuer Vorschlag füllt sie nicht wieder auf. */ export async function removeSlot(client: PoolClient, round: Round, id: string): Promise { await client.query("select pg_advisory_xact_lock(hashtext('plan:' || $1))", [round.id]); const { rowCount } = await client.query("delete from slots where id = $1 and round_id = $2 and cooked_at is null", [id, round.id]); if (!rowCount) return false; await client.query( "update rounds set slots_count = greatest(1, slots_count - 1) where id = $1", [round.id], ); await renumber(client, round.id, null); return true; } /** Neue Reihenfolge (alle Slot-Kennungen der Runde in der gewünschten Folge). */ export async function renumber(client: PoolClient, roundId: string, order: string[] | null): Promise { const ids = (await client.query("select id from slots where round_id = $1 order by position", [roundId])).rows.map((r) => r.id as string); const target = order ?? ids; if (target.length !== ids.length || target.some((id) => !ids.includes(id))) return false; // Positionen sind je Runde eindeutig (aufschiebbar bis zum Ende der Transaktion). for (const [i, id] of target.entries()) await client.query("update slots set position = $2 where id = $1", [id, i + 1]); return true; } export async function approve(client: PoolClient, round: Round, memberId: string): Promise { const { rowCount } = await client.query( `update rounds set status = 'planned', approved_by = $2, approved_at = now() where id = $1 and status = 'open' and exists (select 1 from slots where round_id = $1 and dish_id is not null)`, [round.id, memberId], ); return rowCount === 1; } /** Tag eines Gerichts zum Anzeigen, z. B. „Mo., 9. Nov.“ (26.11.45). */ export function dayLabel(day: string | null, locale: string): string | null { if (!day) return null; return new Intl.DateTimeFormat(locale, { weekday: "short", day: "numeric", month: "short" }).format(new Date(`${day}T12:00:00`)); }