254 lines
12 KiB
TypeScript
254 lines
12 KiB
TypeScript
import "server-only";
|
|
import type { PoolClient } from "pg";
|
|
|
|
// Wünschen (Konzept, „Wünschen“ und „Gamification“): Jede Person hat je Runde
|
|
// Jetons (households.tokens_per_round) und Vetos (vetos_per_round). Ein Tipp
|
|
// ist ein Wunsch; zweimal gewünscht heißt „Favorit der Runde“. Gezählt wird
|
|
// hier, nie in der Oberfläche.
|
|
|
|
/** Wünschen darf jede Person im Haushalt, die mitisst — auch Kinder (Paket 5b) und Jugendliche, keine Gäste. */
|
|
export const WISHERS = ["admin", "member", "teen", "child"] as const;
|
|
|
|
export type Budget = { tokens: number; tokensLeft: number; vetos: number; vetosLeft: number };
|
|
|
|
export type WishEntry = {
|
|
dishId: string;
|
|
memberId: string;
|
|
memberName: string;
|
|
note: string | null;
|
|
wantsToCook: boolean;
|
|
isVeto: boolean;
|
|
/** Gegenvorschlag zu einem Veto: kostet keinen Jeton. */
|
|
viaVeto: boolean;
|
|
/** „Mein Gericht“: garantiert im Plan, kein Veto streicht es. */
|
|
isMine: boolean;
|
|
};
|
|
|
|
export async function budget(client: PoolClient, roundId: string, memberId: string): Promise<Budget> {
|
|
const { rows } = await client.query(
|
|
`select h.tokens_per_round as tokens, h.vetos_per_round as vetos,
|
|
count(w.id) filter (where not w.is_veto and w.veto_id is null)::int as wished,
|
|
count(w.id) filter (where w.is_veto and not exists (
|
|
select 1 from wishes m where m.round_id = w.round_id and m.dish_id = w.dish_id and m.is_mine))::int as vetoed
|
|
from households h
|
|
left join wishes w on w.round_id = $1 and w.member_id = $2
|
|
group by h.id`,
|
|
[roundId, memberId],
|
|
);
|
|
const r = rows[0] ?? { tokens: 0, vetos: 0, wished: 0, vetoed: 0 };
|
|
return { tokens: r.tokens, tokensLeft: Math.max(0, r.tokens - r.wished), vetos: r.vetos, vetosLeft: Math.max(0, r.vetos - r.vetoed) };
|
|
}
|
|
|
|
/**
|
|
* Alle Wünsche und Vetos der Runde. Wer ein Veto eingelegt hat, sehen nur
|
|
* Erwachsene (Kai, 7.11.2026): Ein Veto mit Namen ist eine Bühne zum Ärgern.
|
|
*/
|
|
export async function roundWishes(client: PoolClient, roundId: string, viewer?: { memberId: string; adult: boolean }): Promise<WishEntry[]> {
|
|
const { rows } = await client.query(
|
|
`select w.dish_id as "dishId", w.member_id as "memberId", m.display_name as "memberName", w.note,
|
|
w.wants_to_cook as "wantsToCook", w.is_veto as "isVeto",
|
|
w.veto_id is not null as "viaVeto", 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`,
|
|
[roundId],
|
|
);
|
|
if (!viewer || viewer.adult) return rows;
|
|
return rows.map((e: WishEntry) => (e.isVeto && e.memberId !== viewer.memberId ? { ...e, memberId: "", memberName: "", note: null } : e));
|
|
}
|
|
|
|
/** Gerichte, die mindestens zwei Personen gewünscht haben. */
|
|
export function favorites(entries: WishEntry[]): Set<string> {
|
|
const by = new Map<string, Set<string>>();
|
|
for (const e of entries) if (!e.isVeto) by.set(e.dishId, (by.get(e.dishId) ?? new Set()).add(e.memberId));
|
|
return new Set([...by].filter(([, members]) => members.size >= 2).map(([dish]) => dish));
|
|
}
|
|
|
|
export class WishRefused extends Error {
|
|
constructor(public reason: "noRound" | "noTokens" | "noVetos" | "dish" | "already" | "alternative" | "protected" | "repeat" | "notWished" | "closed") {
|
|
super(reason);
|
|
}
|
|
}
|
|
|
|
type WishOptions = { note?: string | null; wantsToCook?: boolean; veto?: boolean; alternativeDishId?: string };
|
|
|
|
/** Wunsch oder Veto für ein Gericht der offenen Runde. Zählt unter Sperre je Person. */
|
|
/**
|
|
* Die offene Runde, in der man noch wünschen darf. Nach der Frist (rounds.wish_deadline,
|
|
* 26.11.53) ist Wünschen geschlossen — der Plan bleibt für Planende änderbar.
|
|
*/
|
|
async function openRoundFor(client: PoolClient): Promise<{ id: string }> {
|
|
const round = (
|
|
await client.query("select id, coalesce(wish_deadline <= now(), false) as closed from rounds where status = 'open' order by created_at desc limit 1")
|
|
).rows[0] as { id: string; closed: boolean } | undefined;
|
|
if (!round) throw new WishRefused("noRound");
|
|
if (round.closed) throw new WishRefused("closed");
|
|
return { id: round.id };
|
|
}
|
|
|
|
export async function addWish(client: PoolClient, householdId: string, memberId: string, dishId: string, opts: WishOptions = {}) {
|
|
await client.query("select pg_advisory_xact_lock(hashtext('wish:' || $1))", [memberId]);
|
|
const round = await openRoundFor(client);
|
|
const dish = (await client.query("select id from dishes where id = $1 and archived_at is null", [dishId])).rows[0];
|
|
if (!dish) throw new WishRefused("dish");
|
|
// Gegen „Mein Gericht“ hilft kein Veto — es würde nur verbraucht.
|
|
if (opts.veto && (await client.query("select 1 from wishes where round_id = $1 and dish_id = $2 and is_mine", [round.id, dishId])).rowCount)
|
|
throw new WishRefused("protected");
|
|
const b = await budget(client, round.id, memberId);
|
|
if (opts.veto ? b.vetosLeft < 1 : b.tokensLeft < 1) throw new WishRefused(opts.veto ? "noVetos" : "noTokens");
|
|
// Veto nur mit Gegenvorschlag: ein Gericht aus dem Pool, das in dieser Runde noch niemand nennt.
|
|
if (opts.veto) {
|
|
const alt = opts.alternativeDishId;
|
|
const ok =
|
|
alt &&
|
|
alt !== dishId &&
|
|
(
|
|
await client.query(
|
|
`select 1 from dishes d where d.id = $1 and d.archived_at is null and not d.is_trial
|
|
and not exists (select 1 from wishes w where w.round_id = $2 and w.dish_id = d.id)`,
|
|
[alt, round.id],
|
|
)
|
|
).rowCount;
|
|
if (!ok) throw new WishRefused("alternative");
|
|
}
|
|
const { rows } = await client.query(
|
|
`insert into wishes (household_id, round_id, member_id, dish_id, note, wants_to_cook, is_veto)
|
|
values ($1, $2, $3, $4, $5, $6, $7) on conflict (round_id, member_id, dish_id) do nothing returning id`,
|
|
[householdId, round.id, memberId, dishId, opts.note?.trim() || null, !opts.veto && !!opts.wantsToCook, !!opts.veto],
|
|
);
|
|
if (!rows[0]) throw new WishRefused("already");
|
|
if (opts.veto) {
|
|
await client.query(
|
|
`insert into wishes (household_id, round_id, member_id, dish_id, veto_id) values ($1, $2, $3, $4, $5)`,
|
|
[householdId, round.id, memberId, opts.alternativeDishId, rows[0].id],
|
|
);
|
|
}
|
|
}
|
|
|
|
/** Die Runde vor dieser (nach Anlage), oder null. */
|
|
async function previousRoundId(client: PoolClient, roundId: string): Promise<string | null> {
|
|
const { rows } = await client.query(
|
|
`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`,
|
|
[roundId],
|
|
);
|
|
return rows[0]?.id ?? null;
|
|
}
|
|
|
|
/**
|
|
* „Mein Gericht“ der Vorrunde: je Person das Gericht und ob es in den Plan kam.
|
|
* Wer leer ausging, hat diesmal Vorrang; wer es bekam, wählt diesmal ein anderes.
|
|
*/
|
|
export async function lastMine(client: PoolClient, roundId: string): Promise<{ memberId: string; dishId: string; served: boolean }[]> {
|
|
const previous = await previousRoundId(client, roundId);
|
|
if (!previous) return [];
|
|
const { rows } = await client.query(
|
|
`select w.member_id as "memberId", w.dish_id as "dishId",
|
|
exists (select 1 from slots s where s.round_id = w.round_id and s.dish_id = w.dish_id) as served
|
|
from wishes w where w.round_id = $1 and w.is_mine`,
|
|
[previous],
|
|
);
|
|
return rows;
|
|
}
|
|
|
|
/** Einen eigenen Wunsch zu „Mein Gericht“ machen (ein anderes verliert es) oder es zurücknehmen. */
|
|
// Mit `wishIn` (26.11.47, Herz auf der Karte) wünscht ein Tipp das Gericht zuerst
|
|
// (ein Jeton) — in derselben Transaktion, also ganz oder gar nicht.
|
|
export async function setMine(client: PoolClient, memberId: string, dishId: string, on: boolean, opts: { wishIn?: string } = {}): Promise<void> {
|
|
await client.query("select pg_advisory_xact_lock(hashtext('wish:' || $1))", [memberId]);
|
|
const round = await openRoundFor(client);
|
|
if (!on) {
|
|
await client.query("update wishes set is_mine = false where round_id = $1 and member_id = $2 and dish_id = $3", [round.id, memberId, dishId]);
|
|
return;
|
|
}
|
|
const ownWish = () =>
|
|
client.query("select id from wishes where round_id = $1 and member_id = $2 and dish_id = $3 and not is_veto and veto_id is null", [round.id, memberId, dishId]);
|
|
let own = (await ownWish()).rows[0];
|
|
if (!own && opts.wishIn) {
|
|
// Ein eigenes Veto oder ein Wunsch aus einem Veto wird nicht still umgedeutet.
|
|
const other = await client.query("select 1 from wishes where round_id = $1 and member_id = $2 and dish_id = $3", [round.id, memberId, dishId]);
|
|
if (other.rowCount) throw new WishRefused("notWished");
|
|
if ((await lastMine(client, round.id)).some((m) => m.memberId === memberId && m.dishId === dishId && m.served)) throw new WishRefused("repeat");
|
|
await addWish(client, opts.wishIn, memberId, dishId);
|
|
own = (await ownWish()).rows[0];
|
|
}
|
|
if (!own) throw new WishRefused("notWished");
|
|
if ((await lastMine(client, round.id)).some((m) => m.memberId === memberId && m.dishId === dishId && m.served)) throw new WishRefused("repeat");
|
|
await client.query("update wishes set is_mine = false where round_id = $1 and member_id = $2 and is_mine", [round.id, memberId]);
|
|
await client.query("update wishes set is_mine = true where id = $1", [own.id]);
|
|
}
|
|
|
|
/** Gerichte, die als Gegenvorschlag zu einem Veto taugen: Pool, in der Runde noch von niemandem genannt. */
|
|
export async function alternatives(client: PoolClient, roundId: string): Promise<{ id: string; title: string }[]> {
|
|
const { rows } = await client.query(
|
|
`select d.id, d.title from dishes d
|
|
where d.archived_at is null and not d.is_trial
|
|
and not exists (select 1 from wishes w where w.round_id = $1 and w.dish_id = d.id)
|
|
order by lower(d.title)`,
|
|
[roundId],
|
|
);
|
|
return rows;
|
|
}
|
|
|
|
/** Grund oder „Ich koche das“ an einem eigenen Wunsch ändern. */
|
|
export async function updateWish(client: PoolClient, memberId: string, dishId: string, opts: { note: string | null; wantsToCook: boolean }) {
|
|
const { rowCount } = await client.query(
|
|
`update wishes set note = $3, wants_to_cook = $4
|
|
where member_id = $1 and dish_id = $2 and not is_veto
|
|
and round_id = (select id from rounds where status = 'open' order by created_at desc limit 1)`,
|
|
[memberId, dishId, opts.note?.trim() || null, opts.wantsToCook],
|
|
);
|
|
return rowCount === 1;
|
|
}
|
|
|
|
/** Eigenen Wunsch oder eigenes Veto zurücknehmen (nur solange die Runde offen ist). */
|
|
export async function removeWish(client: PoolClient, memberId: string, dishId: string): Promise<boolean> {
|
|
await openRoundFor(client);
|
|
const { rows } = await client.query(
|
|
`delete from wishes where member_id = $1 and dish_id = $2
|
|
and round_id = (select id from rounds where status = 'open' order by created_at desc limit 1)
|
|
returning veto_id`,
|
|
[memberId, dishId],
|
|
);
|
|
// Ein Veto nimmt seinen Gegenvorschlag mit (Fremdschlüssel); der Gegenvorschlag nimmt sein Veto mit.
|
|
if (rows[0]?.veto_id) await client.query("delete from wishes where id = $1", [rows[0].veto_id]);
|
|
return rows.length === 1;
|
|
}
|
|
|
|
/** Joker „Etwas Neues“: ein zufälliges Gericht aus „Ausprobieren“, das ich noch nicht gewünscht habe. */
|
|
export async function jokerDish(client: PoolClient, memberId: string): Promise<{ id: string; title: string } | null> {
|
|
const { rows } = await client.query(
|
|
`select d.id, d.title from dishes d
|
|
where d.is_trial and d.archived_at is null
|
|
and not exists (select 1 from wishes w join rounds r on r.id = w.round_id
|
|
where w.dish_id = d.id and w.member_id = $1 and r.status = 'open')
|
|
order by random() limit 1`,
|
|
[memberId],
|
|
);
|
|
return rows[0] ?? null;
|
|
}
|
|
|
|
export type WishTile = {
|
|
id: string;
|
|
title: string;
|
|
photo: string | null;
|
|
isTrial: boolean;
|
|
effortMinutes: number | null;
|
|
shareUp: number | null;
|
|
lastCooked: string | null;
|
|
createdAt: string;
|
|
};
|
|
|
|
/** Alle wünschbaren Gerichte mit dem, was die Filter brauchen. */
|
|
export async function wishTiles(client: PoolClient): Promise<WishTile[]> {
|
|
const { rows } = await client.query(
|
|
`select d.id, d.title, d.photo_path as photo, d.is_trial as "isTrial", d.effort_minutes as "effortMinutes",
|
|
p.share_up::float as "shareUp",
|
|
(select max(s.cooked_at) from slots s where s.dish_id = d.id)::text as "lastCooked",
|
|
d.created_at::text as "createdAt"
|
|
from dishes d left join dish_popularity p on p.dish_id = d.id
|
|
where d.archived_at is null
|
|
order by lower(d.title)`,
|
|
);
|
|
return rows;
|
|
}
|