import { getTestPayload } from "../helpers/get-test-payload"; import type { Payload } from "payload"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; import type { Poll, Role, User } from "@/payload-types"; import { advancePoll, castPollVote, closePoll, launchDialoguePoll, readPollOutcome, resolveDeadlineTie, resolveTie, } from "@/lib/polls/service"; import type { NpcDialoguePollConfig } from "@/lib/npc-dialogue/dialogue"; let payload: Payload; const RUN = `poll-${Date.now().toString(36)}`; const TIMEOUT = 30_000; let npcId: number; let dialogueId: number; const roleIds: number[] = []; const userIds: number[] = []; /** A poll config with the two answers most tests use. */ const config = (overrides: Partial = {}): NpcDialoguePollConfig => ({ title: `${RUN} question`, options: [{ label: "Work with them" }, { label: "Stay independent" }], durationHours: 24, ...overrides, }); const launch = async ( nodeId: string, initiatorId: number, overrides: Partial = {}, ): Promise => { const { poll } = await launchDialoguePoll(payload, { dialogueId, nodeId, initiatorId, config: config(overrides), }); return poll; }; const reload = async (id: number): Promise => (await payload.findByID({ collection: "polls", id, depth: 0, overrideAccess: true, })) as Poll; describe("Poll service", () => { beforeAll(async () => { payload = await getTestPayload(); const npc = await payload.create({ collection: "game-npcs", data: { name: `${RUN}_npc`, canMessage: true }, overrideAccess: true, }); npcId = npc.id; const dialogue = await payload.create({ collection: "npc-dialogues", data: { name: `${RUN}_dialogue`, npc: npcId, flowData: { nodes: [], edges: [] } }, overrideAccess: true, }); dialogueId = dialogue.id; const logiRole = (await payload.create({ collection: "roles", data: { name: `${RUN}-logistics`, slug: `${RUN}-logistics` }, overrideAccess: true, depth: 0, })) as unknown as Role; roleIds.push(logiRole.id); const makeUser = async (label: string, roleId?: number): Promise => { const user = (await payload.create({ collection: "users", data: { username: `${RUN}-${label}`, discordUsername: `${RUN}-${label}`, displayName: label.toUpperCase(), steamId: `7656119${Math.floor(Math.random() * 1e9)}`, password: "Test123", ...(roleId ? { roleDocs: [roleId] } : {}), }, overrideAccess: true, depth: 0, })) as unknown as User; userIds.push(user.id); return user.id; }; // Fixed ids the tests below index by position. await makeUser("initiator"); await makeUser("voter"); await makeUser("logistics", logiRole.id); await makeUser("superuser"); }, TIMEOUT); afterAll(async () => { if (!payload) return; const cleanup = async (collection: "polls" | "poll-votes" | "player-flags") => { await payload .delete({ collection, where: collection === "polls" ? { sourceKey: { contains: RUN } } : {}, overrideAccess: true, }) .catch(() => undefined); }; await cleanup("poll-votes"); await cleanup("polls"); await payload .delete({ collection: "player-flags", where: { key: { contains: RUN } }, overrideAccess: true }) .catch(() => undefined); await payload .delete({ collection: "npc-dialogues", where: { id: { equals: dialogueId } }, overrideAccess: true }) .catch(() => undefined); await payload .delete({ collection: "game-npcs", where: { id: { equals: npcId } }, overrideAccess: true }) .catch(() => undefined); await payload .delete({ collection: "users", where: { id: { in: userIds } }, overrideAccess: true }) .catch(() => undefined); await payload .delete({ collection: "roles", where: { id: { in: roleIds } }, overrideAccess: true }) .catch(() => undefined); }, TIMEOUT); describe("launch", () => { it("opens one poll per node and joins it on a later trigger", async () => { const nodeId = `${RUN}-launch`; const first = await launch(nodeId, userIds[0]); expect(first.status).toBe("open"); expect(first.options.map((o) => o.key)).toEqual(["work-with-them", "stay-independent"]); expect(first.sourceKey).toBe(`${dialogueId}:${nodeId}`); expect(first.initiatedBy).toBe(userIds[0]); const second = await launchDialoguePoll(payload, { dialogueId, nodeId, initiatorId: userIds[1], config: config({ title: "a different question" }), }); expect(second.created).toBe(false); expect(second.poll.id).toBe(first.id); // The author's later edit did not rewrite the poll people voted in. expect(second.poll.title).toBe(first.title); expect(second.poll.initiatedBy).toBe(userIds[0]); }, TIMEOUT); it("derives distinct keys for two options that read the same", async () => { const poll = await launch(`${RUN}-dupes`, userIds[0], { options: [{ label: "Yes" }, { label: "Yes" }], }); expect(poll.options.map((o) => o.key)).toEqual(["yes", "yes-2"]); }, TIMEOUT); it("refuses a poll with fewer than two labeled options", async () => { await expect( launchDialoguePoll(payload, { dialogueId, nodeId: `${RUN}-invalid`, initiatorId: userIds[0], config: config({ options: [{ label: "Only one" }, { label: " " }] }), }), ).rejects.toThrow(/at least two options/); }, TIMEOUT); }); describe("voting", () => { it("records, replaces, and retracts a ballot", async () => { const poll = await launch(`${RUN}-vote`, userIds[0]); const first = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); expect(first.ok).toBe(true); if (!first.ok) return; expect(first.tally.counts["work-with-them"]).toEqual({ raw: 1, weighted: 1 }); const changed = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["stay-independent"], }); expect(changed.ok).toBe(true); if (!changed.ok) return; expect(changed.tally.counts["work-with-them"].raw).toBe(0); expect(changed.tally.counts["stay-independent"].raw).toBe(1); expect(changed.tally.totalVotes).toBe(1); const retracted = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: [], }); expect(retracted.ok).toBe(true); if (!retracted.ok) return; expect(retracted.cleared).toBe(true); expect(retracted.tally.totalVotes).toBe(0); }, TIMEOUT); it("rejects a second answer on a single-answer poll", async () => { const poll = await launch(`${RUN}-single`, userIds[0]); const result = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them", "stay-independent"], }); expect(result).toEqual({ ok: false, reason: "too-many" }); }, TIMEOUT); it("accepts several answers when multi-select is on", async () => { const poll = await launch(`${RUN}-multi`, userIds[0], { multiSelect: true }); const result = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them", "stay-independent"], }); expect(result.ok).toBe(true); if (!result.ok) return; expect(result.tally.counts["work-with-them"].raw).toBe(1); expect(result.tally.counts["stay-independent"].raw).toBe(1); expect(result.tally.totalVotes).toBe(1); }, TIMEOUT); it("rejects an answer the poll does not carry", async () => { const poll = await launch(`${RUN}-unknown`, userIds[0]); const result = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["not-an-option"], }); expect(result).toEqual({ ok: false, reason: "invalid-answer" }); }, TIMEOUT); it("refuses a voter outside the eligible roles", async () => { const poll = await launch(`${RUN}-gated`, userIds[0], { eligibleRoleIds: [roleIds[0]] }); const outsider = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); expect(outsider).toEqual({ ok: false, reason: "ineligible" }); const member = await castPollVote(payload, { pollId: poll.id, userId: userIds[2], answers: ["work-with-them"], }); expect(member.ok).toBe(true); }, TIMEOUT); }); describe("close and resolve", () => { it("weighs a tiered vote and closes on the top score", async () => { const poll = await launch(`${RUN}-weighted`, userIds[0], { weightTiers: [{ label: "Logistics", roleIds: [roleIds[0]], multiplier: 1.5 }], }); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); await castPollVote(payload, { pollId: poll.id, userId: userIds[2], answers: ["stay-independent"], }); const closed = await closePoll(payload, { pollId: poll.id }); expect(closed.status).toBe("closed"); expect(closed.winnerKey).toBe("stay-independent"); expect(closed.resolutionMethod).toBe("votes"); const outcome = readPollOutcome(closed); expect(outcome?.counts["work-with-them"]).toEqual({ raw: 1, weighted: 1 }); expect(outcome?.counts["stay-independent"]).toEqual({ raw: 1, weighted: 1.5 }); expect(outcome?.totalWeight).toBe(2.5); }, TIMEOUT); it("gives a tie to the initiator's vote", async () => { const poll = await launch(`${RUN}-tie-initiator`, userIds[0]); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); await castPollVote(payload, { pollId: poll.id, userId: userIds[0], answers: ["stay-independent"], }); const closed = await closePoll(payload, { pollId: poll.id }); expect(closed.status).toBe("closed"); expect(closed.winnerKey).toBe("stay-independent"); expect(closed.resolutionMethod).toBe("initiator"); expect(closed.decidedBy).toBe(userIds[0]); }, TIMEOUT); it("escalates a tie the initiator cannot break, then takes a superuser decision", async () => { const poll = await launch(`${RUN}-tie-superuser`, userIds[0], { multiSelect: true }); // The initiator picks both tied options, so their ballot cannot discriminate. await castPollVote(payload, { pollId: poll.id, userId: userIds[0], answers: ["work-with-them", "stay-independent"], }); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them", "stay-independent"], }); const pending = await closePoll(payload, { pollId: poll.id }); expect(pending.status).toBe("pending_decision"); expect(pending.winnerKey).toBeNull(); expect(pending.decisionDeadline).toBeTruthy(); expect(readPollOutcome(pending)?.topKeys).toEqual(["work-with-them", "stay-independent"]); // A key outside the tie is refused. await expect( resolveTie(payload, { pollId: poll.id, winnerKey: "not-tied", decidedBy: userIds[3], }), ).rejects.toThrow(/not one of the tied options/); const decided = await resolveTie(payload, { pollId: poll.id, winnerKey: "stay-independent", decidedBy: userIds[3], }); expect(decided.status).toBe("closed"); expect(decided.winnerKey).toBe("stay-independent"); expect(decided.resolutionMethod).toBe("superuser"); expect(decided.decidedBy).toBe(userIds[3]); }, TIMEOUT); it("picks a random tied option once the grace period expires", async () => { const poll = await launch(`${RUN}-tie-deadline`, userIds[0], { tieGraceHours: 1 }); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); await castPollVote(payload, { pollId: poll.id, userId: userIds[2], answers: ["stay-independent"], }); const closedAt = Date.now(); const pending = await closePoll(payload, { pollId: poll.id, now: closedAt }); expect(pending.status).toBe("pending_decision"); // Still inside the grace window: nothing happens. const early = await resolveDeadlineTie(payload, { pollId: poll.id, now: closedAt + 30 * 60_000, }); expect(early.status).toBe("pending_decision"); const late = await resolveDeadlineTie(payload, { pollId: poll.id, now: closedAt + 2 * 3_600_000, rng: () => 0, }); expect(late.status).toBe("closed"); expect(late.resolutionMethod).toBe("random"); expect(late.winnerKey).toBe("work-with-them"); }, TIMEOUT); it("closes a poll nobody voted in, without a winner", async () => { const poll = await launch(`${RUN}-empty`, userIds[0]); const closed = await closePoll(payload, { pollId: poll.id }); expect(closed.status).toBe("closed"); expect(closed.winnerKey).toBeNull(); expect(closed.resolutionMethod).toBe("no_votes"); }, TIMEOUT); it("writes the result flag with the winning option's key", async () => { const flagKey = `${RUN}_alignment`; const poll = await launch(`${RUN}-flag`, userIds[0], { resultFlag: flagKey }); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); await closePoll(payload, { pollId: poll.id }); const flags = await payload.find({ collection: "player-flags", where: { key: { equals: flagKey } }, limit: 1, depth: 0, overrideAccess: true, }); expect(flags.docs).toHaveLength(1); expect(flags.docs[0].user).toBeNull(); expect(flags.docs[0].flagType).toBe("text"); expect(flags.docs[0].textValue).toBe("work-with-them"); }, TIMEOUT); it("does not write the flag when nobody voted", async () => { const flagKey = `${RUN}_empty_flag`; const poll = await launch(`${RUN}-flag-empty`, userIds[0], { resultFlag: flagKey }); await closePoll(payload, { pollId: poll.id }); const flags = await payload.find({ collection: "player-flags", where: { key: { equals: flagKey } }, limit: 1, depth: 0, overrideAccess: true, }); expect(flags.docs).toHaveLength(0); }, TIMEOUT); it("is idempotent: a second close leaves the first resolution alone", async () => { const poll = await launch(`${RUN}-idempotent`, userIds[0]); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); const first = await closePoll(payload, { pollId: poll.id }); expect(first.winnerKey).toBe("work-with-them"); // The loser changes their mind after the close; the result must not move. await castPollVote(payload, { pollId: poll.id, userId: userIds[2], answers: ["stay-independent"], }); const second = await closePoll(payload, { pollId: poll.id }); expect(second.winnerKey).toBe("work-with-them"); expect(second.resolvedAt).toBe(first.resolvedAt); }, TIMEOUT); it("refuses a vote after the poll closed", async () => { const poll = await launch(`${RUN}-closed-vote`, userIds[0]); await closePoll(payload, { pollId: poll.id }); const result = await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); expect(result).toEqual({ ok: false, reason: "closed" }); }, TIMEOUT); }); describe("advancePoll", () => { it("closes a poll whose time ran out", async () => { const poll = await launch(`${RUN}-due`, userIds[0], { durationHours: 0.25 }); await castPollVote(payload, { pollId: poll.id, userId: userIds[1], answers: ["work-with-them"], }); const before = await advancePoll(payload, { pollId: poll.id }); expect(before.status).toBe("open"); const after = await advancePoll(payload, { pollId: poll.id, now: Date.now() + 30 * 60_000, }); expect(after.status).toBe("closed"); expect(after.winnerKey).toBe("work-with-them"); }, TIMEOUT); it("leaves a settled poll untouched", async () => { const poll = await launch(`${RUN}-settled`, userIds[0]); await closePoll(payload, { pollId: poll.id }); const after = await advancePoll(payload, { pollId: poll.id, now: Date.now() + 365 * 24 * 3_600_000, }); expect(after.status).toBe("closed"); expect((await reload(poll.id)).resolvedAt).toBe(after.resolvedAt); }, TIMEOUT); }); });