diff --git a/src/lib/polls/realtime.ts b/src/lib/polls/realtime.ts new file mode 100644 index 00000000..791d23ae --- /dev/null +++ b/src/lib/polls/realtime.ts @@ -0,0 +1,20 @@ +import type { Payload } from "payload"; + +export const POLL_CHANGED_CHANNEL = "ptf_poll_changed"; + +/** + * Tell the standalone Discord bot that a poll changed, so it re-renders + * immediately instead of waiting for its next poll tick. Mirrors + * `notifyAttendanceChanged`; the bot also reconciles on a timer, so a dropped + * notification only costs latency. + */ +export async function notifyPollChanged(payload: Payload, pollId: number): Promise { + try { + await payload.db.pool.query("SELECT pg_notify($1, $2)", [ + POLL_CHANGED_CHANNEL, + JSON.stringify({ pollId }), + ]); + } catch { + // The bot's timer is the fallback; a notify failure must never fail a vote. + } +} diff --git a/src/lib/polls/service.ts b/src/lib/polls/service.ts new file mode 100644 index 00000000..4676139f --- /dev/null +++ b/src/lib/polls/service.ts @@ -0,0 +1,694 @@ +import type { Payload } from "payload"; +import type { Poll, PollVote } from "@/payload-types"; +import { applyFlagEffect } from "@/lib/npc-dialogue/flags"; +import type { NpcDialoguePollConfig } from "@/lib/npc-dialogue/dialogue"; +import { emitGameEvent } from "@/utils/event-log/emit"; +import { EventTypes } from "@/utils/event-log/eventTypes"; +import { notifyPollChanged } from "./realtime"; +import { + buildPollWeights, + pickRandomTiedOption, + resolvePollTally, + tallyPoll, + type PollCounts, + type PollOption, + type PollResolutionMethod, + type PollTally, + type PollVoteRow, + type PollWeightTier, +} from "./tally"; + +type PayloadType = Payload; + +const DEFAULT_TIE_GRACE_HOURS = 24; +const DEFAULT_DURATION_HOURS = 24; + +/** The tally frozen into `polls.outcome` when voting stops. */ +export interface PollOutcome { + /** + * JSON column: the index signature lets the object satisfy Payload's JSON + * shape without weakening the declared fields below. + */ + [key: string]: unknown; + version: 1; + counts: PollCounts; + totalVotes: number; + totalWeight: number; + topScore: number; + /** Options that shared the top score. More than one means it went to a decision. */ + topKeys: string[]; + winnerKey: string | null; + method: PollResolutionMethod | "no_votes" | null; + decidedBy: number | null; + frozenAt: string; +} + +const toMs = (value: string | number | Date): number => + value instanceof Date ? value.getTime() : new Date(value).getTime(); + +const idOf = (ref: number | { id: number } | null | undefined): number => + typeof ref === "object" && ref !== null ? ref.id : Number(ref); + +/** Role ids from a relationship that may be ids or populated docs. */ +const roleIdsOf = ( + refs: readonly (number | { id: number })[] | null | undefined, +): number[] => (refs ?? []).map(idOf).filter((id) => Number.isFinite(id)); + +/** Slugify a label into an option key, so authors never have to write one. */ +const slugifyKey = (label: string, index: number): string => { + const slug = label + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, "") + .slice(0, 40); + return slug || `option-${index + 1}`; +}; + +/** + * Turn authored options into the stored shape. Blank labels are dropped, keys + * are derived from the label when absent, and duplicates get a numeric suffix + * so two options that read the same can never collapse into one another. + */ +export function normalizePollOptions( + options: NpcDialoguePollConfig["options"], +): { key: string; label: string; emoji?: string; description?: string }[] { + const normalized: { key: string; label: string; emoji?: string; description?: string }[] = []; + const used = new Set(); + + (options ?? []).forEach((option, index) => { + const label = option.label?.trim(); + if (!label) return; + + const base = option.key?.trim() ? slugifyKey(option.key.trim(), index) : slugifyKey(label, index); + let key = base; + let suffix = 2; + while (used.has(key)) { + key = `${base}-${suffix}`; + suffix += 1; + } + used.add(key); + + normalized.push({ + key, + label, + ...(option.emoji?.trim() ? { emoji: option.emoji.trim() } : {}), + ...(option.description?.trim() ? { description: option.description.trim() } : {}), + }); + }); + + return normalized; +} + +/** Stored options as the pure tally expects them. */ +export const pollOptionsOf = (poll: Poll): PollOption[] => + poll.options.map((option) => ({ + key: option.key, + label: option.label, + emoji: option.emoji ?? null, + description: option.description ?? null, + })); + +/** Stored weight tiers as the pure tally expects them. */ +export const pollTiersOf = (poll: Poll): PollWeightTier[] => + (poll.weightTiers ?? []).map((tier) => ({ + label: tier.label, + roleIds: roleIdsOf(tier.roles), + multiplier: tier.multiplier, + })); + +export interface PollLaunchInput { + dialogueId: number; + nodeId: string; + initiatorId: number; + config: NpcDialoguePollConfig | undefined; + now?: number; +} + +export interface PollLaunchResult { + poll: Poll; + /** False when the node had already raised this poll and the player joined it. */ + created: boolean; +} + +/** + * Open the poll an `event` node configures, or return the one it already + * opened. `sourceKey` is the idempotency key: a second player reaching the same + * node joins the existing poll rather than opening a rival one, and a player + * who re-enters the conversation gets the same poll back. + */ +export async function launchDialoguePoll( + payload: PayloadType, + input: PollLaunchInput, +): Promise { + const now = input.now ?? Date.now(); + const sourceKey = `${input.dialogueId}:${input.nodeId}`; + + const existing = await payload.find({ + collection: "polls", + where: { sourceKey: { equals: sourceKey } }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const already = existing.docs[0]; + if (already) return { poll: already, created: false }; + + const config = input.config ?? {}; + const title = config.title?.trim(); + if (!title) throw new Error("This poll has no question configured."); + + const options = normalizePollOptions(config.options); + if (options.length < 2) { + throw new Error("A poll needs at least two options with labels."); + } + + const durationHours = + Number.isFinite(config.durationHours) && (config.durationHours as number) > 0 + ? (config.durationHours as number) + : DEFAULT_DURATION_HOURS; + + const tiers = (config.weightTiers ?? []) + .filter((tier) => (tier.label?.trim() ? true : false) && tier.roleIds?.length) + .map((tier) => ({ + label: tier.label!.trim(), + roles: tier.roleIds!, + multiplier: + Number.isFinite(tier.multiplier) && (tier.multiplier as number) > 0 + ? (tier.multiplier as number) + : 1, + })); + + const data = { + title, + body: config.body?.trim() || null, + options, + status: "open" as const, + closesAt: new Date(now + durationHours * 3_600_000).toISOString(), + multiSelect: config.multiSelect === true, + anonymity: config.anonymity === "anonymous" ? ("anonymous" as const) : ("public" as const), + // Array fields reject null in the drizzle write path: omit instead. + eligibleRoles: config.eligibleRoleIds?.length ? config.eligibleRoleIds : undefined, + defaultWeight: + Number.isFinite(config.defaultWeight) && (config.defaultWeight as number) > 0 + ? (config.defaultWeight as number) + : 1, + weightTiers: tiers.length ? tiers : undefined, + resultFlag: config.resultFlag?.trim() || null, + tieGraceHours: + Number.isFinite(config.tieGraceHours) && (config.tieGraceHours as number) > 0 + ? (config.tieGraceHours as number) + : DEFAULT_TIE_GRACE_HOURS, + sourceKey, + dialogue: input.dialogueId, + nodeId: input.nodeId, + initiatedBy: input.initiatorId, + openedAt: new Date(now).toISOString(), + }; + + let poll: Poll; + try { + poll = (await payload.create({ + collection: "polls", + data, + depth: 0, + overrideAccess: true, + })) as Poll; + } catch (error) { + // Two players can reach the node in the same second. The unique index on + // sourceKey decides; the loser joins the winner's poll. + const raced = await payload.find({ + collection: "polls", + where: { sourceKey: { equals: sourceKey } }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + if (raced.docs[0]) return { poll: raced.docs[0], created: false }; + throw error; + } + + await emitGameEvent(payload, { + type: EventTypes.PollOpen, + message: `Unit poll opened: ${poll.title}`, + actor: input.initiatorId, + targetCollection: "polls", + targetId: poll.id, + data: { options: options.length, closesAt: data.closesAt }, + }); + await notifyPollChanged(payload, poll.id); + + return { poll, created: true }; +} + +/** Vote rows for a poll, in the pure tally's shape. */ +export async function loadPollVoteRows( + payload: PayloadType, + pollId: number, +): Promise { + const res = await payload.find({ + collection: "poll-votes", + where: { poll: { equals: pollId } }, + limit: 1000, + depth: 0, + overrideAccess: true, + }); + + return res.docs.map((doc: PollVote) => ({ + userId: idOf(doc.user), + answers: (doc.answers ?? []).map((answer) => answer.key).filter(Boolean), + })); +} + +/** Role ids held by each voter, for weight resolution. One query for all of them. */ +export async function loadRoleIdsByUser( + payload: PayloadType, + userIds: readonly number[], +): Promise> { + const ids = [...new Set(userIds)].filter((id) => Number.isFinite(id)); + const map = new Map(); + if (ids.length === 0) return map; + + const res = await payload.find({ + collection: "users", + where: { id: { in: ids } }, + limit: ids.length, + depth: 1, + overrideAccess: true, + }); + + for (const doc of res.docs) { + const roleDocs = (doc as unknown as { roleDocs?: (number | { id: number })[] | null }) + .roleDocs; + map.set(doc.id, roleIdsOf(roleDocs)); + } + return map; +} + +export interface PollTallySnapshot { + tally: PollTally; + votes: PollVoteRow[]; + weights: Map; +} + +/** + * Tally a poll from live data. Weights come from the roles each voter holds + * right now; the result is frozen into `outcome` at close, which is what makes + * a pending tie decision stable. + */ +export async function tallyPollNow( + payload: PayloadType, + poll: Poll, +): Promise { + const votes = await loadPollVoteRows(payload, poll.id); + const roleIdsByUser = await loadRoleIdsByUser( + payload, + votes.map((vote) => vote.userId), + ); + + const weights = buildPollWeights({ + votes, + roleIdsByUser, + tiers: pollTiersOf(poll), + defaultWeight: poll.defaultWeight ?? 1, + }); + + return { + tally: tallyPoll({ options: pollOptionsOf(poll), votes, weights }), + votes, + weights, + }; +} + +/** The stored outcome, parsed defensively (the column is free-form JSON). */ +export function readPollOutcome(poll: Poll): PollOutcome | null { + const raw = poll.outcome; + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null; + const candidate = raw as Partial; + if (candidate.version !== 1 || !candidate.counts || !Array.isArray(candidate.topKeys)) { + return null; + } + return candidate as PollOutcome; +} + +/** True once voting is over, whatever the stored status says. */ +export const isPollVotingClosed = (poll: Poll, now = Date.now()): boolean => + poll.status !== "open" || toMs(poll.closesAt) <= now; + +const graceMsOf = (poll: Poll): number => + (poll.tieGraceHours ?? DEFAULT_TIE_GRACE_HOURS) * 3_600_000; + +/** + * Write the resolution: freeze the tally, name the winner, close the poll, and + * apply the result flag. This is the only place a poll becomes `closed`, so a + * double close cannot write the flag twice with different winners. + */ +async function finalizePoll( + payload: PayloadType, + input: { + poll: Poll; + tally: PollTally; + winnerKey: string | null; + method: PollOutcome["method"]; + decidedBy: number | null; + now: number; + }, +): Promise { + const { poll, tally, winnerKey, method, decidedBy, now } = input; + + const outcome: PollOutcome = { + version: 1, + counts: tally.counts, + totalVotes: tally.totalVotes, + totalWeight: tally.totalWeight, + topScore: tally.topScore, + topKeys: [...tally.topKeys], + winnerKey, + method, + decidedBy, + frozenAt: new Date(now).toISOString(), + }; + + const updated = (await payload.update({ + collection: "polls", + id: poll.id, + data: { + status: "closed", + closedAt: poll.closedAt ?? new Date(now).toISOString(), + resolvedAt: new Date(now).toISOString(), + winnerKey, + resolutionMethod: method ?? "no_votes", + decidedBy, + outcome, + }, + depth: 0, + overrideAccess: true, + })) as unknown as Poll; + + const flagKey = poll.resultFlag?.trim(); + if (flagKey && winnerKey) { + // Global flag (owner null), written through the single flag write path. + await applyFlagEffect(payload, null, flagKey, "set_text", 0, winnerKey); + } + + const winnerLabel = + poll.options.find((option) => option.key === winnerKey)?.label ?? winnerKey ?? "no decision"; + await emitGameEvent(payload, { + type: EventTypes.PollClose, + message: `Unit poll closed: ${poll.title} (${winnerLabel})`, + actor: decidedBy ?? undefined, + targetCollection: "polls", + targetId: poll.id, + data: { winnerKey, method, topKeys: outcome.topKeys }, + }); + await notifyPollChanged(payload, poll.id); + + return updated; +} + +/** + * Stop voting and resolve. A unique top score wins; a tie goes to the + * initiator's vote when it discriminates, and otherwise to a superuser with a + * grace deadline (recorded as `pending_decision`). + * + * Idempotent: a poll that is already past `open` is returned untouched. + */ +export async function closePoll( + payload: PayloadType, + input: { pollId: number; now?: number }, +): Promise { + const now = input.now ?? Date.now(); + const poll = (await payload.findByID({ + collection: "polls", + id: input.pollId, + depth: 0, + overrideAccess: true, + })) as Poll; + + if (poll.status !== "open") return poll; + + const { tally, votes } = await tallyPollNow(payload, poll); + const initiatorId = poll.initiatedBy ? idOf(poll.initiatedBy) : null; + const initiatorAnswers = initiatorId + ? (votes.find((vote) => vote.userId === initiatorId)?.answers ?? null) + : null; + + const resolution = resolvePollTally({ tally, initiatorAnswers }); + const closedAt = new Date(now).toISOString(); + + if (resolution.status === "decided") { + return finalizePoll(payload, { + poll, + tally, + winnerKey: resolution.winnerKey, + method: resolution.method, + decidedBy: resolution.method === "initiator" ? initiatorId : null, + now, + }); + } + + if (resolution.status === "none") { + return finalizePoll(payload, { + poll, + tally, + winnerKey: null, + method: "no_votes", + decidedBy: null, + now, + }); + } + + // A tie the initiator could not break. Freeze the tally so the tie set cannot + // shift while a superuser is deciding, and start the grace clock. + const outcome: PollOutcome = { + version: 1, + counts: tally.counts, + totalVotes: tally.totalVotes, + totalWeight: tally.totalWeight, + topScore: tally.topScore, + topKeys: [...resolution.tiedKeys], + winnerKey: null, + method: null, + decidedBy: null, + frozenAt: closedAt, + }; + + const pending = (await payload.update({ + collection: "polls", + id: poll.id, + data: { + status: "pending_decision", + closedAt, + decisionDeadline: new Date(now + graceMsOf(poll)).toISOString(), + outcome, + }, + depth: 0, + overrideAccess: true, + })) as unknown as Poll; + + await emitGameEvent(payload, { + type: EventTypes.PollTiePending, + message: `Unit poll tied, awaiting a superuser: ${poll.title}`, + targetCollection: "polls", + targetId: poll.id, + data: { topKeys: outcome.topKeys }, + }); + await notifyPollChanged(payload, poll.id); + + return pending; +} + +/** + * A superuser names the winner of a tied poll. Refuses a key that is not one + * of the frozen tied options, so the decision can only settle the tie it was + * asked about. + */ +export async function resolveTie( + payload: PayloadType, + input: { pollId: number; winnerKey: string; decidedBy: number; now?: number }, +): Promise { + const now = input.now ?? Date.now(); + const poll = (await payload.findByID({ + collection: "polls", + id: input.pollId, + depth: 0, + overrideAccess: true, + })) as Poll; + + if (poll.status !== "pending_decision") { + throw new Error("This poll is not waiting on a decision."); + } + + const outcome = readPollOutcome(poll); + const tiedKeys = outcome?.topKeys ?? []; + if (!tiedKeys.includes(input.winnerKey)) { + throw new Error("That option is not one of the tied options."); + } + + const { tally } = await tallyPollNow(payload, poll); + return finalizePoll(payload, { + poll, + tally, + winnerKey: input.winnerKey, + method: "superuser", + decidedBy: input.decidedBy, + now, + }); +} + +/** + * The deadline fallback: a tied poll nobody decided picks a random tied option + * once the grace period is up. `rng` is injectable for tests. + */ +export async function resolveDeadlineTie( + payload: PayloadType, + input: { pollId: number; now?: number; rng?: () => number }, +): Promise { + const now = input.now ?? Date.now(); + const poll = (await payload.findByID({ + collection: "polls", + id: input.pollId, + depth: 0, + overrideAccess: true, + })) as Poll; + + if (poll.status !== "pending_decision") return poll; + + const deadline = poll.decisionDeadline ? toMs(poll.decisionDeadline) : 0; + if (deadline > now) return poll; + + const outcome = readPollOutcome(poll); + const winnerKey = pickRandomTiedOption(outcome?.topKeys ?? [], input.rng); + if (!winnerKey) return poll; + + const { tally } = await tallyPollNow(payload, poll); + return finalizePoll(payload, { + poll, + tally, + winnerKey, + method: "random", + decidedBy: null, + now, + }); +} + +/** + * The single reconcile entry point, called by the bot tick and by the poll + * page. Whatever is due happens here, so a poll closes even when nobody is + * looking at it and a stalled bot cannot leave one open forever. + */ +export async function advancePoll( + payload: PayloadType, + input: { pollId: number; now?: number; rng?: () => number }, +): Promise { + const now = input.now ?? Date.now(); + const poll = (await payload.findByID({ + collection: "polls", + id: input.pollId, + depth: 0, + overrideAccess: true, + })) as Poll; + + if (poll.status === "open" && toMs(poll.closesAt) <= now) { + return closePoll(payload, { pollId: poll.id, now }); + } + if (poll.status === "pending_decision") { + return resolveDeadlineTie(payload, { pollId: poll.id, now, rng: input.rng }); + } + return poll; +} + +export type CastPollVoteResult = + | { ok: true; poll: Poll; tally: PollTally; cleared: boolean } + | { ok: false; reason: "not-found" | "closed" | "ineligible" | "invalid-answer" | "too-many" }; + +export interface CastPollVoteInput { + pollId: number; + userId: number; + /** Option keys. Empty retracts the vote. */ + answers: readonly string[]; + now?: number; +} + +/** + * The only vote write path, shared by the web page and the Discord buttons. + * Empty answers retract the ballot; a single-answer poll keeps at most one. + */ +export async function castPollVote( + payload: PayloadType, + input: CastPollVoteInput, +): Promise { + const now = input.now ?? Date.now(); + + const poll = (await payload + .findByID({ collection: "polls", id: input.pollId, depth: 0, overrideAccess: true }) + .catch(() => null)) as Poll | null; + if (!poll) return { ok: false, reason: "not-found" }; + + if (poll.status !== "open") return { ok: false, reason: "closed" }; + if (toMs(poll.closesAt) <= now) { + // Self-heal: the first voter after expiry closes the poll they found open. + await closePoll(payload, { pollId: poll.id, now }); + return { ok: false, reason: "closed" }; + } + + const eligible = roleIdsOf(poll.eligibleRoles); + if (eligible.length > 0) { + const roles = await loadRoleIdsByUser(payload, [input.userId]); + const held = roles.get(input.userId) ?? []; + if (!held.some((roleId) => eligible.includes(roleId))) { + return { ok: false, reason: "ineligible" }; + } + } + + const optionKeys = new Set(poll.options.map((option) => option.key)); + const answers = [...new Set(input.answers.map((answer) => answer.trim()).filter(Boolean))]; + if (answers.some((answer) => !optionKeys.has(answer))) { + return { ok: false, reason: "invalid-answer" }; + } + if (!poll.multiSelect && answers.length > 1) { + return { ok: false, reason: "too-many" }; + } + + const existing = await payload.find({ + collection: "poll-votes", + where: { + and: [{ poll: { equals: poll.id } }, { user: { equals: input.userId } }], + }, + limit: 1, + depth: 0, + overrideAccess: true, + }); + const ballot = existing.docs[0] as PollVote | undefined; + + const cleared = answers.length === 0; + if (ballot) { + if (cleared) { + await payload.delete({ + collection: "poll-votes", + id: ballot.id, + overrideAccess: true, + }); + } else { + await payload.update({ + collection: "poll-votes", + id: ballot.id, + data: { answers: answers.map((key) => ({ key })) }, + overrideAccess: true, + }); + } + } else if (!cleared) { + await payload.create({ + collection: "poll-votes", + data: { + poll: poll.id, + user: input.userId, + answers: answers.map((key) => ({ key })), + }, + overrideAccess: true, + }); + } + + await notifyPollChanged(payload, poll.id); + const { tally } = await tallyPollNow(payload, poll); + return { ok: true, poll, tally, cleared }; +} diff --git a/src/lib/polls/surface.ts b/src/lib/polls/surface.ts new file mode 100644 index 00000000..233485ba --- /dev/null +++ b/src/lib/polls/surface.ts @@ -0,0 +1,207 @@ +import type { Payload } from "payload"; +import type { Poll } from "@/payload-types"; +import { + isPollVotingClosed, + loadPollVoteRows, + readPollOutcome, + tallyPollNow, +} from "./service"; +import type { PollCounts } from "./tally"; + +/** + * Read model for the /polls surfaces. + * + * The anonymity rule lives here and nowhere else: vote rows are read with + * `overrideAccess` (members cannot read the collection at all), and voter + * identities are only included when the poll is public or the viewer is a + * superuser. Everything else is a count. + */ + +export interface PollOptionView { + key: string; + label: string; + emoji: string | null; + description: string | null; + raw: number; + weighted: number; + /** Percentage of the highest weighted score, for the bar. */ + share: number; + voters: string[]; + /** The viewer picked this option. */ + chosen: boolean; +} + +export interface PollView { + id: number; + title: string; + body: string | null; + status: Poll["status"]; + closesAt: string; + openedAt: string | null; + multiSelect: boolean; + anonymity: Poll["anonymity"]; + eligibleRoleCount: number; + options: PollOptionView[]; + totalVotes: number; + totalWeight: number; + winnerKey: string | null; + winnerLabel: string | null; + /** Options sharing the top weighted score, when the poll is waiting on a decision. */ + tiedKeys: string[]; + resolutionMethod: Poll["resolutionMethod"]; + decisionDeadline: string | null; + /** True when the poll is waiting on a superuser decision. */ + awaitingDecision: boolean; + /** True when voting is over, whatever the stored status says. */ + closed: boolean; + /** True once the poll is fully settled (closed, not awaiting a decision). */ + resolved: boolean; + /** The viewer's own answers. */ + yourAnswers: string[]; + /** The viewer may still vote. */ + canVote: boolean; + /** The viewer may settle a tie. */ + canResolve: boolean; + /** Identities are included for this viewer. */ + showsVoters: boolean; + /** The viewer opened the poll from the conversation. */ + initiated: boolean; + sourceKey: string; +} + +const idOf = (ref: number | { id: number } | null | undefined): number => + typeof ref === "object" && ref !== null ? ref.id : Number(ref); + +const memberName = (user: { displayName?: string | null; username?: string | null }): string => + user.displayName?.trim() || user.username?.trim() || "member"; + +export interface PollViewer { + userId: number; + isSuperuser: boolean; + /** Roles held by the viewer, for the eligibility gate. */ + roleIds: readonly number[]; +} + +export async function buildPollView( + payload: Payload, + poll: Poll, + viewer: PollViewer, + now = Date.now(), +): Promise { + const { tally, votes } = await tallyPollNow(payload, poll); + const outcome = readPollOutcome(poll); + const counts: PollCounts = outcome?.counts ?? tally.counts; + const totalVotes = outcome?.totalVotes ?? tally.totalVotes; + const totalWeight = outcome?.totalWeight ?? tally.totalWeight; + + const closed = isPollVotingClosed(poll, now); + const showsVoters = poll.anonymity === "public" || viewer.isSuperuser; + + // Identities, only when this viewer is allowed to see them. + const namesByOption = new Map(); + if (showsVoters && votes.length > 0) { + const userIds = [...new Set(votes.map((vote) => vote.userId))]; + const users = await payload.find({ + collection: "users", + where: { id: { in: userIds } }, + limit: userIds.length, + depth: 0, + overrideAccess: true, + }); + const nameById = new Map(users.docs.map((doc) => [doc.id, memberName(doc)])); + for (const vote of votes) { + const name = nameById.get(vote.userId) ?? `member ${vote.userId}`; + for (const key of vote.answers) { + const list = namesByOption.get(key) ?? []; + list.push(name); + namesByOption.set(key, list); + } + } + for (const [key, names] of namesByOption) { + namesByOption.set(key, [...names].sort((a, b) => a.localeCompare(b))); + } + } + + const yourAnswers = [...(votes.find((vote) => vote.userId === viewer.userId)?.answers ?? [])]; + const topWeighted = Math.max(0, ...poll.options.map((option) => counts[option.key]?.weighted ?? 0)); + const eligible = (poll.eligibleRoles ?? []).map(idOf).filter((id) => Number.isFinite(id)); + const eligibleForViewer = + eligible.length === 0 || viewer.roleIds.some((roleId) => eligible.includes(roleId)); + + const winnerOption = poll.options.find((option) => option.key === poll.winnerKey) ?? null; + + return { + id: poll.id, + title: poll.title, + body: poll.body ?? null, + status: poll.status, + closesAt: poll.closesAt, + openedAt: poll.openedAt ?? null, + multiSelect: poll.multiSelect === true, + anonymity: poll.anonymity, + eligibleRoleCount: eligible.length, + options: poll.options.map((option) => { + const optionCounts = counts[option.key] ?? { raw: 0, weighted: 0 }; + return { + key: option.key, + label: option.label, + emoji: option.emoji ?? null, + description: option.description ?? null, + raw: optionCounts.raw, + weighted: optionCounts.weighted, + share: topWeighted > 0 ? Math.round((optionCounts.weighted / topWeighted) * 100) : 0, + voters: namesByOption.get(option.key) ?? [], + chosen: yourAnswers.includes(option.key), + }; + }), + totalVotes, + totalWeight, + winnerKey: poll.winnerKey ?? null, + winnerLabel: winnerOption?.label ?? poll.winnerKey ?? null, + tiedKeys: + poll.status === "pending_decision" + ? (outcome?.topKeys ?? + poll.options + .filter((option) => (counts[option.key]?.weighted ?? 0) === topWeighted) + .map((option) => option.key)) + : [], + resolutionMethod: poll.resolutionMethod ?? null, + decisionDeadline: poll.decisionDeadline ?? null, + awaitingDecision: poll.status === "pending_decision", + closed, + resolved: poll.status === "closed", + yourAnswers, + canVote: !closed && poll.status === "open" && eligibleForViewer, + canResolve: poll.status === "pending_decision" && viewer.isSuperuser, + showsVoters, + initiated: idOf(poll.initiatedBy) === viewer.userId, + sourceKey: poll.sourceKey, + }; +} + +/** Polls for the index: live ones first, then recently closed. */ +export async function listPolls( + payload: Payload, + viewer: PollViewer, + now = Date.now(), +): Promise { + const res = await payload.find({ + collection: "polls", + limit: 60, + depth: 0, + sort: "-openedAt", + overrideAccess: true, + }); + + const views: PollView[] = []; + for (const poll of res.docs) { + views.push(await buildPollView(payload, poll, viewer, now)); + } + + const rank = (view: PollView): number => { + if (view.awaitingDecision) return 0; + if (!view.closed) return 1; + return 2; + }; + return views.sort((a, b) => rank(a) - rank(b)); +} diff --git a/src/lib/polls/tally.ts b/src/lib/polls/tally.ts new file mode 100644 index 00000000..ae0cf459 --- /dev/null +++ b/src/lib/polls/tally.ts @@ -0,0 +1,226 @@ +/** + * Poll tallying and tie resolution. Pure: no Payload, no Discord, no clock, no + * randomness that is not injected. + * + * A poll always resolves to a single winning option, even when it allows + * multiple answers per voter. The result feeds a player flag and a narrative + * branch, so "the unit chose X" has to name one X. + * + * Weights are resolved at tally time from the voter's current roles, matching + * the tech ballot. The service freezes the resulting tally when the poll + * closes, so the tie set a superuser is asked about cannot shift underneath + * them while the decision is pending. + */ + +export interface PollOption { + /** Stable slug. Votes reference options by key, never by array index. */ + key: string; + label: string; + emoji?: string | null; + description?: string | null; +} + +/** A role-based voting weight. The highest matching multiplier wins. */ +export interface PollWeightTier { + label: string; + /** Role ids from the dynamic Roles collection. */ + roleIds: readonly number[]; + multiplier: number; +} + +export interface PollVoteRow { + userId: number; + /** Option keys. Deduped, so a repeated key cannot double-count. */ + answers: readonly string[]; +} + +export interface PollOptionCount { + raw: number; + weighted: number; +} + +export type PollCounts = Record; + +export interface PollTally { + counts: PollCounts; + /** Vote documents that named at least one live option. Not weighted. */ + totalVotes: number; + /** Sum of the weights of those vote documents. */ + totalWeight: number; + /** Highest weighted score; 0 when nothing counted. */ + topScore: number; + /** Options sharing the top score. More than one means a tie. */ + topKeys: string[]; +} + +export type PollResolutionMethod = "votes" | "initiator" | "superuser" | "random"; + +export type PollResolution = + | { status: "decided"; winnerKey: string; method: PollResolutionMethod } + /** A tie the initiator could not break. Needs a superuser, then the deadline. */ + | { status: "pending"; tiedKeys: string[] } + /** No votes, or nothing that counted. There is nothing to decide. */ + | { status: "none" }; + +/** Weights are compared as integers in thousandths, so 1.1 + 1.1 ties 2.2 exactly. */ +const WEIGHT_SCALE = 1000; + +const scaleWeight = (multiplier: number): number => { + if (!Number.isFinite(multiplier) || multiplier <= 0) return WEIGHT_SCALE; + return Math.round(multiplier * WEIGHT_SCALE); +}; + +/** + * The weight a voter's ballot carries: the highest multiplier among the tiers + * they hold, or the poll's default. A voter in several weighted roles gets the + * best one, never a sum, because stacking lets one person in three roles + * outvote the unit. + * + * Equal multipliers resolve to the earlier tier in author order. + */ +export function resolvePollWeight(input: { + roleIds: Iterable; + tiers: readonly PollWeightTier[]; + defaultWeight?: number; +}): { multiplier: number; label: string | null } { + const held = new Set(input.roleIds); + let best: { multiplier: number; label: string } | null = null; + + for (const tier of input.tiers) { + if (!tier.roleIds.some((id) => held.has(id))) continue; + const multiplier = tier.multiplier > 0 ? tier.multiplier : 1; + if (!best || multiplier > best.multiplier) best = { multiplier, label: tier.label }; + } + + return best ?? { multiplier: input.defaultWeight ?? 1, label: null }; +} + +/** Weights keyed by user id, from the roles each voter holds right now. */ +export function buildPollWeights(input: { + votes: readonly PollVoteRow[]; + roleIdsByUser: ReadonlyMap; + tiers: readonly PollWeightTier[]; + defaultWeight?: number; +}): Map { + const weights = new Map(); + for (const vote of input.votes) { + if (weights.has(vote.userId)) continue; + const { multiplier } = resolvePollWeight({ + roleIds: input.roleIdsByUser.get(vote.userId) ?? [], + tiers: input.tiers, + defaultWeight: input.defaultWeight, + }); + weights.set(vote.userId, multiplier); + } + return weights; +} + +/** + * Count a poll. Answers naming an option that is not on the poll are ignored + * (defensive: writes validate, but a tally must never crash on a stale row), + * and a vote document that names no live option does not count as turnout. + */ +export function tallyPoll(input: { + options: readonly PollOption[]; + votes: readonly PollVoteRow[]; + weights: ReadonlyMap; +}): PollTally { + const counts: PollCounts = {}; + for (const option of input.options) counts[option.key] = { raw: 0, weighted: 0 }; + + const scaled: Record = {}; + for (const key of Object.keys(counts)) scaled[key] = 0; + + let totalVotes = 0; + let totalWeightScaled = 0; + + for (const vote of input.votes) { + const answers = [...new Set(vote.answers)].filter((key) => key in counts); + if (answers.length === 0) continue; + + const weightScaled = scaleWeight(input.weights.get(vote.userId) ?? 1); + totalVotes += 1; + totalWeightScaled += weightScaled; + + for (const key of answers) { + counts[key].raw += 1; + scaled[key] += weightScaled; + } + } + + for (const key of Object.keys(counts)) { + counts[key].weighted = scaled[key] / WEIGHT_SCALE; + } + + let topScaled = 0; + for (const key of Object.keys(scaled)) topScaled = Math.max(topScaled, scaled[key]); + const topKeys = + topScaled > 0 + ? Object.keys(scaled).filter((key) => scaled[key] === topScaled) + : []; + + return { + counts, + totalVotes, + totalWeight: totalWeightScaled / WEIGHT_SCALE, + topScore: topScaled / WEIGHT_SCALE, + topKeys, + }; +} + +/** + * The first rung of the tie ladder: if exactly one tied option is among the + * conversation initiator's answers, it wins. + * + * Returns null when the initiator cannot discriminate, which is the case when + * they did not vote, voted only for options outside the tie, or picked several + * tied options on a multi-answer poll. + */ +export function breakTieWithInitiator(input: { + tiedKeys: readonly string[]; + initiatorAnswers: readonly string[] | null | undefined; +}): string | null { + if (input.tiedKeys.length === 0 || !input.initiatorAnswers?.length) return null; + const picked = new Set(input.initiatorAnswers); + const matches = input.tiedKeys.filter((key) => picked.has(key)); + return matches.length === 1 ? matches[0] : null; +} + +/** + * The last rung: a random tied option, chosen after the superuser grace period + * expires. `rng` is injected so tests are deterministic. + */ +export function pickRandomTiedOption( + tiedKeys: readonly string[], + rng: () => number = Math.random, +): string | null { + if (tiedKeys.length === 0) return null; + const raw = Math.floor(rng() * tiedKeys.length); + const index = Math.min(Math.max(raw, 0), tiedKeys.length - 1); + return tiedKeys[index] ?? null; +} + +/** + * Tally plus the first two rungs of the ladder. A poll that lands on + * `status: "pending"` still needs a superuser decision (or the deadline + * fallback), which is the service's job because it writes state. + */ +export function resolvePollTally(input: { + tally: PollTally; + initiatorAnswers: readonly string[] | null | undefined; +}): PollResolution { + const { tally } = input; + + if (tally.topKeys.length === 0) return { status: "none" }; + if (tally.topKeys.length === 1) { + return { status: "decided", winnerKey: tally.topKeys[0], method: "votes" }; + } + + const byInitiator = breakTieWithInitiator({ + tiedKeys: tally.topKeys, + initiatorAnswers: input.initiatorAnswers, + }); + if (byInitiator) return { status: "decided", winnerKey: byInitiator, method: "initiator" }; + + return { status: "pending", tiedKeys: [...tally.topKeys] }; +}