Compare commits
14 commits
ed7b262d4f
...
35bb0842c5
| Author | SHA1 | Date | |
|---|---|---|---|
| 35bb0842c5 | |||
| 121c1ed3dd | |||
| c0f1c9fc58 | |||
| 3291340b77 | |||
| 06dbc88a2e | |||
| d9d4ef1c08 | |||
| dee3dbea09 | |||
| c05ef12110 | |||
| 90d6435b71 | |||
| 9c49e52c8a | |||
| bf9fd09752 | |||
| 4ed5b4ee79 | |||
| 802e2391a8 | |||
| 1db89addf5 |
53 changed files with 149988 additions and 96 deletions
|
|
@ -139,6 +139,7 @@ lists the invariant that caused the most damage when ignored.
|
|||
| Marketplace & NPC negotiation | `src/lib/market/AGENTS.md` | Only "clean" locker stock can be listed; `buyListing()` is the single purchase path |
|
||||
| Superstructure interiors (rooms/jobs/stations) | `src/lib/interior/AGENTS.md` | Cancel never touches storage (refund flows through the job's collectable output); collect prechecks deposits and parks on full storage |
|
||||
| Notifications | `src/lib/notifications/AGENTS.md` | `notifyUser()` is fire-and-forget via `overrideAccess` |
|
||||
| Unit polls (NPC-triggered) | `src/lib/polls/` + `src/bot/AGENTS.md` ("Feature flow: unit polls") | `castPollVote()` is the only vote path; `poll-votes` is superuser-read only, which is what keeps anonymous polls anonymous; a poll is created once per `sourceKey` and never re-triggered |
|
||||
| Announcements | `src/lib/announcements/AGENTS.md` | Client-side evaluation (Shims pattern); role targeting uses Roles docs, not the legacy enum |
|
||||
| Narrative events editor | `src/components/admin/narrative-flow/AGENTS.md` | Flow data syncs to the Payload form via `useField().setValue()` with JSON diffing |
|
||||
| Tech tree (admin) | `src/components/admin/tech-tree/AGENTS.md` | Positions go through one bulk POST; never PATCH per node (pool exhaustion) |
|
||||
|
|
|
|||
22
CHANGELOG.md
22
CHANGELOG.md
|
|
@ -1,5 +1,27 @@
|
|||
# Changelog
|
||||
|
||||
# v0.21.0
|
||||
|
||||
A conversation can now put a question to the whole unit, and the answer is tallied in one place for everyone.
|
||||
|
||||
### Features
|
||||
|
||||
- **Unit polls.** A contact can put a question to the whole unit. The poll opens on the site and in Discord at once, and a vote cast in either place appears in the other within a second. You can move or withdraw your answer until it closes, and some polls allow more than one.
|
||||
- **Anonymous when it matters.** A poll can hide who voted and show only the counts, so a sensitive question stays private.
|
||||
- **Weighted results.** A poll can count a division's vote more heavily. Results show the raw count and the weighted total, so you can see what changed the outcome.
|
||||
- **Ties get settled.** A tied poll goes to whoever's conversation raised it. If that cannot break the tie, it waits for command, and a tied option is picked at random if no decision arrives within a day.
|
||||
- **Outcomes are recorded.** When a poll closes, the result is kept, so later conversations can refer to what the unit decided.
|
||||
|
||||
### Improvements
|
||||
|
||||
- **Long lines hold their pace.** A line that runs past a few sentences now types at the same rhythm as a short one instead of speeding up.
|
||||
|
||||
### Fixes
|
||||
|
||||
- Various bug fixes and improvements.
|
||||
|
||||
---
|
||||
|
||||
# v0.20.0
|
||||
|
||||
A mission's chain of command is now an org chart you can edit by dragging.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "polaris-task-force",
|
||||
"version": "0.20.0",
|
||||
"version": "0.21.0",
|
||||
"description": "Web app for the Arma 3 unit Polaris Task Force. Uses Next.js for client- and server-side rendering, with a Postgres database and some other neat libraries.",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { canSeeTestingDialogues, loadPlayerDialogue } from "@/lib/npc-dialogue/v
|
|||
import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments";
|
||||
import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { launchDialoguePoll } from "@/lib/polls/service";
|
||||
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
|
||||
import { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings";
|
||||
import {
|
||||
|
|
@ -72,7 +73,7 @@ export async function triggerNpcDialogueEvent(
|
|||
dialogueId: number,
|
||||
npcId: number,
|
||||
nodeId: string,
|
||||
): Promise<ActionResult> {
|
||||
): Promise<ActionResult<{ pollId: number } | undefined>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
|
||||
|
|
@ -97,9 +98,15 @@ export async function triggerNpcDialogueEvent(
|
|||
}
|
||||
|
||||
const effect: NpcDialogueEffect = node.data.effect;
|
||||
await runEffect(payload, user.id as number, npcId, effect);
|
||||
const result = await runEffect(payload, {
|
||||
userId: user.id as number,
|
||||
npcId,
|
||||
dialogueId,
|
||||
nodeId,
|
||||
effect,
|
||||
});
|
||||
|
||||
return { success: true };
|
||||
return { success: true, data: result };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") {
|
||||
|
|
@ -111,10 +118,16 @@ export async function triggerNpcDialogueEvent(
|
|||
|
||||
async function runEffect(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
userId: number,
|
||||
npcId: number,
|
||||
effect: NpcDialogueEffect,
|
||||
): Promise<void> {
|
||||
context: {
|
||||
userId: number;
|
||||
npcId: number;
|
||||
dialogueId: number;
|
||||
nodeId: string;
|
||||
effect: NpcDialogueEffect;
|
||||
},
|
||||
): Promise<{ pollId: number } | undefined> {
|
||||
const { userId, npcId, dialogueId, nodeId, effect } = context;
|
||||
|
||||
switch (effect.type) {
|
||||
case "notify": {
|
||||
await notifyUser(payload, {
|
||||
|
|
@ -183,6 +196,30 @@ async function runEffect(
|
|||
});
|
||||
break;
|
||||
}
|
||||
case "poll": {
|
||||
// Idempotent: the node raises the poll once, and every later player who
|
||||
// reaches it joins the same poll instead of opening a second one.
|
||||
const { poll, created } = await launchDialoguePoll(payload, {
|
||||
dialogueId,
|
||||
nodeId,
|
||||
initiatorId: userId,
|
||||
config: effect.poll,
|
||||
});
|
||||
|
||||
// The conversation hands the player a durable way back to the poll, and
|
||||
// says whether they are the one who opened it.
|
||||
await notifyUser(payload, {
|
||||
userId,
|
||||
type: "poll:open",
|
||||
title: poll.title,
|
||||
message: created
|
||||
? "The unit is being polled. Cast your vote."
|
||||
: "This poll is already open. Cast your vote.",
|
||||
link: `/polls/${poll.id}`,
|
||||
});
|
||||
|
||||
return { pollId: poll.id };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -178,10 +178,12 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
|
||||
// Typing animation: the unit default from the settings global, overridden by
|
||||
// this player's own preference. Read here so the dialog needs no round trip.
|
||||
// One read of the settings global for both presentation defaults.
|
||||
const dialogueSettings = dialogue ? await loadDialogueSettings(payload) : null;
|
||||
const typewriterEnabled = dialogue
|
||||
? resolveTypewriter(
|
||||
isPayloadUser(user) ? user.preferences?.dialogue?.typewriter : undefined,
|
||||
(await loadDialogueSettings(payload)).typewriterDefault,
|
||||
dialogueSettings?.typewriterDefault ?? true,
|
||||
)
|
||||
: false;
|
||||
// Sound is on unless the player turned voice clips off in their account.
|
||||
|
|
@ -207,6 +209,7 @@ export default async function NpcContactPage({ params }: NpcContactPageProps) {
|
|||
typewriter={typewriterEnabled}
|
||||
typewriterSound={typewriterSoundEnabled}
|
||||
voice={voiceEnabled}
|
||||
pacing={dialogueSettings?.pacing}
|
||||
/>
|
||||
}
|
||||
employmentSlot={
|
||||
|
|
|
|||
56
src/app/(frontend)/polls/[id]/page.tsx
Normal file
56
src/app/(frontend)/polls/[id]/page.tsx
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { ArrowLeft } from "lucide-react";
|
||||
|
||||
import { PollVotePanel } from "@/components/frontend/polls/PollVotePanel";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { advancePoll } from "@/lib/polls/service";
|
||||
import { buildPollView } from "@/lib/polls/surface";
|
||||
import type { Poll } from "@/payload-types";
|
||||
|
||||
export const metadata = {
|
||||
title: "Poll: Polaris Task Force",
|
||||
};
|
||||
|
||||
export default async function PollPage({ params }: { params: Promise<{ id: string }> }) {
|
||||
const { id } = await params;
|
||||
const pollId = Number(id);
|
||||
if (!Number.isInteger(pollId)) notFound();
|
||||
|
||||
const headers = await nextHeaders();
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
|
||||
// The (frontend) layout renders LandingPage for guests; this only guards the
|
||||
// authed render path's types.
|
||||
if (!user || user.collection !== "users") return null;
|
||||
|
||||
// Opening the page settles anything that is due, so a poll closes on time
|
||||
// even when the bot is down.
|
||||
const poll = (await advancePoll(payload, { pollId })) as Poll | null;
|
||||
if (!poll || !poll.id) notFound();
|
||||
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
const view = await buildPollView(payload, poll, {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-3xl flex-col gap-4 p-5">
|
||||
<Link
|
||||
href="/polls"
|
||||
className="flex items-center gap-1 text-xs text-muted-foreground underline-offset-4 hover:underline"
|
||||
>
|
||||
<ArrowLeft className="size-3.5" />
|
||||
All polls
|
||||
</Link>
|
||||
<PollVotePanel initialView={view} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
180
src/app/(frontend)/polls/actions.ts
Normal file
180
src/app/(frontend)/polls/actions.ts
Normal file
|
|
@ -0,0 +1,180 @@
|
|||
"use server";
|
||||
|
||||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { isPayloadUser } from "@/utils/access-control/isPayloadUser";
|
||||
import { hasPermission } from "@/utils/access-control/hasPermission";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import {
|
||||
advancePoll,
|
||||
castPollVote,
|
||||
resolveTie,
|
||||
tallyPollNow,
|
||||
type CastPollVoteResult,
|
||||
} from "@/lib/polls/service";
|
||||
import { buildPollView, type PollView, type PollViewer } from "@/lib/polls/surface";
|
||||
import type { Poll } from "@/payload-types";
|
||||
|
||||
interface ActionResult<T = undefined> {
|
||||
success: boolean;
|
||||
error?: string;
|
||||
data?: T;
|
||||
}
|
||||
|
||||
async function authenticate() {
|
||||
const payloadConfig = await config;
|
||||
const payload = await getPayload({ config: payloadConfig });
|
||||
const { headers } = await import("next/headers");
|
||||
const hdrs = await headers();
|
||||
const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false });
|
||||
|
||||
if (!isPayloadUser(user)) {
|
||||
throw new Error("Unauthorized");
|
||||
}
|
||||
|
||||
return { payload, user };
|
||||
}
|
||||
|
||||
/** The viewer's roles and superuser flag, in one cached permission load. */
|
||||
async function loadViewer(
|
||||
payload: Awaited<ReturnType<typeof getPayload>>,
|
||||
user: { id: number | string; roleDocs?: unknown },
|
||||
): Promise<PollViewer> {
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
return {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
};
|
||||
}
|
||||
|
||||
const failure = (result: Extract<CastPollVoteResult, { ok: false }>): string => {
|
||||
switch (result.reason) {
|
||||
case "not-found":
|
||||
return "That poll no longer exists.";
|
||||
case "closed":
|
||||
return "This poll has closed.";
|
||||
case "ineligible":
|
||||
return "You are not eligible to vote in this poll.";
|
||||
case "invalid-answer":
|
||||
return "That answer is not on this poll.";
|
||||
case "too-many":
|
||||
return "This poll takes one answer.";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Cast, change, or retract a vote. Empty `answers` retracts. Returns the
|
||||
* rebuilt view so the caller can render the new tally without a round trip.
|
||||
*/
|
||||
export async function castPollVoteAction(
|
||||
pollId: number,
|
||||
answers: string[],
|
||||
): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
// Close anything that is due before deciding the vote is refused: a poll
|
||||
// whose time ran out should not answer "closed" without being resolved.
|
||||
await advancePoll(payload, { pollId });
|
||||
|
||||
const result = await castPollVote(payload, {
|
||||
pollId,
|
||||
userId: viewer.userId,
|
||||
answers,
|
||||
});
|
||||
if (!result.ok) return { success: false, error: failure(result) };
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A superuser settles a tied poll. Permission is the superuser tier, which is
|
||||
* the same tier that may read vote identities.
|
||||
*/
|
||||
export async function resolvePollTieAction(
|
||||
pollId: number,
|
||||
winnerKey: string,
|
||||
): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "system:admin-access"))) {
|
||||
return { success: false, error: "Only a superuser can settle a tied poll." };
|
||||
}
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await resolveTie(payload, { pollId, winnerKey, decidedBy: viewer.userId });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Close a poll early. Staff only: polls:update. */
|
||||
export async function closePollAction(pollId: number): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
if (!(await hasPermission(payload, user, "polls:update"))) {
|
||||
return { success: false, error: "You do not have permission to close this poll." };
|
||||
}
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await advancePoll(payload, { pollId, now: Date.now() + 1 });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Lightweight refresh for the live tally, so open pages converge without SSE. */
|
||||
export async function getPollViewAction(pollId: number): Promise<ActionResult<PollView>> {
|
||||
try {
|
||||
const { payload, user } = await authenticate();
|
||||
const viewer = await loadViewer(payload, user);
|
||||
|
||||
await advancePoll(payload, { pollId });
|
||||
|
||||
const poll = await payload.findByID({
|
||||
collection: "polls",
|
||||
id: pollId,
|
||||
depth: 0,
|
||||
overrideAccess: true,
|
||||
});
|
||||
return { success: true, data: await buildPollView(payload, poll as Poll, viewer) };
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "Unknown error";
|
||||
if (message === "Unauthorized") return { success: false, error: "You must be logged in." };
|
||||
return { success: false, error: message };
|
||||
}
|
||||
}
|
||||
150
src/app/(frontend)/polls/page.tsx
Normal file
150
src/app/(frontend)/polls/page.tsx
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
import config from "@payload-config";
|
||||
import { getPayload } from "payload";
|
||||
import { headers as nextHeaders } from "next/headers";
|
||||
import Link from "next/link";
|
||||
import { Vote } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { loadUserPermissions } from "@/utils/access-control/loadUserPermissions";
|
||||
import { listPolls, type PollView } from "@/lib/polls/surface";
|
||||
|
||||
export const metadata = {
|
||||
title: "Polls: Polaris Task Force",
|
||||
};
|
||||
|
||||
const statusLabel = (view: PollView): string => {
|
||||
if (view.awaitingDecision) return "Tied";
|
||||
if (view.closed) return "Closed";
|
||||
return "Open";
|
||||
};
|
||||
|
||||
const statusClass = (view: PollView): string => {
|
||||
if (view.awaitingDecision) return "border-amber-500/50 text-amber-300";
|
||||
if (view.closed) return "border-white/20 text-muted-foreground";
|
||||
return "border-emerald-500/50 text-emerald-300";
|
||||
};
|
||||
|
||||
function PollCard({ view }: { view: PollView }) {
|
||||
const leading = [...view.options].sort((a, b) => b.weighted - a.weighted)[0];
|
||||
return (
|
||||
<Link href={`/polls/${view.id}`} className="block">
|
||||
<Card className="transition-colors hover:border-white/25">
|
||||
<CardHeader className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<Badge variant="outline" className={statusClass(view)}>
|
||||
{statusLabel(view)}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.multiSelect ? "Multiple answers" : "One answer"}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.anonymity === "anonymous" ? "Anonymous" : "Public"}
|
||||
</Badge>
|
||||
{view.initiated && (
|
||||
<Badge variant="outline" className="border-sky-500/50 text-sky-300">
|
||||
You opened this
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-base">{view.title}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span>
|
||||
{view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"}
|
||||
</span>
|
||||
<span>
|
||||
{view.closed
|
||||
? `Closed ${new Date(view.closesAt).toLocaleDateString()}`
|
||||
: `Closes ${new Date(view.closesAt).toLocaleString()}`}
|
||||
</span>
|
||||
{view.closed && view.winnerLabel && <span>Outcome: {view.winnerLabel}</span>}
|
||||
</div>
|
||||
|
||||
{leading && (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center justify-between text-xs">
|
||||
<span className="truncate">
|
||||
{leading.emoji ? `${leading.emoji} ` : ""}
|
||||
{leading.label}
|
||||
</span>
|
||||
<span className="font-mono text-muted-foreground">
|
||||
{leading.raw} · weight {Number.isInteger(leading.weighted) ? leading.weighted : leading.weighted.toFixed(2)}
|
||||
</span>
|
||||
</div>
|
||||
<Progress value={leading.share} className="h-1.5" />
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
export default async function PollsPage() {
|
||||
const headers = await nextHeaders();
|
||||
const payload = await getPayload({ config });
|
||||
const { user } = await payload.auth({ headers, canSetHeaders: false });
|
||||
|
||||
// The (frontend) layout renders LandingPage for guests; this only guards the
|
||||
// authed render path's types.
|
||||
if (!user || user.collection !== "users") return null;
|
||||
|
||||
const { isSuperuser } = await loadUserPermissions(payload, user);
|
||||
const roleDocs = (user as { roleDocs?: (number | { id: number })[] | null }).roleDocs ?? [];
|
||||
const polls = await listPolls(payload, {
|
||||
userId: Number(user.id),
|
||||
isSuperuser,
|
||||
roleIds: roleDocs.map((ref) => (typeof ref === "number" ? ref : ref.id)),
|
||||
});
|
||||
|
||||
const live = polls.filter((poll) => !poll.closed || poll.awaitingDecision);
|
||||
const past = polls.filter((poll) => poll.closed && !poll.awaitingDecision);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex w-full max-w-4xl flex-col gap-6 p-5">
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<Vote className="size-5 text-muted-foreground" />
|
||||
<h1 className="text-lg font-semibold">Unit polls</h1>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Questions the unit answers together. A conversation with an NPC can raise one; your vote
|
||||
here and on Discord are the same vote.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{live.length === 0 && past.length === 0 && (
|
||||
<Card>
|
||||
<CardContent className="py-8 text-center text-sm text-muted-foreground">
|
||||
No polls yet. They appear here when a conversation raises one.
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{live.length > 0 && (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Live
|
||||
</h2>
|
||||
{live.map((view) => (
|
||||
<PollCard key={view.id} view={view} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
|
||||
{past.length > 0 && (
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-xs font-medium uppercase tracking-wide text-muted-foreground">
|
||||
Closed
|
||||
</h2>
|
||||
{past.map((view) => (
|
||||
<PollCard key={view.id} view={view} />
|
||||
))}
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -8,7 +8,7 @@ Standalone long-running process (`bun run bot`). Imports `@payload-config` direc
|
|||
|
||||
## Env
|
||||
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `DISCORD_DEBUG_CHANNEL_ID` (sandbox channel for `/debug run ... mode:sandbox`; unset disables sandbox), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s). Logs through `payload.logger`.
|
||||
Required: `DISCORD_TOKEN`, `DISCORD_GUILD_ID` (fail-fast on missing vars in `config.ts`). Optional: `DISCORD_OPS_CHANNEL_ID`, `DISCORD_ANNOUNCE_CHANNEL_ID`, `DISCORD_CHANGELOG_CHANNEL_ID` (dedicated #releases channel for `/changelog`; falls back to the announce channel), `DISCORD_STAFF_ROLE_IDS`, `DISCORD_SIDE_OPS_CHANNEL_ID` (Friday open-slot notice channel), `DISCORD_COMMUNITY_ZEUS_ROLE_ID` (role ping for that notice), `DISCORD_NPC_EVENT_CHANNEL_ID` (NPC dispatch channel for dialogue events; unset disables posting), `DISCORD_DEBUG_CHANNEL_ID` (sandbox channel for `/debug run ... mode:sandbox`; unset disables sandbox), `APP_URL`, plus poll intervals `DISCORD_ATTENDANCE_POLL_MS` (default 60s), `DISCORD_NOTIFICATION_POLL_MS` (default 20s), `DISCORD_EVALUATION_POLL_MS` (default 60s), `DISCORD_IMMINENT_POLL_MS` (default 60s), `DISCORD_SIDE_OPS_POLL_MS` (default 30 min), `DISCORD_PRESENCE_POLL_MS` (default 30s), `DISCORD_NPC_EVENT_POLL_MS` (default 60s), `DISCORD_POLL_CHANNEL_ID` (unit poll channel; falls back to the ops channel), `DISCORD_POLL_POLL_MS` (default 60s). Logs through `payload.logger`.
|
||||
|
||||
## Structure
|
||||
|
||||
|
|
@ -36,6 +36,7 @@ bot/
|
|||
services/
|
||||
index.ts # Service registry
|
||||
missionEmbeds.ts # Attendance embed lifecycle + reconcile loop (poll tick)
|
||||
pollEmbeds.ts # Unit poll embed + buttons + reconcile loop + LISTEN ptf_poll_changed
|
||||
notificationBridge.ts # Poll user-notifications → Discord DMs
|
||||
evaluationReminders.ts # Post-mission evaluation reminder DMs (one-shot marker on Missions)
|
||||
imminentReminders.ts # Pre-op reminder: thread on the roll-call message + attendee pings (one-shot marker on Missions)
|
||||
|
|
@ -85,6 +86,18 @@ Actions live in `bot/lib/debugActions.ts`. Each `build` receives the client and
|
|||
|
||||
Bot posts RSVP embeds (Yes/Tentative/No) for future, Scheduled, visibility:"unit" missions into ops channel. Stores `discordMessageId` + `discordAttendanceHash` on mission. Reconciles hash changes every poll tick (web ↔ Discord two-way sync, loop-safe). The embed title links to the mission page, a mission summary sits under the title (truncated to 300 characters with an ellipsis), and an "Open the op" field carries the URL; `attendanceHash` includes an embed schema version so layout-only changes re-render live roll-calls once (idempotent). Web UI: `MissionAttendance` component. Weekly main missions are cloned by `bun run payload generate-mission` (a payload bin, see `src/scripts/AGENTS.md`). Staff can force one outside the lead-time window with `/rollcall [mission]` (ID, name, or code name; omit to target the next upcoming Scheduled unit op): `forceRollCall` in `missionEmbeds.ts` re-renders the live message or posts a fresh one (even after a manual deletion), bypassing only the 3-day gate; target lookup/validation lives in `src/lib/intelligence/rollCall.ts`.
|
||||
|
||||
## Feature flow: unit polls
|
||||
|
||||
An NPC `event` node with the `poll` effect raises a unit-wide poll: `launchDialoguePoll()` (`src/lib/polls/service.ts`) snapshots the node's authored config into a `polls` document keyed by `sourceKey` (`<dialogueId>:<nodeId>`), so the trigger is idempotent: a second player reaching the node joins the existing poll instead of opening a rival one, and later edits to the node never rewrite a poll people already voted in. The bot posts an embed with one button per option (`ptf-poll:<pollId>:<optionKey>`) into `DISCORD_POLL_CHANNEL_ID`, and both surfaces write through `castPollVote()`, the only vote path.
|
||||
|
||||
**Why buttons, not a native Discord poll**: native polls (message type 46) cannot weight votes, cannot be edited, and cannot be closed early. Buttons keep weighted tallies, the tie ladder and the two-way sync possible.
|
||||
|
||||
**Sync** mirrors the roll-call exactly: `discordPollHash` fingerprints everything the message shows (schema version, status, counts, winner, deadline, public voter names), the reconcile loop edits on drift and stamps the hash back, and a `LISTEN ptf_poll_changed` listener reacts to web-side votes in under a second. A deleted message is never reposted (one-shot rule); the web page stays the source of truth. `advancePoll()` runs inside the reconcile pass, so a poll closes and resolves even when nobody is looking at it.
|
||||
|
||||
**Buttons are deliberately neutral**: the message is shared, so highlighting one member's choice would show their ballot to the unit, and on an anonymous poll it would leak the thing the poll hides. The voter's own ballot comes back ephemerally.
|
||||
|
||||
**Ties**: `tallyPoll` weights votes by the highest matching role tier, then `resolvePollTally` gives a tie to the conversation initiator when exactly one tied option is on their ballot. Otherwise the poll parks in `pending_decision` with the tally frozen, the buttons disable, and a superuser settles it on `/polls/[id]`; `resolveDeadlineTie` picks a random tied option once `tieGraceHours` passes. Only a resolved poll writes its `resultFlag`.
|
||||
|
||||
## Feature flow: notifications
|
||||
|
||||
`notificationBridge` polls `user-notifications` (cursor = last seen id; cap 5 DMs/tick). DMs opted-in users (`preferences.discord.enabled`, not in `mutedTypes`). Remaining polish: the web preferences UI does not yet expose the `preferences.discord` toggles — they exist on the Users collection and are read by the bridge, but are currently only settable in the Payload admin panel.
|
||||
|
|
|
|||
|
|
@ -10,6 +10,8 @@ export interface BotConfig {
|
|||
changelogChannelId: string | null;
|
||||
announceMentionRoleId: string | null;
|
||||
npcEventChannelId: string | null;
|
||||
/** Channel unit polls are posted in. Falls back to the ops channel. */
|
||||
pollChannelId: string | null;
|
||||
debugChannelId: string | null;
|
||||
attendancePollMs: number;
|
||||
notificationPollMs: number;
|
||||
|
|
@ -20,6 +22,7 @@ export interface BotConfig {
|
|||
achievementPollMs: number;
|
||||
presencePollMs: number;
|
||||
npcEventPollMs: number;
|
||||
pollPollMs: number;
|
||||
/** Hours before a scheduled operation the modlist buffer reminder fires. */
|
||||
modlistBufferHours: number;
|
||||
}
|
||||
|
|
@ -77,6 +80,7 @@ export const botConfig: BotConfig = {
|
|||
changelogChannelId: optional("DISCORD_CHANGELOG_CHANNEL_ID"),
|
||||
announceMentionRoleId: optional("DISCORD_ANNOUNCE_MENTION_ROLE_ID"),
|
||||
npcEventChannelId: optional("DISCORD_NPC_EVENT_CHANNEL_ID"),
|
||||
pollChannelId: optional("DISCORD_POLL_CHANNEL_ID"),
|
||||
debugChannelId: optional("DISCORD_DEBUG_CHANNEL_ID"),
|
||||
attendancePollMs: pollMs("DISCORD_ATTENDANCE_POLL_MS", 60_000),
|
||||
notificationPollMs: pollMs("DISCORD_NOTIFICATION_POLL_MS", 20_000),
|
||||
|
|
@ -87,5 +91,6 @@ export const botConfig: BotConfig = {
|
|||
achievementPollMs: pollMs("DISCORD_ACHIEVEMENT_POLL_MS", 60_000),
|
||||
presencePollMs: pollMs("DISCORD_PRESENCE_POLL_MS", 30_000),
|
||||
npcEventPollMs: pollMs("DISCORD_NPC_EVENT_POLL_MS", 60_000),
|
||||
pollPollMs: pollMs("DISCORD_POLL_POLL_MS", 60_000),
|
||||
modlistBufferHours: parseHours("DISCORD_MODLIST_BUFFER_HOURS", 8),
|
||||
};
|
||||
|
|
|
|||
|
|
@ -9,6 +9,8 @@ import {
|
|||
renderAttendanceEmbed,
|
||||
} from "@/bot/services/missionEmbeds";
|
||||
import { botConfig } from "@/bot/config";
|
||||
import { refreshPollMessage } from "@/bot/services/pollEmbeds";
|
||||
import { castPollVote, loadPollVoteRows, isPollVotingClosed } from "@/lib/polls/service";
|
||||
import {
|
||||
attendanceClosedMessage,
|
||||
type AttendanceResponse,
|
||||
|
|
@ -53,6 +55,96 @@ export const handleButtonInteraction = async (
|
|||
return;
|
||||
}
|
||||
|
||||
// Unit poll buttons. Acknowledge first: resolving the Discord member to a
|
||||
// Payload user is a database call, and the interaction token dies at 3s.
|
||||
if (parts.length === 3 && parts[0] === "ptf-poll") {
|
||||
const pollId = Number(parts[1]);
|
||||
const optionKey = parts[2];
|
||||
if (!Number.isInteger(pollId) || !optionKey) return;
|
||||
|
||||
try {
|
||||
await interaction.deferReply({ flags: MessageFlags.Ephemeral });
|
||||
} catch (error) {
|
||||
payload.logger.error(`[Bot] Poll interaction could not be acknowledged: ${errorMessage(error)}`);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const user = await findUserByDiscordId(payload, interaction.user.id);
|
||||
if (!user) {
|
||||
await interaction.editReply("Run /signup or /link first.");
|
||||
return;
|
||||
}
|
||||
|
||||
const poll = await payload
|
||||
.findByID({ collection: "polls", id: pollId, depth: 0, overrideAccess: true })
|
||||
.catch(() => null);
|
||||
if (!poll) {
|
||||
await interaction.editReply("That poll no longer exists.");
|
||||
return;
|
||||
}
|
||||
if (isPollVotingClosed(poll)) {
|
||||
await interaction.editReply("This poll has closed.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Toggle: pressing your current answer on a single-answer poll retracts it.
|
||||
const rows = await loadPollVoteRows(payload, poll.id);
|
||||
const current = rows.find((row) => row.userId === user.id)?.answers ?? [];
|
||||
const alreadyChosen = current.includes(optionKey);
|
||||
const answers = poll.multiSelect
|
||||
? alreadyChosen
|
||||
? current.filter((key) => key !== optionKey)
|
||||
: [...current, optionKey]
|
||||
: alreadyChosen
|
||||
? []
|
||||
: [optionKey];
|
||||
|
||||
const result = await castPollVote(payload, {
|
||||
pollId: poll.id,
|
||||
userId: user.id,
|
||||
answers,
|
||||
});
|
||||
|
||||
if (!result.ok) {
|
||||
const message =
|
||||
result.reason === "closed"
|
||||
? "This poll has closed."
|
||||
: result.reason === "ineligible"
|
||||
? "You are not eligible to vote in this poll."
|
||||
: result.reason === "too-many"
|
||||
? "This poll takes one answer."
|
||||
: "That vote could not be recorded.";
|
||||
await interaction.editReply(message);
|
||||
return;
|
||||
}
|
||||
|
||||
await refreshPollMessage(payload, result.poll, interaction.message);
|
||||
|
||||
const labelFor = (key: string) => {
|
||||
const option = result.poll.options.find((o) => o.key === key);
|
||||
return option ? `${option.emoji ? `${option.emoji} ` : ""}${option.label}` : key;
|
||||
};
|
||||
await interaction.editReply(
|
||||
answers.length === 0
|
||||
? "Your vote was withdrawn."
|
||||
: `Voted: ${answers.map(labelFor).join(", ")}. Press it again to withdraw.`,
|
||||
);
|
||||
} catch (error) {
|
||||
payload.logger.error(
|
||||
`[Bot] Poll interaction failed for poll #${pollId}: ${errorMessage(error)}`,
|
||||
);
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await safeEphemeralReply(
|
||||
interaction,
|
||||
payload,
|
||||
"Something went wrong while recording your vote.",
|
||||
);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Attendance roll-call buttons.
|
||||
if (parts.length !== 3 || parts[0] !== "ptf-att") {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import { start as startImminentReminders } from "./imminentReminders";
|
|||
import { start as startFridayOpsNotice } from "./fridayOpsNotice";
|
||||
import { start as startAchievementAnnouncements } from "./achievementAnnouncements";
|
||||
import { start as startNpcEventAnnouncements } from "./npcEventAnnouncements";
|
||||
import { start as startPolls } from "./pollEmbeds";
|
||||
import { start as startDiscordPresence } from "./discordPresence";
|
||||
|
||||
export type ServiceStarter = (client: Client, payload: Payload) => Promise<void> | void;
|
||||
|
|
@ -23,5 +24,6 @@ export const services: ServiceStarter[] = [
|
|||
startFridayOpsNotice,
|
||||
startAchievementAnnouncements,
|
||||
startNpcEventAnnouncements,
|
||||
startPolls,
|
||||
startDiscordPresence,
|
||||
];
|
||||
|
|
|
|||
411
src/bot/services/pollEmbeds.ts
Normal file
411
src/bot/services/pollEmbeds.ts
Normal file
|
|
@ -0,0 +1,411 @@
|
|||
import {
|
||||
ActionRowBuilder,
|
||||
ButtonBuilder,
|
||||
ButtonStyle,
|
||||
EmbedBuilder,
|
||||
type Client,
|
||||
type Message,
|
||||
type TextBasedChannelFields,
|
||||
} from "discord.js";
|
||||
import type { Payload } from "payload";
|
||||
import type { Poll, User } from "@/payload-types";
|
||||
import { botConfig } from "@/bot/config";
|
||||
import { getOpsChannel } from "@/bot/services/missionEmbeds";
|
||||
import { POLL_CHANGED_CHANNEL } from "@/lib/polls/realtime";
|
||||
import {
|
||||
advancePoll,
|
||||
isPollVotingClosed,
|
||||
loadPollVoteRows,
|
||||
readPollOutcome,
|
||||
tallyPollNow,
|
||||
} from "@/lib/polls/service";
|
||||
import type { PollTally } from "@/lib/polls/tally";
|
||||
|
||||
/**
|
||||
* Discord mirror of a unit poll.
|
||||
*
|
||||
* Native Discord polls cannot weight votes, cannot be edited, and cannot be
|
||||
* closed early, so the poll is an embed with one button per option. The
|
||||
* reconcile loop renders, edits and finalises it; the buttons write through
|
||||
* the same `castPollVote` the web page uses.
|
||||
*/
|
||||
|
||||
const POLL_EMBED_SCHEMA_VERSION = 1;
|
||||
const POLL_EMBED_COLOR = 0x6366f1;
|
||||
const POLL_CLOSED_COLOR = 0x71717a;
|
||||
const POLL_TIED_COLOR = 0xf59e0b;
|
||||
|
||||
const errorMessage = (error: unknown): string =>
|
||||
error instanceof Error ? error.message : "Unknown error";
|
||||
|
||||
const memberName = (user: User): string => user.displayName ?? user.username;
|
||||
|
||||
/** Bars are drawn from the weighted share, in ten steps. */
|
||||
const bar = (value: number, max: number): string => {
|
||||
if (max <= 0 || value <= 0) return "";
|
||||
const filled = Math.max(1, Math.round((value / max) * 10));
|
||||
return "█".repeat(filled);
|
||||
};
|
||||
|
||||
export interface PollRenderInput {
|
||||
poll: Poll;
|
||||
tally: PollTally;
|
||||
/** Voter names, only populated for public polls. */
|
||||
votersByOption: Map<string, string[]>;
|
||||
now?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fingerprint of everything the message shows. Drift triggers an edit; the
|
||||
* edit stamps the hash back so the loop settles. The schema version forces one
|
||||
* re-render when the layout changes.
|
||||
*/
|
||||
export const pollHash = (input: PollRenderInput): string => {
|
||||
const { poll, tally, votersByOption } = input;
|
||||
return JSON.stringify({
|
||||
v: POLL_EMBED_SCHEMA_VERSION,
|
||||
status: poll.status,
|
||||
closesAt: poll.closesAt,
|
||||
multiSelect: poll.multiSelect === true,
|
||||
anonymity: poll.anonymity,
|
||||
counts: poll.options.map((option) => [
|
||||
option.key,
|
||||
tally.counts[option.key]?.raw ?? 0,
|
||||
tally.counts[option.key]?.weighted ?? 0,
|
||||
]),
|
||||
winner: poll.winnerKey ?? null,
|
||||
method: poll.resolutionMethod ?? null,
|
||||
deadline: poll.decisionDeadline ?? null,
|
||||
voters: poll.options.map((option) => [option.key, votersByOption.get(option.key) ?? []]),
|
||||
});
|
||||
};
|
||||
|
||||
const optionLabel = (option: Poll["options"][number]): string =>
|
||||
`${option.emoji ? `${option.emoji} ` : ""}${option.label}`;
|
||||
|
||||
export const renderPollEmbed = (input: PollRenderInput): EmbedBuilder => {
|
||||
const { poll, tally, votersByOption } = input;
|
||||
const now = input.now ?? Date.now();
|
||||
const closesUnix = Math.floor(new Date(poll.closesAt).getTime() / 1000);
|
||||
const pollUrl = `${botConfig.appUrl}/polls/${poll.id}`;
|
||||
const closed = isPollVotingClosed(poll, now);
|
||||
const pending = poll.status === "pending_decision";
|
||||
const maxWeighted = Math.max(0, ...poll.options.map((o) => tally.counts[o.key]?.weighted ?? 0));
|
||||
|
||||
const fields = poll.options.map((option) => {
|
||||
const counts = tally.counts[option.key] ?? { raw: 0, weighted: 0 };
|
||||
const weightedText =
|
||||
counts.weighted === counts.raw
|
||||
? `${counts.raw}`
|
||||
: `${counts.raw} (weight ${counts.weighted % 1 === 0 ? counts.weighted : counts.weighted.toFixed(2)})`;
|
||||
const barText = bar(counts.weighted, maxWeighted);
|
||||
const names = votersByOption.get(option.key) ?? [];
|
||||
const voterText =
|
||||
poll.anonymity === "public" && names.length > 0
|
||||
? `\n${names.join(", ").slice(0, 900)}`
|
||||
: "";
|
||||
return {
|
||||
name: `${optionLabel(option)}: ${weightedText}`,
|
||||
value: `${barText || "-"}${voterText}`.slice(0, 1024),
|
||||
inline: false,
|
||||
};
|
||||
});
|
||||
|
||||
const statusLine = pending
|
||||
? "**Tied.** Awaiting a superuser decision."
|
||||
: closed
|
||||
? poll.winnerKey
|
||||
? `**Closed.** Winner: ${
|
||||
optionLabel(
|
||||
poll.options.find((o) => o.key === poll.winnerKey) ?? {
|
||||
key: "",
|
||||
label: poll.winnerKey,
|
||||
},
|
||||
) || poll.winnerKey
|
||||
}`
|
||||
: "**Closed.** No decision."
|
||||
: `**Closes:** <t:${closesUnix}:F> (<t:${closesUnix}:R>)`;
|
||||
|
||||
const settings = [
|
||||
poll.multiSelect ? "Multiple answers" : "One answer",
|
||||
poll.anonymity === "anonymous" ? "Anonymous (counts only)" : "Public",
|
||||
`Weighted votes: ${tally.totalWeight % 1 === 0 ? tally.totalWeight : tally.totalWeight.toFixed(2)}`,
|
||||
`${tally.totalVotes} voter${tally.totalVotes === 1 ? "" : "s"}`,
|
||||
].join(" · ");
|
||||
|
||||
const deadlineUnix = poll.decisionDeadline
|
||||
? Math.floor(new Date(poll.decisionDeadline).getTime() / 1000)
|
||||
: null;
|
||||
|
||||
return new EmbedBuilder()
|
||||
.setTitle(poll.title)
|
||||
.setURL(pollUrl)
|
||||
.setDescription(
|
||||
[
|
||||
...(poll.body?.trim() ? [poll.body.trim(), ""] : []),
|
||||
statusLine,
|
||||
pending && deadlineUnix
|
||||
? `A random tied option is chosen <t:${deadlineUnix}:R> if no superuser decides.`
|
||||
: null,
|
||||
settings,
|
||||
]
|
||||
.filter((line): line is string => line !== null)
|
||||
.join("\n"),
|
||||
)
|
||||
.setColor(pending ? POLL_TIED_COLOR : closed ? POLL_CLOSED_COLOR : POLL_EMBED_COLOR)
|
||||
.addFields(fields)
|
||||
.setFooter({ text: `Vote here or on the web · ${pollUrl}` });
|
||||
};
|
||||
|
||||
/**
|
||||
* One row per five options. Every button is neutral: the message is shared, so
|
||||
* a highlight would show one member's ballot to the whole unit, and on an
|
||||
* anonymous poll it would leak the very thing the poll hides. The voter gets
|
||||
* their own confirmation ephemerally instead. Once voting is over every button
|
||||
* is disabled so the message becomes a stable record.
|
||||
*/
|
||||
export const buildPollRows = (poll: Poll): ActionRowBuilder<ButtonBuilder>[] => {
|
||||
const closed = isPollVotingClosed(poll);
|
||||
const rows: ActionRowBuilder<ButtonBuilder>[] = [];
|
||||
|
||||
for (let index = 0; index < poll.options.length; index += 5) {
|
||||
const chunk = poll.options.slice(index, index + 5);
|
||||
const row = new ActionRowBuilder<ButtonBuilder>();
|
||||
for (const option of chunk) {
|
||||
const button = new ButtonBuilder()
|
||||
.setCustomId(`ptf-poll:${poll.id}:${option.key}`)
|
||||
.setStyle(ButtonStyle.Secondary)
|
||||
.setLabel(
|
||||
`${option.emoji ? `${option.emoji} ` : ""}${option.label}`.slice(0, 80),
|
||||
)
|
||||
.setDisabled(closed);
|
||||
row.addComponents(button);
|
||||
}
|
||||
rows.push(row);
|
||||
}
|
||||
return rows;
|
||||
};
|
||||
|
||||
/** Voter names per option, for public polls only. Anonymous polls never name voters here. */
|
||||
const loadVoterNames = async (
|
||||
payload: Payload,
|
||||
poll: Poll,
|
||||
): Promise<Map<string, string[]>> => {
|
||||
const byOption = new Map<string, string[]>();
|
||||
if (poll.anonymity !== "public") return byOption;
|
||||
|
||||
const rows = await loadPollVoteRows(payload, poll.id);
|
||||
if (rows.length === 0) return byOption;
|
||||
|
||||
const userIds = [...new Set(rows.map((row) => row.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 as unknown as User)]),
|
||||
);
|
||||
|
||||
for (const row of rows) {
|
||||
const name = nameById.get(row.userId) ?? `user ${row.userId}`;
|
||||
for (const key of row.answers) {
|
||||
const list = byOption.get(key) ?? [];
|
||||
list.push(name);
|
||||
byOption.set(key, list);
|
||||
}
|
||||
}
|
||||
for (const [key, names] of byOption) {
|
||||
byOption.set(key, [...names].sort((a, b) => a.localeCompare(b)));
|
||||
}
|
||||
return byOption;
|
||||
};
|
||||
|
||||
/** Everything the renderer needs, fetched once per reconcile pass. */
|
||||
export const loadPollRender = async (
|
||||
payload: Payload,
|
||||
poll: Poll,
|
||||
): Promise<PollRenderInput> => {
|
||||
const { tally } = await tallyPollNow(payload, poll);
|
||||
return { poll, tally, votersByOption: await loadVoterNames(payload, poll) };
|
||||
};
|
||||
|
||||
const pollChannelId = (): string | null => botConfig.pollChannelId ?? botConfig.opsChannelId;
|
||||
|
||||
const getPollChannel = async (client: Client): Promise<TextBasedChannelFields | null> => {
|
||||
const channelId = pollChannelId();
|
||||
if (!channelId) return null;
|
||||
return getOpsChannel(client, channelId);
|
||||
};
|
||||
|
||||
/**
|
||||
* Render, post or edit one poll, then stamp the hash. A deleted message is not
|
||||
* reposted (one-shot, same rule as the roll-call): the web page remains the
|
||||
* source of truth.
|
||||
*/
|
||||
export const reconcilePoll = async (
|
||||
client: Client,
|
||||
payload: Payload,
|
||||
pollId: number,
|
||||
): Promise<void> => {
|
||||
const channel = await getPollChannel(client);
|
||||
if (!channel) return;
|
||||
|
||||
// Close or resolve first, so the message never shows a poll that should have
|
||||
// ended. advancePoll is idempotent and cheap when nothing is due.
|
||||
const poll = await advancePoll(payload, { pollId });
|
||||
if (poll.status === "closed" && !poll.discordMessageId) return;
|
||||
|
||||
const render = await loadPollRender(payload, poll);
|
||||
const hash = pollHash(render);
|
||||
|
||||
if (!poll.discordMessageId) {
|
||||
const message = await channel.send({
|
||||
embeds: [renderPollEmbed(render)],
|
||||
components: buildPollRows(poll),
|
||||
});
|
||||
await payload.update({
|
||||
collection: "polls",
|
||||
id: poll.id,
|
||||
data: {
|
||||
discordMessageId: message.id,
|
||||
discordChannelId: message.channelId ?? pollChannelId(),
|
||||
discordPostedAt: new Date().toISOString(),
|
||||
discordPollHash: hash,
|
||||
},
|
||||
overrideAccess: true,
|
||||
});
|
||||
payload.logger.info(`[Bot] Posted poll #${poll.id} (${poll.title}).`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (poll.discordPollHash === hash) return;
|
||||
|
||||
const message = await channel.messages.fetch(poll.discordMessageId).catch(() => null);
|
||||
if (!message) {
|
||||
payload.logger.warn(
|
||||
`[Bot] Poll #${poll.id} message ${poll.discordMessageId} is gone; leaving it unposted.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
await message.edit({
|
||||
embeds: [renderPollEmbed(render)],
|
||||
components: buildPollRows(poll),
|
||||
});
|
||||
await payload.update({
|
||||
collection: "polls",
|
||||
id: poll.id,
|
||||
data: { discordPollHash: hash },
|
||||
overrideAccess: true,
|
||||
});
|
||||
};
|
||||
|
||||
/** Edit a poll message after an in-Discord vote, so the tally moves immediately. */
|
||||
export const refreshPollMessage = async (
|
||||
payload: Payload,
|
||||
poll: Poll,
|
||||
message: Message,
|
||||
): Promise<void> => {
|
||||
const render = await loadPollRender(payload, poll);
|
||||
await message.edit({
|
||||
embeds: [renderPollEmbed(render)],
|
||||
components: buildPollRows(poll),
|
||||
});
|
||||
await payload.update({
|
||||
collection: "polls",
|
||||
id: poll.id,
|
||||
data: { discordPollHash: pollHash(render) },
|
||||
overrideAccess: true,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Which polls need a render pass: anything still live, anything posted, and
|
||||
* anything resolved in the last two weeks (so a closed poll's final message is
|
||||
* written once). Older history is left alone.
|
||||
*/
|
||||
const getReconcilablePolls = async (payload: Payload): Promise<Poll[]> => {
|
||||
const cutoff = new Date(Date.now() - 14 * 24 * 3_600_000).toISOString();
|
||||
const res = await payload.find({
|
||||
collection: "polls",
|
||||
where: {
|
||||
or: [
|
||||
{ status: { in: ["open", "pending_decision"] } },
|
||||
{ discordMessageId: { exists: true }, updatedAt: { greater_than: cutoff } },
|
||||
],
|
||||
},
|
||||
limit: 50,
|
||||
depth: 0,
|
||||
sort: "-updatedAt",
|
||||
overrideAccess: true,
|
||||
});
|
||||
return res.docs;
|
||||
};
|
||||
|
||||
let reconcileRunning = false;
|
||||
|
||||
export const reconcile = async (client: Client, payload: Payload): Promise<void> => {
|
||||
if (reconcileRunning) return;
|
||||
reconcileRunning = true;
|
||||
try {
|
||||
if (!pollChannelId()) return;
|
||||
const polls = await getReconcilablePolls(payload);
|
||||
for (const poll of polls) {
|
||||
try {
|
||||
await reconcilePoll(client, payload, poll.id);
|
||||
} catch (error) {
|
||||
payload.logger.error(
|
||||
`[Bot] Poll reconcile failed for poll #${poll.id}: ${errorMessage(error)}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
payload.logger.error(`[Bot] Poll reconcile failed: ${errorMessage(error)}`);
|
||||
} finally {
|
||||
reconcileRunning = false;
|
||||
}
|
||||
};
|
||||
|
||||
const startPollListener = async (client: Client, payload: Payload): Promise<void> => {
|
||||
if (!pollChannelId()) return;
|
||||
|
||||
const listener = await payload.db.pool.connect();
|
||||
listener.on("notification", (notification) => {
|
||||
if (notification.channel !== POLL_CHANGED_CHANNEL || !notification.payload) return;
|
||||
|
||||
let pollId: unknown;
|
||||
try {
|
||||
pollId = JSON.parse(notification.payload).pollId;
|
||||
} catch {
|
||||
payload.logger.warn("[Bot] Ignoring malformed poll change notification.");
|
||||
return;
|
||||
}
|
||||
if (typeof pollId !== "number" || !Number.isInteger(pollId)) return;
|
||||
|
||||
void reconcilePoll(client, payload, pollId).catch((error) => {
|
||||
payload.logger.error(
|
||||
`[Bot] Poll change reconcile failed for poll #${pollId}: ${errorMessage(error)}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
listener.on("error", (error) => {
|
||||
payload.logger.error(`[Bot] Poll listener failed: ${errorMessage(error)}`);
|
||||
});
|
||||
await listener.query(`LISTEN ${POLL_CHANGED_CHANNEL}`);
|
||||
payload.logger.info("[Bot] Poll realtime listener started");
|
||||
};
|
||||
|
||||
export const start = (client: Client, payload: Payload): void => {
|
||||
payload.logger.info("[Bot] Poll service started");
|
||||
void startPollListener(client, payload).catch((error) => {
|
||||
payload.logger.error(`[Bot] Poll realtime listener failed to start: ${errorMessage(error)}`);
|
||||
});
|
||||
void reconcile(client, payload);
|
||||
setInterval(() => {
|
||||
void reconcile(client, payload);
|
||||
}, botConfig.pollPollMs);
|
||||
};
|
||||
|
|
@ -55,6 +55,7 @@ const TARGET_COLLECTIONS = [
|
|||
{ label: "Leadership Transfers", value: "leadership-transfers" },
|
||||
{ label: "Player Flags", value: "player-flags" },
|
||||
{ label: "Reinforcement Pools", value: "reinforcement-pools" },
|
||||
{ label: "Polls", value: "polls" },
|
||||
] as const;
|
||||
|
||||
export const GameEventLogs: CollectionConfig = {
|
||||
|
|
|
|||
|
|
@ -95,6 +95,21 @@ export const NpcDialogueSettings: GlobalConfig = {
|
|||
"The default for everyone. Players can override it in their account preferences, and a player whose device asks for reduced motion never sees the animation.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "pacing",
|
||||
label: "Typing pace",
|
||||
type: "select",
|
||||
defaultValue: "natural",
|
||||
options: [
|
||||
{ label: "Subtle (quick, about 45 characters a second)", value: "subtle" },
|
||||
{ label: "Natural (about 33 a second)", value: "natural" },
|
||||
{ label: "Pronounced (slow and deliberate, about 24 a second)", value: "pronounced" },
|
||||
],
|
||||
admin: {
|
||||
description:
|
||||
"How fast conversation lines type out and how long the pauses at punctuation last. Applies to the next conversation opened, with no deploy. Authors can still hold a specific line with {1.2s} or {400ms}.",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
|
|
|||
73
src/collections/polls/PollVotes.ts
Normal file
73
src/collections/polls/PollVotes.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
import { requirePermission } from "@/utils/access-control/hasPermission";
|
||||
|
||||
/**
|
||||
* One ballot per voter per poll (unique poll+user). Votes are updatable until
|
||||
* the poll closes; the poll service rewrites the row in place, so a voter can
|
||||
* change or retract their answer.
|
||||
*
|
||||
* Weight is deliberately NOT stored: it is resolved from the voter's roles when
|
||||
* the poll closes, then frozen into `polls.outcome`. That keeps one source of
|
||||
* truth for "who counts double" and makes the tie set a superuser is asked
|
||||
* about stable while the decision is pending.
|
||||
*
|
||||
* Read access is the anonymity guarantee: only the superuser tier can read
|
||||
* vote rows. Everyone else sees counts, which the service computes with
|
||||
* `overrideAccess`. Writes are service-only, the same posture as
|
||||
* `tech-ballot-votes`.
|
||||
*/
|
||||
export const PollVotes: CollectionConfig = {
|
||||
slug: "poll-votes",
|
||||
admin: {
|
||||
group: "Polls",
|
||||
defaultColumns: ["poll", "user", "updatedAt"],
|
||||
description:
|
||||
"Ballots. Readable only by the superuser tier, which is what keeps anonymous polls anonymous for everyone else.",
|
||||
},
|
||||
access: {
|
||||
read: requirePermission("system:admin-access"),
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
delete: () => false,
|
||||
},
|
||||
indexes: [
|
||||
{
|
||||
fields: ["poll", "user"],
|
||||
unique: true,
|
||||
},
|
||||
],
|
||||
fields: [
|
||||
{
|
||||
name: "poll",
|
||||
type: "relationship",
|
||||
relationTo: "polls",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "user",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
required: true,
|
||||
index: true,
|
||||
},
|
||||
{
|
||||
name: "answers",
|
||||
type: "array",
|
||||
required: true,
|
||||
minRows: 1,
|
||||
maxRows: 10,
|
||||
admin: {
|
||||
description:
|
||||
"The option keys this voter chose. One row on a single-answer poll; the service dedupes and rejects keys the poll does not carry.",
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "key",
|
||||
type: "text",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
319
src/collections/polls/Polls.ts
Normal file
319
src/collections/polls/Polls.ts
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
import type { CollectionConfig } from "payload";
|
||||
|
||||
/**
|
||||
* A unit-wide poll raised by an NPC conversation.
|
||||
*
|
||||
* Writes are closed at the collection level: the dialogue effect creates one,
|
||||
* and every later change (vote, close, tie decision) goes through the poll
|
||||
* service with `overrideAccess`. The admin panel is a read-only history, which
|
||||
* is the same posture as `tech-ballots`.
|
||||
*
|
||||
* `sourceKey` (`<dialogueId>:<nodeId>`) makes the trigger idempotent: a second
|
||||
* player reaching the same node joins the existing poll instead of opening a
|
||||
* new one. The option list and settings are copied out of the dialogue node at
|
||||
* launch, so editing the node afterwards cannot rewrite a poll people have
|
||||
* already voted in.
|
||||
*/
|
||||
export const Polls: CollectionConfig = {
|
||||
slug: "polls",
|
||||
admin: {
|
||||
group: "Polls",
|
||||
useAsTitle: "title",
|
||||
defaultColumns: ["title", "status", "closesAt", "winnerKey"],
|
||||
description:
|
||||
"Unit-wide polls raised by NPC conversations. Read-only here: they are created by the dialogue effect and resolved by the poll service.",
|
||||
},
|
||||
access: {
|
||||
read: ({ req }) => Boolean(req.user),
|
||||
create: () => false,
|
||||
update: () => false,
|
||||
delete: () => false,
|
||||
},
|
||||
indexes: [
|
||||
{ fields: ["sourceKey"], unique: true },
|
||||
{ fields: ["status"] },
|
||||
],
|
||||
hooks: {
|
||||
beforeValidate: [
|
||||
({ data }) => {
|
||||
const options = (data?.options ?? []) as { key?: unknown }[];
|
||||
const seen = new Set<string>();
|
||||
for (const option of options) {
|
||||
const key = typeof option.key === "string" ? option.key.trim() : "";
|
||||
if (!key) throw new Error("Every poll option needs a key.");
|
||||
if (seen.has(key)) throw new Error(`Duplicate poll option key "${key}".`);
|
||||
seen.add(key);
|
||||
}
|
||||
|
||||
const tiers = (data?.weightTiers ?? []) as { multiplier?: unknown }[];
|
||||
for (const tier of tiers) {
|
||||
const multiplier = tier.multiplier;
|
||||
if (typeof multiplier !== "number" || !Number.isFinite(multiplier) || multiplier <= 0) {
|
||||
throw new Error("Every voting weight tier needs a positive multiplier.");
|
||||
}
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
],
|
||||
},
|
||||
fields: [
|
||||
{
|
||||
name: "title",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: { description: "The question, as it appears on both surfaces." },
|
||||
},
|
||||
{
|
||||
name: "body",
|
||||
type: "textarea",
|
||||
admin: {
|
||||
description:
|
||||
"Optional context under the question. Plain text with **bold** and line breaks; both surfaces render it the same way.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "options",
|
||||
type: "array",
|
||||
required: true,
|
||||
minRows: 2,
|
||||
maxRows: 10,
|
||||
admin: { description: "The answers on offer. Keys are stable and never shown." },
|
||||
fields: [
|
||||
{
|
||||
name: "key",
|
||||
type: "text",
|
||||
required: true,
|
||||
admin: { description: "Stable slug, e.g. 'accept'. Votes reference this, never the row." },
|
||||
},
|
||||
{ name: "label", type: "text", required: true },
|
||||
{
|
||||
name: "emoji",
|
||||
type: "text",
|
||||
admin: { description: "Optional emoji shown before the label on both surfaces." },
|
||||
},
|
||||
{ name: "description", type: "text" },
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "status",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "open",
|
||||
options: [
|
||||
{ label: "Open", value: "open" },
|
||||
{ label: "Tied (awaiting a superuser)", value: "pending_decision" },
|
||||
{ label: "Closed", value: "closed" },
|
||||
],
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "closesAt",
|
||||
type: "date",
|
||||
required: true,
|
||||
admin: {
|
||||
date: { pickerAppearance: "dayAndTime" },
|
||||
description: "When voting stops. Voting is also refused past this moment by the service.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multiSelect",
|
||||
type: "checkbox",
|
||||
defaultValue: false,
|
||||
admin: { description: "Allow more than one answer per voter." },
|
||||
},
|
||||
{
|
||||
name: "anonymity",
|
||||
type: "select",
|
||||
required: true,
|
||||
defaultValue: "public",
|
||||
options: [
|
||||
{ label: "Public (everyone sees who voted)", value: "public" },
|
||||
{ label: "Anonymous (counts for members, names for superusers)", value: "anonymous" },
|
||||
],
|
||||
admin: {
|
||||
description:
|
||||
"Anonymous hides voter identities from everyone except superusers. Counts are always visible.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "eligibleRoles",
|
||||
type: "relationship",
|
||||
relationTo: "roles",
|
||||
hasMany: true,
|
||||
admin: {
|
||||
description:
|
||||
"Leave empty for the whole unit. When set, only holders of these roles may vote.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "defaultWeight",
|
||||
type: "number",
|
||||
defaultValue: 1,
|
||||
min: 0.1,
|
||||
admin: {
|
||||
description:
|
||||
"Voting weight for everyone without a matching tier. Tiers pick the HIGHEST matching multiplier, never a sum.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "weightTiers",
|
||||
type: "array",
|
||||
label: "Voting weight tiers",
|
||||
admin: {
|
||||
description:
|
||||
"Optional role-based weight, e.g. Logistics 1.5. Resolved at close, from the roles each voter holds then.",
|
||||
},
|
||||
fields: [
|
||||
{ name: "label", type: "text", required: true },
|
||||
{
|
||||
name: "roles",
|
||||
type: "relationship",
|
||||
relationTo: "roles",
|
||||
hasMany: true,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: "multiplier",
|
||||
type: "number",
|
||||
required: true,
|
||||
min: 0.1,
|
||||
admin: { description: "1.5 means this role's vote counts 50% more." },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "resultFlag",
|
||||
type: "text",
|
||||
admin: {
|
||||
description:
|
||||
"Optional global player-flag key written with the winning option's key when the poll resolves. Must already exist in Player Flags.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "tieGraceHours",
|
||||
type: "number",
|
||||
defaultValue: 24,
|
||||
min: 1,
|
||||
admin: {
|
||||
description:
|
||||
"How long a superuser has to break a tie before a random tied option is chosen.",
|
||||
},
|
||||
},
|
||||
|
||||
// Provenance. Written once, at launch.
|
||||
{
|
||||
name: "sourceKey",
|
||||
type: "text",
|
||||
required: true,
|
||||
unique: true,
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "`<dialogueId>:<nodeId>`. Makes the dialogue trigger idempotent.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "dialogue",
|
||||
type: "relationship",
|
||||
relationTo: "npc-dialogues",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "nodeId",
|
||||
type: "text",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "initiatedBy",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"The player who reached the node first. Their vote is the first tie-breaker.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "openedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
|
||||
// Resolution.
|
||||
{
|
||||
name: "closedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true, description: "When voting stopped and the tally froze." },
|
||||
},
|
||||
{
|
||||
name: "decisionDeadline",
|
||||
type: "date",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "A tied poll: when a random tied option wins if no superuser decides.",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "decidedBy",
|
||||
type: "relationship",
|
||||
relationTo: "users",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "resolvedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "winnerKey",
|
||||
type: "text",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "resolutionMethod",
|
||||
type: "select",
|
||||
options: [
|
||||
{ label: "Most votes", value: "votes" },
|
||||
{ label: "Initiator's vote", value: "initiator" },
|
||||
{ label: "Superuser decision", value: "superuser" },
|
||||
{ label: "Random (deadline)", value: "random" },
|
||||
{ label: "No votes", value: "no_votes" },
|
||||
],
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "outcome",
|
||||
type: "json",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description:
|
||||
"The tally frozen at close: per-option raw and weighted counts, top options, and the resolution.",
|
||||
},
|
||||
},
|
||||
|
||||
// Discord sync, mirroring the mission roll-call lifecycle.
|
||||
{
|
||||
name: "discordMessageId",
|
||||
type: "text",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "discordChannelId",
|
||||
type: "text",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "discordPostedAt",
|
||||
type: "date",
|
||||
admin: { readOnly: true },
|
||||
},
|
||||
{
|
||||
name: "discordPollHash",
|
||||
type: "text",
|
||||
admin: {
|
||||
readOnly: true,
|
||||
description: "Content hash of the last message the bot rendered; drift triggers an edit.",
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { DialogueText } from "@/lib/npc-dialogue/DialogueText";
|
||||
|
||||
|
|
@ -18,6 +18,26 @@ const COLOR_CHOICES = [
|
|||
"slate",
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* How long the preview waits after the last keystroke.
|
||||
*
|
||||
* The preview is a full markup parse and render, and it used to run on every
|
||||
* character: typing a long line with colours, bold and a link meant re-parsing
|
||||
* the whole line per keypress, which is what made the box feel sticky. A fifth
|
||||
* of a second is below noticing for a preview and removes the work entirely while
|
||||
* someone is typing.
|
||||
*/
|
||||
const PREVIEW_DEBOUNCE_MS = 220;
|
||||
|
||||
/** The rendered preview, memoised so an unchanged line never re-parses. */
|
||||
const MarkupPreview = memo(function MarkupPreview({ text }: { text: string }) {
|
||||
return (
|
||||
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
|
||||
<DialogueText text={text} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Textarea for authored dialogue strings with a formatting toolbar, a
|
||||
* right-click markup menu, and a live `DialogueText` preview. Storage stays
|
||||
|
|
@ -48,6 +68,14 @@ export function MarkupEditor({
|
|||
const innerRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const el = () => textareaRef?.current ?? innerRef.current;
|
||||
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null);
|
||||
/** What the preview shows: the value as of the last pause in typing. */
|
||||
const [previewText, setPreviewText] = useState(value);
|
||||
|
||||
useEffect(() => {
|
||||
if (previewText === value) return;
|
||||
const timer = setTimeout(() => setPreviewText(value), PREVIEW_DEBOUNCE_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [value, previewText]);
|
||||
|
||||
// Close the context menu on any outside click or Escape.
|
||||
useEffect(() => {
|
||||
|
|
@ -171,12 +199,10 @@ export function MarkupEditor({
|
|||
"bg-zinc-800 border border-white/20 rounded px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
}
|
||||
/>
|
||||
{preview && value.trim() !== "" && (
|
||||
{preview && previewText.trim() !== "" && (
|
||||
<div className="flex flex-col gap-0.5">
|
||||
<span className="text-[9px] uppercase tracking-wider text-white/30">Preview</span>
|
||||
<div className="min-w-0 break-words rounded border border-white/10 bg-black/40 px-2 py-1.5 text-sm text-white/80">
|
||||
<DialogueText text={value} />
|
||||
</div>
|
||||
<MarkupPreview text={previewText} />
|
||||
</div>
|
||||
)}
|
||||
{menu && (
|
||||
|
|
|
|||
|
|
@ -27,6 +27,9 @@ import type {
|
|||
DialogueVoiceClip,
|
||||
NpcDialogueEffect,
|
||||
NpcDialogueNodeType,
|
||||
NpcDialoguePollConfig,
|
||||
NpcDialoguePollOption,
|
||||
NpcDialoguePollWeightTier,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import {
|
||||
conditionSummary,
|
||||
|
|
@ -63,8 +66,43 @@ const EFFECT_LABELS: Record<NpcDialogueEffect["type"], string> = {
|
|||
emit: "Log game event",
|
||||
reward: "Reward (unconfigured)",
|
||||
flag: "Set player flag",
|
||||
poll: "Open a unit poll",
|
||||
};
|
||||
|
||||
/** Compact checkbox list for role ids. Native inputs: the admin has no preflight. */
|
||||
function RoleChecklist({
|
||||
roles,
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
readonly roles: { id: number; name: string }[];
|
||||
readonly value: number[];
|
||||
readonly onChange: (next: number[]) => void;
|
||||
}) {
|
||||
if (roles.length === 0) {
|
||||
return <p className="text-[10px] text-white/40">No roles loaded.</p>;
|
||||
}
|
||||
return (
|
||||
<div className="flex max-h-32 flex-col gap-1 overflow-y-auto rounded border border-white/20 bg-zinc-800 p-1.5">
|
||||
{roles.map((role) => (
|
||||
<label key={role.id} className="flex items-center gap-2 text-xs text-white/70">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={value.includes(role.id)}
|
||||
onChange={(e) =>
|
||||
onChange(
|
||||
e.target.checked ? [...value, role.id] : value.filter((id) => id !== role.id),
|
||||
)
|
||||
}
|
||||
className="accent-emerald-500"
|
||||
/>
|
||||
{role.name}
|
||||
</label>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const FLAG_OP_LABELS: Record<DialogueFlagOp, string> = {
|
||||
set_true: "Set to true",
|
||||
set_false: "Set to false",
|
||||
|
|
@ -193,6 +231,30 @@ export function NodeEditDialog({
|
|||
};
|
||||
}, [open]);
|
||||
|
||||
// Roles for poll audience and voting-weight tiers. Same one-shot fetch.
|
||||
const [roles, setRoles] = useState<{ id: number; name: string }[]>([]);
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
if (!open) return;
|
||||
fetch("/api/roles?limit=200&depth=0")
|
||||
.then((res) => (res.ok ? res.json() : null))
|
||||
.then((data) => {
|
||||
if (!active) return;
|
||||
const list = Array.isArray(data?.docs) ? data.docs : [];
|
||||
setRoles(
|
||||
list
|
||||
.filter((r: { name?: unknown }) => Boolean(r?.name))
|
||||
.map((r: { id: number; name: string }) => ({ id: r.id, name: r.name })),
|
||||
);
|
||||
})
|
||||
.catch(() => {
|
||||
if (active) setRoles([]);
|
||||
});
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
useEffect(() => {
|
||||
setDraft(node?.data ?? null);
|
||||
}, [node?.id, open]);
|
||||
|
|
@ -224,6 +286,28 @@ export function NodeEditDialog({
|
|||
const patchEffect = (partial: Partial<NpcDialogueEffect>) =>
|
||||
patch({ effect: { type: "notify", ...draft.effect, ...partial } });
|
||||
|
||||
// Poll authoring helpers. The poll config lives under `effect.poll` so the
|
||||
// effect keeps its own flat fields (message, visibility, discord) untouched.
|
||||
const patchPoll = (partial: Partial<NpcDialoguePollConfig>) =>
|
||||
patchEffect({ poll: { ...draft.effect?.poll, ...partial } });
|
||||
const pollOptions = draft.effect?.poll?.options ?? [];
|
||||
const setPollOption = (index: number, partial: Partial<NpcDialoguePollOption>) =>
|
||||
patchPoll({
|
||||
options: pollOptions.map((option, i) => (i === index ? { ...option, ...partial } : option)),
|
||||
});
|
||||
const addPollOption = () => patchPoll({ options: [...pollOptions, { label: "" }] });
|
||||
const removePollOption = (index: number) =>
|
||||
patchPoll({ options: pollOptions.filter((_, i) => i !== index) });
|
||||
const pollTiers = draft.effect?.poll?.weightTiers ?? [];
|
||||
const setPollTier = (index: number, partial: Partial<NpcDialoguePollWeightTier>) =>
|
||||
patchPoll({
|
||||
weightTiers: pollTiers.map((tier, i) => (i === index ? { ...tier, ...partial } : tier)),
|
||||
});
|
||||
const addPollTier = () =>
|
||||
patchPoll({ weightTiers: [...pollTiers, { label: "", roleIds: [], multiplier: 1.5 }] });
|
||||
const removePollTier = (index: number) =>
|
||||
patchPoll({ weightTiers: pollTiers.filter((_, i) => i !== index) });
|
||||
|
||||
|
||||
|
||||
const setChoice = (index: number, next: DialogueNext) =>
|
||||
|
|
@ -318,7 +402,9 @@ export function NodeEditDialog({
|
|||
with a ternary: {'{{ trust ? friend : hostile }}'}, also {'{{ !key }}'} and
|
||||
{'{{ rep >= 5 ? elite : rookie }}'}. Branches may nest tokens. Inline
|
||||
images use {''} (e.g. {``}) and
|
||||
render at text height. Lines starting with "- " or "1. " become lists.
|
||||
render at text height. Hold the typing with {'{1.2s}'} or {'{400ms}'} (up to
|
||||
10s); the marker is invisible to players. Lines starting with "- " or "1. "
|
||||
become lists.
|
||||
Right-click the box for a markup menu.
|
||||
</p>
|
||||
</div>
|
||||
|
|
@ -735,7 +821,241 @@ export function NodeEditDialog({
|
|||
</p>
|
||||
</div>
|
||||
)}
|
||||
{draft.effect && (
|
||||
{draft.effect?.type === "poll" && (
|
||||
<div className="flex flex-col gap-3 rounded border border-white/15 bg-zinc-900/60 p-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Question
|
||||
</Label>
|
||||
<Input
|
||||
value={draft.effect.poll?.title ?? ""}
|
||||
onChange={(e) => patchPoll({ title: e.target.value })}
|
||||
placeholder="Should the Task Force work with the Vanguard?"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Context (optional)
|
||||
</Label>
|
||||
<textarea
|
||||
value={draft.effect.poll?.body ?? ""}
|
||||
onChange={(e) => patchPoll({ body: e.target.value })}
|
||||
rows={2}
|
||||
placeholder="What the unit is being asked to weigh."
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Options
|
||||
</Label>
|
||||
{pollOptions.map((option, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col gap-1 rounded border border-white/10 bg-zinc-800/60 p-2"
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
value={option.emoji ?? ""}
|
||||
onChange={(e) => setPollOption(index, { emoji: e.target.value })}
|
||||
placeholder="⚑"
|
||||
className="w-12 text-center bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
<Input
|
||||
value={option.label ?? ""}
|
||||
onChange={(e) => setPollOption(index, { label: e.target.value })}
|
||||
placeholder={`Option ${index + 1}`}
|
||||
className="flex-1 bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removePollOption(index)}
|
||||
disabled={pollOptions.length <= 2}
|
||||
className="h-8 w-8 shrink-0 text-white/60 hover:text-white"
|
||||
>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Input
|
||||
value={option.description ?? ""}
|
||||
onChange={(e) => setPollOption(index, { description: e.target.value })}
|
||||
placeholder="Optional detail under the label"
|
||||
className="bg-zinc-800 border-white/20 text-xs text-white placeholder:text-white/30"
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addPollOption}
|
||||
disabled={pollOptions.length >= 10}
|
||||
className="self-start border-white/20 text-white/70 hover:text-white"
|
||||
>
|
||||
Add option
|
||||
</Button>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Option keys are derived from the labels. Two options that read the same
|
||||
still get distinct keys.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Open for (hours)
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0.25}
|
||||
step={0.25}
|
||||
value={draft.effect.poll?.durationHours ?? 24}
|
||||
onChange={(e) =>
|
||||
patchPoll({ durationHours: Number(e.target.value) || 24 })
|
||||
}
|
||||
className="bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Tie grace (hours)
|
||||
</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={1}
|
||||
step={1}
|
||||
value={draft.effect.poll?.tieGraceHours ?? 24}
|
||||
onChange={(e) =>
|
||||
patchPoll({ tieGraceHours: Number(e.target.value) || 24 })
|
||||
}
|
||||
className="bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||
<Checkbox
|
||||
checked={draft.effect.poll?.multiSelect === true}
|
||||
onCheckedChange={(checked) =>
|
||||
patchPoll({ multiSelect: checked === true })
|
||||
}
|
||||
className="border-white/30 data-[state=checked]:border-emerald-500 data-[state=checked]:bg-emerald-500"
|
||||
/>
|
||||
Allow more than one answer per member
|
||||
</label>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Voter identities
|
||||
</Label>
|
||||
<select
|
||||
value={draft.effect.poll?.anonymity ?? "public"}
|
||||
onChange={(e) =>
|
||||
patchPoll({ anonymity: e.target.value as "public" | "anonymous" })
|
||||
}
|
||||
className="bg-zinc-800 border border-white/20 rounded px-2 py-1 text-sm text-white"
|
||||
>
|
||||
<option value="public">Public: everyone sees who voted</option>
|
||||
<option value="anonymous">
|
||||
Anonymous: counts for members, names for superusers
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Who may vote
|
||||
</Label>
|
||||
<RoleChecklist
|
||||
roles={roles}
|
||||
value={draft.effect.poll?.eligibleRoleIds ?? []}
|
||||
onChange={(eligibleRoleIds) => patchPoll({ eligibleRoleIds })}
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Leave empty for the whole unit.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Voting weight tiers
|
||||
</Label>
|
||||
{pollTiers.map((tier, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="flex flex-col gap-1.5 rounded border border-white/10 bg-zinc-800/60 p-2"
|
||||
>
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Input
|
||||
value={tier.label ?? ""}
|
||||
onChange={(e) => setPollTier(index, { label: e.target.value })}
|
||||
placeholder="Logistics"
|
||||
className="flex-1 bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<Input
|
||||
type="number"
|
||||
min={0.1}
|
||||
step={0.1}
|
||||
value={tier.multiplier ?? 1.5}
|
||||
onChange={(e) =>
|
||||
setPollTier(index, { multiplier: Number(e.target.value) || 1 })
|
||||
}
|
||||
className="w-20 bg-zinc-800 border-white/20 text-white"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => removePollTier(index)}
|
||||
className="h-8 w-8 shrink-0 text-white/60 hover:text-white"
|
||||
>
|
||||
<XIcon className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<RoleChecklist
|
||||
roles={roles}
|
||||
value={tier.roleIds ?? []}
|
||||
onChange={(roleIds) => setPollTier(index, { roleIds })}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={addPollTier}
|
||||
className="self-start border-white/20 text-white/70 hover:text-white"
|
||||
>
|
||||
Add weight tier
|
||||
</Button>
|
||||
<p className="text-[10px] text-white/40">
|
||||
A member in several tiers gets the highest multiplier, never the sum.
|
||||
Weight is resolved from roles when the poll closes.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">
|
||||
Result flag (optional)
|
||||
</Label>
|
||||
<Input
|
||||
value={draft.effect.poll?.resultFlag ?? ""}
|
||||
onChange={(e) => patchPoll({ resultFlag: e.target.value })}
|
||||
placeholder="vanguard_alignment"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Written as a global text flag with the winning option's key when the
|
||||
poll resolves, so conditions and tokens can branch on the outcome.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{draft.effect && draft.effect.type !== "poll" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[10px] uppercase tracking-wider text-white/50">Message</Label>
|
||||
<MarkupEditor
|
||||
|
|
@ -748,7 +1068,9 @@ export function NodeEditDialog({
|
|||
/>
|
||||
</div>
|
||||
)}
|
||||
{draft.effect && draft.effect.type !== "notify" && (
|
||||
{draft.effect &&
|
||||
draft.effect.type !== "notify" &&
|
||||
draft.effect.type !== "poll" && (
|
||||
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||
<Checkbox
|
||||
checked={draft.effect.eventVisibility === "public"}
|
||||
|
|
@ -762,7 +1084,9 @@ export function NodeEditDialog({
|
|||
Show this event to everyone (normally staff only)
|
||||
</label>
|
||||
)}
|
||||
{draft.effect && draft.effect.type !== "notify" && (
|
||||
{draft.effect &&
|
||||
draft.effect.type !== "notify" &&
|
||||
draft.effect.type !== "poll" && (
|
||||
<label className="flex items-center gap-2 text-xs text-white/60">
|
||||
<Checkbox
|
||||
checked={draft.effect.discord === true}
|
||||
|
|
|
|||
|
|
@ -172,7 +172,9 @@ export function NpcDialogueNode({ data, type, selected }: NodeProps) {
|
|||
? "Log game event"
|
||||
: d.effect.type === "flag"
|
||||
? `Set flag "${d.effect.flagKey || "?"}"`
|
||||
: "Reward (unconfigured)"}
|
||||
: d.effect.type === "poll"
|
||||
? `Open poll "${d.effect.poll?.title || "?"}"`
|
||||
: "Reward (unconfigured)"}
|
||||
{d.effect.message ? `: "${d.effect.message}"` : ""}
|
||||
</span>
|
||||
) : (
|
||||
|
|
|
|||
|
|
@ -29,6 +29,7 @@ import {
|
|||
Truck,
|
||||
UserCog,
|
||||
Users,
|
||||
Vote,
|
||||
} from "lucide-react";
|
||||
|
||||
export const sidebarData = {
|
||||
|
|
@ -109,6 +110,11 @@ export const sidebarData = {
|
|||
url: "/operations/extractions",
|
||||
icon: ClipboardCheck,
|
||||
},
|
||||
{
|
||||
title: "Unit Polls",
|
||||
url: "/polls",
|
||||
icon: Vote,
|
||||
},
|
||||
],
|
||||
navLogistics: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,7 +1,15 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState, Fragment } from "react";
|
||||
import { LockIcon, MessageCircleIcon, Volume2Icon, VolumeXIcon, XIcon } from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import {
|
||||
LockIcon,
|
||||
MessageCircleIcon,
|
||||
Volume2Icon,
|
||||
VolumeXIcon,
|
||||
VoteIcon,
|
||||
XIcon,
|
||||
} from "lucide-react";
|
||||
|
||||
import type { GameNpc } from "@/payload-types";
|
||||
import type { ChoiceGate, DialogueNext, DialogueNode, FlowData } from "@/lib/npc-dialogue/dialogue";
|
||||
|
|
@ -12,10 +20,12 @@ import { choiceIndexFromKey, choiceShortcutLabel, isSkipKey } from "@/lib/npc-di
|
|||
import {
|
||||
DEFAULT_PACING_PRESET,
|
||||
beatMs,
|
||||
lineDurationMs,
|
||||
buildRevealSchedule,
|
||||
scaleSchedule,
|
||||
shownAt,
|
||||
} from "@/lib/npc-dialogue/pacing";
|
||||
import type { PacingPreset } from "@/lib/npc-dialogue/pacing";
|
||||
import { playTypeTick, primeTypeSound } from "@/lib/npc-dialogue/typeSound";
|
||||
import { DialogueAttachments } from "@/components/frontend/personnel/DialogueAttachments";
|
||||
import {
|
||||
|
|
@ -58,6 +68,9 @@ interface NpcConversationProps {
|
|||
readonly typewriterSound?: boolean;
|
||||
/** Play recorded voice clips. The header button mutes for the session. */
|
||||
readonly voice?: boolean;
|
||||
/** Typing speed and punctuation pauses, chosen in the admin panel. Resolved
|
||||
* server-side so the dialog needs no round trip for it. */
|
||||
readonly pacing?: PacingPreset;
|
||||
}
|
||||
|
||||
interface ResolvedFlow {
|
||||
|
|
@ -95,9 +108,10 @@ function resolveFlow(dialogue: NpcConversationProps["dialogue"]): ResolvedFlow |
|
|||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
/** Longest a line may take, pauses included. Past this the schedule is
|
||||
* compressed: a wall of text still has to arrive while the player is looking. */
|
||||
const REVEAL_CAP_MS = 3000;
|
||||
/* Line duration lives in pacing.ts (`lineDurationMs`): the 3s ceiling that used
|
||||
* to sit here compressed every line past about 120 characters, down to 8ms per
|
||||
* character on a long one, which is why the typing felt faster the deeper a
|
||||
* conversation went. */
|
||||
|
||||
/** True when the device asks for reduced motion; the animation is skipped
|
||||
* entirely rather than merely shortened. */
|
||||
|
|
@ -151,6 +165,7 @@ export function NpcConversation({
|
|||
typewriter = true,
|
||||
typewriterSound = true,
|
||||
voice = true,
|
||||
pacing = DEFAULT_PACING_PRESET,
|
||||
}: NpcConversationProps) {
|
||||
const flow = useMemo(() => resolveFlow(dialogue), [dialogue]);
|
||||
const [open, setOpen] = useState(false);
|
||||
|
|
@ -372,11 +387,10 @@ export function NpcConversation({
|
|||
// clip takes over as the target and the schedule is scaled to fit it, which
|
||||
// keeps text and speech together. Only a very long line is compressed, by
|
||||
// the cap.
|
||||
const unscaled = buildRevealSchedule(text);
|
||||
const durationMs =
|
||||
voiceStarted && clipSeconds > 0.4
|
||||
? Math.min(60_000, clipSeconds * 1000)
|
||||
: Math.min(REVEAL_CAP_MS, unscaled.total);
|
||||
const unscaled = buildRevealSchedule(text, pacing);
|
||||
const voicedMs =
|
||||
voiceStarted && clipSeconds > 0.4 ? Math.min(60_000, clipSeconds * 1000) : null;
|
||||
const durationMs = lineDurationMs(unscaled, voicedMs);
|
||||
|
||||
setLog((prev) => [
|
||||
...prev,
|
||||
|
|
@ -458,7 +472,7 @@ export function NpcConversation({
|
|||
const beatThen = async (node: DialogueNode, token: number) => {
|
||||
skipBeatRef.current = false;
|
||||
setTyping(node.data.speaker?.trim() || npc.name);
|
||||
const wait = beatMs();
|
||||
const wait = beatMs(pacing);
|
||||
const startedAt = performance.now();
|
||||
try {
|
||||
while (performance.now() - startedAt < wait) {
|
||||
|
|
@ -542,9 +556,15 @@ export function NpcConversation({
|
|||
// Await the effect so flags it writes are visible to the lines
|
||||
// that follow (interpolated text and later condition nodes).
|
||||
if (dialogueId !== null) {
|
||||
await triggerNpcDialogueEvent(dialogueId, Number(npc.id), current.id).catch(
|
||||
() => undefined,
|
||||
);
|
||||
const result = await triggerNpcDialogueEvent(
|
||||
dialogueId,
|
||||
Number(npc.id),
|
||||
current.id,
|
||||
).catch(() => null);
|
||||
// A poll effect hands back the poll it opened (or joined).
|
||||
if (result?.success && result.data?.pollId) {
|
||||
setRaisedPollId(result.data.pollId);
|
||||
}
|
||||
}
|
||||
if (sessionRef.current !== token) return;
|
||||
}
|
||||
|
|
@ -590,6 +610,11 @@ export function NpcConversation({
|
|||
const [awaitingContinueId, setAwaitingContinueId] = useState<string | null>(null);
|
||||
const continueResolverRef = useRef<(() => void) | null>(null);
|
||||
|
||||
/** Poll raised by an event node in this conversation. The notification is the
|
||||
* durable path; this link keeps the player from having to leave the dialog
|
||||
* and find it in their inbox. */
|
||||
const [raisedPollId, setRaisedPollId] = useState<number | null>(null);
|
||||
|
||||
/** Let the parked cascade continue. Idempotent: a second press finds no
|
||||
* resolver and does nothing. */
|
||||
const resumeContinue = () => {
|
||||
|
|
@ -969,6 +994,21 @@ export function NpcConversation({
|
|||
</div>
|
||||
</div>
|
||||
|
||||
{/* A conversation that raised a poll leaves a way back to it. The
|
||||
notification is the durable path; this keeps the player in
|
||||
the dialog without having to hunt for it. */}
|
||||
{raisedPollId !== null && (
|
||||
<div className="shrink-0 border-t border-cyan-500/30 bg-cyan-500/5 px-4 py-2">
|
||||
<Link
|
||||
href={`/polls/${raisedPollId}`}
|
||||
className="flex items-center gap-2 text-xs text-cyan-300 underline-offset-4 hover:underline"
|
||||
>
|
||||
<VoteIcon className="size-3.5 shrink-0" />
|
||||
The unit is being polled on this. Open the poll.
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* The footer opens by growing its grid row, so the menu slides in
|
||||
and the log above it gives up height over the same 260ms
|
||||
instead of the text jumping up in one frame. Always mounted so
|
||||
|
|
|
|||
328
src/components/frontend/polls/PollVotePanel.tsx
Normal file
328
src/components/frontend/polls/PollVotePanel.tsx
Normal file
|
|
@ -0,0 +1,328 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState, useTransition } from "react";
|
||||
import Link from "next/link";
|
||||
import { Check, Clock, Gavel, ShieldQuestion, Users } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Progress } from "@/components/ui/progress";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { PollView } from "@/lib/polls/surface";
|
||||
import { castPollVoteAction, getPollViewAction, resolvePollTieAction } from "@/app/(frontend)/polls/actions";
|
||||
|
||||
const REFRESH_MS = 10_000;
|
||||
|
||||
const formatWeight = (value: number): string =>
|
||||
Number.isInteger(value) ? String(value) : value.toFixed(2);
|
||||
|
||||
const formatWhen = (iso: string | null): string => {
|
||||
if (!iso) return "n/a";
|
||||
const date = new Date(iso);
|
||||
return Number.isNaN(date.getTime()) ? "n/a" : date.toLocaleString();
|
||||
};
|
||||
|
||||
const relative = (iso: string | null): string => {
|
||||
if (!iso) return "";
|
||||
const ms = new Date(iso).getTime() - Date.now();
|
||||
if (Number.isNaN(ms)) return "";
|
||||
const abs = Math.abs(ms);
|
||||
const minutes = Math.round(abs / 60_000);
|
||||
const hours = Math.round(abs / 3_600_000);
|
||||
const days = Math.round(abs / 86_400_000);
|
||||
const span =
|
||||
minutes < 60 ? `${minutes}m` : hours < 48 ? `${hours}h` : `${days}d`;
|
||||
return ms >= 0 ? `in ${span}` : `${span} ago`;
|
||||
};
|
||||
|
||||
function StatusBadge({ view }: { view: PollView }) {
|
||||
if (view.awaitingDecision) {
|
||||
return <Badge variant="outline" className="border-amber-500/50 text-amber-300">Tied</Badge>;
|
||||
}
|
||||
if (view.closed) {
|
||||
return <Badge variant="outline" className="border-white/20 text-muted-foreground">Closed</Badge>;
|
||||
}
|
||||
return <Badge variant="outline" className="border-emerald-500/50 text-emerald-300">Open</Badge>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vote panel for one poll. Voting, the live tally, and the superuser tie
|
||||
* decision all live here so the page itself stays a server component.
|
||||
*
|
||||
* The tally refreshes on a scoped timer instead of the app-wide SSE bus: every
|
||||
* game event makes each client re-render its whole layout, and a poll page
|
||||
* does not need to join that fan-out.
|
||||
*/
|
||||
export function PollVotePanel({ initialView }: { initialView: PollView }) {
|
||||
const [view, setView] = useState<PollView>(initialView);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [isPending, startTransition] = useTransition();
|
||||
const busy = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
setView(initialView);
|
||||
}, [initialView]);
|
||||
|
||||
const refresh = useCallback(() => {
|
||||
if (busy.current || document.visibilityState !== "visible") return;
|
||||
startTransition(async () => {
|
||||
const result = await getPollViewAction(initialView.id);
|
||||
if (result.success && result.data) setView(result.data);
|
||||
});
|
||||
}, [initialView.id]);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(refresh, REFRESH_MS);
|
||||
return () => clearInterval(timer);
|
||||
}, [refresh]);
|
||||
|
||||
const applyAnswers = (answers: string[]) => {
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
busy.current = true;
|
||||
startTransition(async () => {
|
||||
const result = await castPollVoteAction(view.id, answers);
|
||||
busy.current = false;
|
||||
if (!result.success || !result.data) {
|
||||
setError(result.error ?? "Your vote could not be recorded.");
|
||||
return;
|
||||
}
|
||||
setView(result.data);
|
||||
setNotice(answers.length === 0 ? "Vote withdrawn." : "Vote recorded.");
|
||||
});
|
||||
};
|
||||
|
||||
const toggleOption = (key: string) => {
|
||||
if (!view.canVote) return;
|
||||
if (view.multiSelect) {
|
||||
const next = view.yourAnswers.includes(key)
|
||||
? view.yourAnswers.filter((answer) => answer !== key)
|
||||
: [...view.yourAnswers, key];
|
||||
applyAnswers(next);
|
||||
return;
|
||||
}
|
||||
// Single answer: pressing the chosen option again retracts it.
|
||||
applyAnswers(view.yourAnswers.includes(key) ? [] : [key]);
|
||||
};
|
||||
|
||||
const settleTie = (winnerKey: string) => {
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
busy.current = true;
|
||||
startTransition(async () => {
|
||||
const result = await resolvePollTieAction(view.id, winnerKey);
|
||||
busy.current = false;
|
||||
if (!result.success || !result.data) {
|
||||
setError(result.error ?? "The decision could not be recorded.");
|
||||
return;
|
||||
}
|
||||
setView(result.data);
|
||||
setNotice("Tie settled.");
|
||||
});
|
||||
};
|
||||
|
||||
const tiedOptions = view.options.filter((option) => view.tiedKeys.includes(option.key));
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<Card>
|
||||
<CardHeader className="gap-2">
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<StatusBadge view={view} />
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.multiSelect ? "Multiple answers" : "One answer"}
|
||||
</Badge>
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.anonymity === "anonymous" ? "Anonymous" : "Public"}
|
||||
</Badge>
|
||||
{view.eligibleRoleCount > 0 && (
|
||||
<Badge variant="outline" className="border-white/20 text-muted-foreground">
|
||||
{view.eligibleRoleCount} eligible role{view.eligibleRoleCount === 1 ? "" : "s"}
|
||||
</Badge>
|
||||
)}
|
||||
{view.initiated && (
|
||||
<Badge variant="outline" className="border-sky-500/50 text-sky-300">
|
||||
You opened this
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<CardTitle className="text-xl">{view.title}</CardTitle>
|
||||
{view.body && <p className="text-sm text-muted-foreground">{view.body}</p>}
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-3">
|
||||
<div className="flex flex-wrap items-center gap-x-4 gap-y-1 text-xs text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
<Clock className="size-3.5" />
|
||||
{view.closed
|
||||
? `Closed ${formatWhen(view.closesAt)}`
|
||||
: `Closes ${formatWhen(view.closesAt)} (${relative(view.closesAt)})`}
|
||||
</span>
|
||||
<span className="flex items-center gap-1">
|
||||
<Users className="size-3.5" />
|
||||
{view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"} · weight{" "}
|
||||
{formatWeight(view.totalWeight)}
|
||||
</span>
|
||||
{view.anonymity === "anonymous" && (
|
||||
<span className="flex items-center gap-1">
|
||||
<ShieldQuestion className="size-3.5" />
|
||||
{view.showsVoters
|
||||
? "Anonymous to members; you can see voters"
|
||||
: "Voter identities are hidden"}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
{view.options.map((option) => {
|
||||
const chosen = option.chosen;
|
||||
const selectable = view.canVote;
|
||||
return (
|
||||
<div
|
||||
key={option.key}
|
||||
className={cn(
|
||||
"rounded-lg border p-3 transition-colors",
|
||||
chosen ? "border-emerald-500/50 bg-emerald-500/5" : "border-white/10",
|
||||
)}
|
||||
>
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<div className="flex items-center gap-2 text-sm font-medium">
|
||||
{option.emoji && <span>{option.emoji}</span>}
|
||||
<span className="truncate">{option.label}</span>
|
||||
{chosen && <Check className="size-4 shrink-0 text-emerald-400" />}
|
||||
</div>
|
||||
{option.description && (
|
||||
<p className="mt-0.5 text-xs text-muted-foreground">{option.description}</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="shrink-0 text-right font-mono text-xs text-muted-foreground">
|
||||
<div>{option.raw}</div>
|
||||
<div className="text-[10px]">weight {formatWeight(option.weighted)}</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Progress value={option.share} className="mt-2 h-1.5" />
|
||||
|
||||
{option.voters.length > 0 && (
|
||||
<p className="mt-1.5 text-[11px] text-muted-foreground">
|
||||
{option.voters.join(", ")}
|
||||
</p>
|
||||
)}
|
||||
|
||||
{selectable && (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant={chosen ? "secondary" : "outline"}
|
||||
className="mt-2"
|
||||
disabled={isPending}
|
||||
onClick={() => toggleOption(option.key)}
|
||||
>
|
||||
{chosen
|
||||
? view.multiSelect
|
||||
? "Remove my answer"
|
||||
: "Withdraw my vote"
|
||||
: view.multiSelect
|
||||
? "Add my answer"
|
||||
: "Vote for this"}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{error && <p className="text-sm text-destructive">{error}</p>}
|
||||
{notice && !error && <p className="text-sm text-emerald-400">{notice}</p>}
|
||||
|
||||
{!view.canVote && !view.closed && view.eligibleRoleCount > 0 && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only members holding one of this poll's eligible roles may vote.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{view.resolved && (
|
||||
<p className="text-sm">
|
||||
{view.winnerKey ? (
|
||||
<>
|
||||
<span className="text-muted-foreground">Outcome: </span>
|
||||
<span className="font-medium">{view.winnerLabel}</span>
|
||||
<span className="text-muted-foreground">
|
||||
{" "}
|
||||
({view.resolutionMethod?.replace("_", " ")})
|
||||
</span>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-muted-foreground">
|
||||
{view.totalVotes === 0
|
||||
? "No decision: nobody voted, so no result flag was written."
|
||||
: "No decision: no option carried a weighted score, so no result flag was written."}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{view.awaitingDecision && (
|
||||
<Card className="border-amber-500/30">
|
||||
<CardHeader className="gap-1">
|
||||
<CardTitle className="flex items-center gap-2 text-base">
|
||||
<Gavel className="size-4 text-amber-300" />
|
||||
Tied vote
|
||||
</CardTitle>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
The top options scored the same and the initiator's vote could not break it.
|
||||
{view.decisionDeadline
|
||||
? ` If nobody decides by ${formatWhen(view.decisionDeadline)} (${relative(
|
||||
view.decisionDeadline,
|
||||
)}), a random tied option wins.`
|
||||
: ""}
|
||||
</p>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-2">
|
||||
{tiedOptions.map((option) => (
|
||||
<div key={option.key} className="flex items-center justify-between gap-3">
|
||||
<span className="text-sm">
|
||||
{option.emoji ? `${option.emoji} ` : ""}
|
||||
{option.label}
|
||||
<span className="ml-2 text-xs text-muted-foreground">
|
||||
weight {formatWeight(option.weighted)}
|
||||
</span>
|
||||
</span>
|
||||
{view.canResolve ? (
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={isPending}
|
||||
onClick={() => settleTie(option.key)}
|
||||
>
|
||||
Decide
|
||||
</Button>
|
||||
) : null}
|
||||
</div>
|
||||
))}
|
||||
{!view.canResolve && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A superuser will settle this.
|
||||
</p>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between text-xs text-muted-foreground">
|
||||
<Link href="/polls" className="underline-offset-4 hover:underline">
|
||||
All polls
|
||||
</Link>
|
||||
<span>{isPending ? "Updating..." : `Refreshes every ${REFRESH_MS / 1000}s`}</span>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -33,6 +33,7 @@ lib/
|
|||
logistics/ # Mission lifecycle + mission reminder logic
|
||||
market/ # Buy/sell, NPC negotiation, dialogue, vendor resolution
|
||||
notifications/ # User notification helper + muteable types
|
||||
polls/ # Unit polls: tally.ts (pure weights/tie ladder), service.ts (single write path), surface.ts (read model + anonymity), realtime.ts (pg_notify)
|
||||
projects/ # Project ticket-type metadata (projectMeta.ts)
|
||||
realtime/ # In-process SSE bus + presence tracking (single-instance only)
|
||||
session/ # Session token expiry helpers
|
||||
|
|
|
|||
|
|
@ -316,6 +316,19 @@ export async function generatePlainText(
|
|||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The shape `generateStructured` needs from a structured stream. Narrow on
|
||||
* purpose: it lets a test supply a lazy stream without mocking the whole `ai`
|
||||
* module, and it keeps the production call readable.
|
||||
*/
|
||||
export interface StructuredStreamFactory {
|
||||
(options: Record<string, unknown>): {
|
||||
textStream: AsyncIterable<string>;
|
||||
object: Promise<unknown>;
|
||||
finishReason: Promise<string>;
|
||||
};
|
||||
}
|
||||
|
||||
export interface StructuredGenerationOptions {
|
||||
/** The user-turn instruction. */
|
||||
prompt: string;
|
||||
|
|
@ -336,6 +349,13 @@ export interface StructuredGenerationOptions {
|
|||
* callers pass something smaller.
|
||||
*/
|
||||
timeoutMs?: number;
|
||||
/**
|
||||
* Seam for tests. Production always uses the SDK's `streamObject`; a test that
|
||||
* needs to model a lazy provider stream supplies its own here, because
|
||||
* mocking the `ai` module is unreliable when the test worker shares a module
|
||||
* registry between files.
|
||||
*/
|
||||
streamFactory?: StructuredStreamFactory;
|
||||
}
|
||||
|
||||
export interface StructuredResult<T> {
|
||||
|
|
@ -410,7 +430,8 @@ export async function generateStructured<T>(
|
|||
|
||||
const reasoning = connection ? connection.sendReasoningOff !== false : true;
|
||||
|
||||
const result = streamObject({
|
||||
const factory = options.streamFactory ?? (streamObject as unknown as StructuredStreamFactory);
|
||||
const result = factory({
|
||||
maxOutputTokens: options.maxTokens ?? 5000,
|
||||
// No transport retries. The SDK's default (two) turns one stalled stream into
|
||||
// three sequential waits, which is how a 60s idle abort became a multi-minute
|
||||
|
|
@ -422,7 +443,7 @@ export async function generateStructured<T>(
|
|||
// modal waits on `result.object` for as long as the stream dribbles.
|
||||
abortSignal: AbortSignal.timeout(options.timeoutMs ?? REQUEST_TIMEOUT_MS),
|
||||
model: chatModelFor(connection, connection?.modelId || options.model || resolveModel()),
|
||||
onError: (error) => {
|
||||
onError: (error: unknown) => {
|
||||
console.error("AI generateStructured: ", error);
|
||||
},
|
||||
prompt: options.prompt,
|
||||
|
|
|
|||
|
|
@ -334,6 +334,35 @@ markers for the offered ones), plus one flag evaluation per NPC that has a gated
|
|||
conversation. The page swallows loader errors and renders no chips rather than
|
||||
failing the directory.
|
||||
|
||||
### Typing pace and authored pauses
|
||||
|
||||
`pacing.ts` prices the reveal: a per-unit cost from the active preset plus a
|
||||
pause after punctuation and line breaks. Three presets exist (`subtle` 22ms,
|
||||
`natural` 30ms, `pronounced` 42ms per character) and each moves the character cost
|
||||
and the punctuation pauses together, because a slow character rate with brisk
|
||||
pauses reads as broken rather than deliberate. The unit picks one in the NPC
|
||||
Dialogue Prompt global (Presentation, "Typing pace"); `loadDialogueSettings`
|
||||
normalises it, so an unknown stored value falls back to `natural` instead of
|
||||
rendering with no pacing. Changing it applies to the next conversation opened,
|
||||
no deploy. A line
|
||||
takes `lineDurationMs` of the schedule: a recorded clip sets the target, an
|
||||
authored pause outlasts a short clip, and a silent line is never compressed
|
||||
below the base pace (ceiling `MAX_LINE_MS` 20s, floor 500ms).
|
||||
|
||||
That ceiling used to be 3s in the component, which silently compressed every
|
||||
line past about 120 characters: 240 characters ran at 13ms per character and
|
||||
360 at 8. Long NPC lines therefore read as if the typing had sped up, which is
|
||||
what "it gets faster the deeper you go" turned out to be. The cap now sits high
|
||||
enough that it only catches a wall of text, and the duration rule lives in
|
||||
`lineDurationMs` so it can be tested without a browser.
|
||||
|
||||
Authors can hold a line anywhere with `{1.2s}` or `{400ms}` (clamped to 10s).
|
||||
`DialogueText`'s parser skips the marker and records where it sat;
|
||||
`visibleSegments` exposes that to the schedule, which charges the pause between
|
||||
the units either side. Pauses are **absolute**: `scaleSchedule` strips them out
|
||||
before scaling, so matching a line to a voice clip never shortens a beat the
|
||||
author asked for. The admin preview shows markers as written.
|
||||
|
||||
### The Continue gate
|
||||
|
||||
`data.requireContinue` (dialogue node, off by default) parks the conversation on
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useState, type ReactNode } from "react";
|
||||
import { memo, useEffect, useState, type ReactNode } from "react";
|
||||
import { ExternalLinkIcon, XIcon } from "lucide-react";
|
||||
|
||||
import { Dialog, DialogContent, DialogTitle } from "@/components/ui/dialog";
|
||||
|
|
@ -36,6 +36,9 @@ interface RevealBudget {
|
|||
* An image or a countdown contributes one placeholder character (it costs
|
||||
* one unit but renders no text of its own). */
|
||||
seen?: string[];
|
||||
/** Authored pauses (`{1.2s}`), positioned by how many visible characters
|
||||
* precede them. Renders nothing; the schedule is what gives it a duration. */
|
||||
pauses?: { at: number; ms: number }[];
|
||||
}
|
||||
|
||||
/** One visible unit of an image or a countdown: countable, non-space, and
|
||||
|
|
@ -52,7 +55,9 @@ const UNLIMITED_REVEAL = Number.MAX_SAFE_INTEGER;
|
|||
* the whole line. Truncation happens on the rendered strings, never on the
|
||||
* source, so a half-typed line can never show `{gre` or an unclosed `**`.
|
||||
*/
|
||||
export function DialogueText({
|
||||
/** Memoised: the canvas and the editor preview render the same line many times
|
||||
* per interaction, and a re-parse is the expensive part. */
|
||||
const DialogueText = memo(function DialogueTextImpl({
|
||||
text,
|
||||
className,
|
||||
reveal,
|
||||
|
|
@ -69,7 +74,9 @@ export function DialogueText({
|
|||
{renderBlocks(text, { i: 0 }, budget)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
export { DialogueText };
|
||||
|
||||
/**
|
||||
* Visible characters in a line, counted the way `reveal` counts them (markup
|
||||
|
|
@ -89,9 +96,22 @@ export function visibleLength(text: string): number {
|
|||
* it fits.
|
||||
*/
|
||||
export function visibleText(text: string): string {
|
||||
const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [] };
|
||||
return visibleSegments(text).text;
|
||||
}
|
||||
|
||||
/**
|
||||
* The same walk as `visibleText`, plus where the authored pauses fall. `at` is
|
||||
* the count of visible characters before the pause, so a schedule can charge
|
||||
* the gap between two specific units. Markers cost nothing themselves and never
|
||||
* reach the page.
|
||||
*/
|
||||
export function visibleSegments(text: string): {
|
||||
text: string;
|
||||
pauses: { at: number; ms: number }[];
|
||||
} {
|
||||
const budget: RevealBudget = { left: UNLIMITED_REVEAL, seen: [], pauses: [] };
|
||||
renderBlocks(text, { i: 0 }, budget);
|
||||
return (budget.seen ?? []).join("");
|
||||
return { text: (budget.seen ?? []).join(""), pauses: budget.pauses ?? [] };
|
||||
}
|
||||
|
||||
const BULLET_RE = /^[-*]\s+/;
|
||||
|
|
@ -185,6 +205,12 @@ const MAX_DEPTH = 8;
|
|||
const IMG_RE = /^!\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const LINK_RE = /^\[([^\]]*)\]\(([^()\s]*)\)/;
|
||||
const COLOR_OPEN_RE = /^\{([^{}|]{1,20})\}/;
|
||||
/** An authored pause: `{1.2s}`, `{400ms}`, `{2S}`. Digits first so it can never
|
||||
* collide with the colour tokens that also use braces. */
|
||||
const PAUSE_RE = /^\{(\d+(?:\.\d+)?)(ms|s)\}/i;
|
||||
/** Longest an authored pause may hold a line. A conversation is not a place to
|
||||
* park a player, and a typo such as `{90s}` should not read as a broken line. */
|
||||
export const MAX_PAUSE_MS = 10_000;
|
||||
const COUNTDOWN_RE = /^\{cd\|([^}]*)\}/;
|
||||
|
||||
/** Only http(s) and site-relative URLs render; anything else stays literal. */
|
||||
|
|
@ -327,11 +353,35 @@ function parseSegment(
|
|||
}
|
||||
}
|
||||
|
||||
// Authored pause. It renders nothing; the pacing schedule reads where it
|
||||
// sits from the budget and gives the line that much extra time.
|
||||
if (rest[0] === "{") {
|
||||
const pause = PAUSE_RE.exec(rest);
|
||||
if (pause) {
|
||||
flush();
|
||||
const amount = Number.parseFloat(pause[1]);
|
||||
const ms = Math.round(pause[2].toLowerCase() === "s" ? amount * 1000 : amount);
|
||||
budget.pauses?.push({
|
||||
at: budget.seen ? budget.seen.reduce((total, chunk) => total + chunk.length, 0) : 0,
|
||||
ms: Math.min(MAX_PAUSE_MS, Math.max(0, ms)),
|
||||
});
|
||||
i += pause[0].length;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Color run: recurse so inner markup renders inside the colored span.
|
||||
if (rest[0] === "{") {
|
||||
const open = COLOR_OPEN_RE.exec(rest);
|
||||
if (open && open[1] !== "/") {
|
||||
flush();
|
||||
// A failed attempt (unknown token, unclosed run) falls through and
|
||||
// renders the braces literally, so what it consumed has to be given
|
||||
// back: the recursion had already spent budget on the "inner" text and
|
||||
// the line would otherwise count those characters twice.
|
||||
const leftBefore = budget.left;
|
||||
const seenBefore = budget.seen ? [...budget.seen] : undefined;
|
||||
const pausesBefore = budget.pauses ? [...budget.pauses] : undefined;
|
||||
const inner = parseSegment(text.slice(i + open[0].length), depth + 1, keys, true, budget);
|
||||
const style = colorStyle(open[1]);
|
||||
if (inner.closed && style) {
|
||||
|
|
@ -347,7 +397,11 @@ function parseSegment(
|
|||
i += open[0].length + inner.consumed;
|
||||
continue;
|
||||
}
|
||||
// Unknown token or unclosed: fall through and render literally.
|
||||
// Unknown token or unclosed: restore what the attempt consumed, then
|
||||
// fall through and render the braces literally.
|
||||
budget.left = leftBefore;
|
||||
if (seenBefore) budget.seen = seenBefore;
|
||||
if (pausesBefore) budget.pauses = pausesBefore;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -130,9 +130,47 @@ export const NUMERIC_CONDITION_OPS: DialogueFlagCondition["op"][] = [
|
|||
/** How a flag effect writes the flag. */
|
||||
export type DialogueFlagOp = "set_true" | "set_false" | "set_number" | "set_text" | "add";
|
||||
|
||||
/** One answer on a poll effect. `key` is the stable slug votes reference. */
|
||||
export interface NpcDialoguePollOption {
|
||||
key?: string;
|
||||
label?: string;
|
||||
emoji?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/** A role-based voting weight on a poll effect. Highest matching tier wins. */
|
||||
export interface NpcDialoguePollWeightTier {
|
||||
label?: string;
|
||||
roleIds?: number[];
|
||||
multiplier?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* A unit-wide poll raised by an `event` node. The node only carries the
|
||||
* authoring config; the poll itself is a `polls` document created on first
|
||||
* trigger, so editing the node later cannot rewrite a poll people voted in.
|
||||
*/
|
||||
export interface NpcDialoguePollConfig {
|
||||
title?: string;
|
||||
body?: string;
|
||||
options?: NpcDialoguePollOption[];
|
||||
/** How long the poll stays open. */
|
||||
durationHours?: number;
|
||||
multiSelect?: boolean;
|
||||
anonymity?: "public" | "anonymous";
|
||||
/** Empty means the whole unit. */
|
||||
eligibleRoleIds?: number[];
|
||||
defaultWeight?: number;
|
||||
weightTiers?: NpcDialoguePollWeightTier[];
|
||||
/** Global player-flag key written with the winning option's key on resolution. */
|
||||
resultFlag?: string;
|
||||
/** How long a superuser has to break a tie before a random tied option wins. */
|
||||
tieGraceHours?: number;
|
||||
}
|
||||
|
||||
/** Configured effect for an `event` node. */
|
||||
export interface NpcDialogueEffect {
|
||||
type: "notify" | "emit" | "reward" | "flag";
|
||||
type: "notify" | "emit" | "reward" | "flag" | "poll";
|
||||
/** In-app notification title (notify). */
|
||||
title?: string;
|
||||
/** Notification / event-log body (notify, emit). */
|
||||
|
|
@ -174,6 +212,12 @@ export interface NpcDialogueEffect {
|
|||
flagTarget?: "self" | "global" | "user";
|
||||
/** `flagTarget === "user"`: the player the flag belongs to. */
|
||||
flagTargetUserId?: number | null;
|
||||
/**
|
||||
* Poll settings (poll). Copied into a `polls` document the first time a
|
||||
* player reaches this node; later triggers join that poll instead of
|
||||
* opening a second one.
|
||||
*/
|
||||
poll?: NpcDialoguePollConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -298,6 +342,7 @@ export const EFFECT_TYPES: NpcDialogueEffect["type"][] = [
|
|||
"emit",
|
||||
"reward",
|
||||
"flag",
|
||||
"poll",
|
||||
];
|
||||
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
import { normalizePacingPreset } from "./pacing";
|
||||
import type { PacingPreset } from "./pacing";
|
||||
import { resolveVoice } from "./generationPrompt";
|
||||
import type { ResolvedVoice } from "./generationPrompt";
|
||||
|
||||
|
|
@ -27,6 +29,7 @@ type SettingsDoc = {
|
|||
revision?: number | null;
|
||||
presentation?: {
|
||||
typewriterDefault?: boolean | null;
|
||||
pacing?: string | null;
|
||||
} | null;
|
||||
} | null;
|
||||
|
||||
|
|
@ -39,6 +42,8 @@ export interface DialoguePromptSettings {
|
|||
revision: number | null;
|
||||
/** Unit default for typing conversation lines out character by character. */
|
||||
typewriterDefault: boolean;
|
||||
/** How fast conversations type out, chosen in the admin panel. */
|
||||
pacing: PacingPreset;
|
||||
}
|
||||
|
||||
const EMPTY: DialoguePromptSettings = {
|
||||
|
|
@ -46,6 +51,7 @@ const EMPTY: DialoguePromptSettings = {
|
|||
extraRules: null,
|
||||
revision: null,
|
||||
typewriterDefault: true,
|
||||
pacing: "natural",
|
||||
};
|
||||
|
||||
/** Read the prompt settings, falling back to the built-in defaults on any miss. */
|
||||
|
|
@ -67,6 +73,7 @@ export async function loadDialogueSettings(payload: Payload): Promise<DialoguePr
|
|||
// Only an explicit false turns it off, so a document written before this
|
||||
// field existed still types out (its default).
|
||||
typewriterDefault: doc?.presentation?.typewriterDefault !== false,
|
||||
pacing: normalizePacingPreset(doc?.presentation?.pacing),
|
||||
};
|
||||
} catch (error) {
|
||||
// A missing global (fresh database before the migration ran) must not make
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { visibleText } from "./DialogueText";
|
||||
import { visibleSegments } from "./DialogueText";
|
||||
|
||||
/**
|
||||
* Pacing for a conversation line that types itself out.
|
||||
|
|
@ -13,8 +13,10 @@ import { visibleText } from "./DialogueText";
|
|||
* Pure and client-safe: no Payload, no timers. The component owns the clock.
|
||||
*/
|
||||
|
||||
/** How long each of the four kinds of pause costs. */
|
||||
/** How long each of the four kinds of pause costs, and how fast characters land. */
|
||||
export interface PauseProfile {
|
||||
/** Cost of one visible character. The overall speed of a line. */
|
||||
readonly baseMs: number;
|
||||
/** After a comma, semicolon or colon. */
|
||||
readonly clauseMs: number;
|
||||
/** After a full stop, question mark, exclamation mark or ellipsis. */
|
||||
|
|
@ -27,18 +29,35 @@ export interface PauseProfile {
|
|||
readonly beatMs: number;
|
||||
}
|
||||
|
||||
/** Cost of one visible unit before any pause is added. */
|
||||
export const BASE_UNIT_MS = 24;
|
||||
|
||||
/**
|
||||
* The three approved strengths. `natural` is the unit default: long enough to
|
||||
* read as speech, short enough that a ten line conversation is not a chore.
|
||||
* Tuned up once from the first cut, which read as too rushed at commas.
|
||||
* The three strengths, chosen in the admin panel (NPC Dialogue Prompt,
|
||||
* Presentation). Each one changes both speeds at once: how fast characters land
|
||||
* and how long each punctuation pause holds, because a slow character rate with
|
||||
* brisk pauses reads as broken, not deliberate.
|
||||
*
|
||||
* `natural` is the default: about 33 characters a second, long enough to read as
|
||||
* speech, short enough that a ten line conversation is not a chore. The first cut
|
||||
* was 24ms a character, which measured fine on paper and read as a blur.
|
||||
*/
|
||||
export const PACING_PRESETS: Record<string, PauseProfile> = {
|
||||
subtle: { clauseMs: 80, sentenceMs: 220, newlineMs: 280, paragraphMs: 460, beatMs: 460 },
|
||||
natural: { clauseMs: 155, sentenceMs: 370, newlineMs: 450, paragraphMs: 720, beatMs: 720 },
|
||||
subtle: {
|
||||
baseMs: 22,
|
||||
clauseMs: 80,
|
||||
sentenceMs: 220,
|
||||
newlineMs: 280,
|
||||
paragraphMs: 460,
|
||||
beatMs: 460,
|
||||
},
|
||||
natural: {
|
||||
baseMs: 30,
|
||||
clauseMs: 155,
|
||||
sentenceMs: 370,
|
||||
newlineMs: 450,
|
||||
paragraphMs: 720,
|
||||
beatMs: 720,
|
||||
},
|
||||
pronounced: {
|
||||
baseMs: 42,
|
||||
clauseMs: 225,
|
||||
sentenceMs: 540,
|
||||
newlineMs: 640,
|
||||
|
|
@ -51,6 +70,20 @@ export type PacingPreset = keyof typeof PACING_PRESETS;
|
|||
|
||||
export const DEFAULT_PACING_PRESET: PacingPreset = "natural";
|
||||
|
||||
/** Cost of one visible unit at the default preset; see `PauseProfile.baseMs`. */
|
||||
export const BASE_UNIT_MS = PACING_PRESETS[DEFAULT_PACING_PRESET].baseMs;
|
||||
|
||||
/**
|
||||
* Coerce a stored setting to a known preset. Anything unrecognised (an older
|
||||
* document, a value removed from the list) means the default, so a bad value in
|
||||
* the database cannot make a conversation render with no pacing at all.
|
||||
*/
|
||||
export function normalizePacingPreset(value: unknown): PacingPreset {
|
||||
return typeof value === "string" && value in PACING_PRESETS
|
||||
? (value as PacingPreset)
|
||||
: DEFAULT_PACING_PRESET;
|
||||
}
|
||||
|
||||
/** Gaps between typing ticks, in relative units. Wide enough that a fast line
|
||||
* does not turn into a buzz, narrow enough to sound like keys under a sentence. */
|
||||
const TICK_MIN_GAP = 95;
|
||||
|
|
@ -61,8 +94,14 @@ export interface RevealSchedule {
|
|||
* unit `i` appears. */
|
||||
readonly arrival: readonly number[];
|
||||
/** The denominator for scaling: the line is finished once the last unit has
|
||||
* arrived, so trailing pause is deliberately excluded. */
|
||||
* arrived, so trailing punctuation pause is deliberately excluded. */
|
||||
readonly total: number;
|
||||
/** Authored pause (ms) to insert after each unit, index-aligned with
|
||||
* `arrival`; 0 for a unit with no marker. These are absolute: they are the
|
||||
* author's beat, so scaling the line to a voice clip must not shorten them. */
|
||||
readonly pauses: readonly number[];
|
||||
/** Sum of `pauses`, i.e. how much of the line's duration is authored pause. */
|
||||
readonly explicitTotal: number;
|
||||
/** Moments (relative units) at which to play a typing tick, ascending. */
|
||||
readonly ticks: readonly number[];
|
||||
/** The flattened line the schedule was built from, for debugging and tests. */
|
||||
|
|
@ -138,18 +177,32 @@ export function buildRevealSchedule(
|
|||
preset: PacingPreset = DEFAULT_PACING_PRESET,
|
||||
): RevealSchedule {
|
||||
const profile = PACING_PRESETS[preset] ?? PACING_PRESETS.natural;
|
||||
const visible = visibleText(text);
|
||||
if (visible.length === 0) return { arrival: [], total: 0, ticks: [], text: visible };
|
||||
const segments = visibleSegments(text);
|
||||
const visible = segments.text;
|
||||
// Widen the authored markers to "after this unit", so the loop below can price
|
||||
// them with the rest of the rhythm. A marker at the very start (index 0) has no
|
||||
// unit to follow, so it is charged against the first unit's gap instead.
|
||||
const pauses = new Array<number>(visible.length).fill(0);
|
||||
for (const pause of segments.pauses) {
|
||||
const index = Math.min(visible.length - 1, Math.max(0, pause.at - 1));
|
||||
if (visible.length > 0) pauses[index] += pause.ms;
|
||||
}
|
||||
const explicitTotal = pauses.reduce((sum, ms) => sum + ms, 0);
|
||||
|
||||
if (visible.length === 0) {
|
||||
return { arrival: [], total: explicitTotal, ticks: [], text: visible, pauses, explicitTotal };
|
||||
}
|
||||
|
||||
const arrival: number[] = [];
|
||||
let cursor = 0;
|
||||
for (let i = 0; i < visible.length; i += 1) {
|
||||
arrival.push(cursor);
|
||||
cursor += BASE_UNIT_MS + pauseAfter(visible, i, profile);
|
||||
cursor += profile.baseMs + pauseAfter(visible, i, profile) + pauses[i];
|
||||
}
|
||||
// The last unit's own cost is what finishes the line; its trailing pause is
|
||||
// dropped so the reveal never sits on a complete line waiting for nothing.
|
||||
const total = arrival[arrival.length - 1] + BASE_UNIT_MS;
|
||||
// The last unit's own cost is what finishes the line; its trailing punctuation
|
||||
// pause is dropped so the reveal never sits on a complete line waiting for
|
||||
// nothing. An authored pause there is kept: that is a deliberate beat.
|
||||
const total = arrival[arrival.length - 1] + profile.baseMs + pauses[pauses.length - 1];
|
||||
|
||||
const random = seededRandom(hashText(visible));
|
||||
const ticks: number[] = [];
|
||||
|
|
@ -161,7 +214,7 @@ export function buildRevealSchedule(
|
|||
nextTick = arrival[i] + TICK_MIN_GAP + random() * (TICK_MAX_GAP - TICK_MIN_GAP);
|
||||
}
|
||||
|
||||
return { arrival, total, ticks, text: visible };
|
||||
return { arrival, total, ticks, text: visible, pauses, explicitTotal };
|
||||
}
|
||||
|
||||
export interface ScaledSchedule {
|
||||
|
|
@ -180,15 +233,50 @@ export interface ScaledSchedule {
|
|||
*/
|
||||
export function scaleSchedule(schedule: RevealSchedule, targetMs: number): ScaledSchedule {
|
||||
const target = Math.max(0, targetMs);
|
||||
if (schedule.total <= 0) return { arrivalMs: [], tickMs: [], durationMs: target };
|
||||
const factor = target / schedule.total;
|
||||
if (schedule.total <= 0) {
|
||||
// A line that is nothing but pauses still lasts as long as they do.
|
||||
return { arrivalMs: [], tickMs: [], durationMs: Math.max(target, schedule.explicitTotal) };
|
||||
}
|
||||
// Authored pauses are absolute: only the typed part stretches or shrinks to
|
||||
// fit. A 1.2s beat stays 1.2s whether the line is silent or matched to a clip.
|
||||
const baseTotal = Math.max(1, schedule.total - schedule.explicitTotal);
|
||||
const baseTarget = Math.max(0, target - schedule.explicitTotal);
|
||||
const factor = baseTarget / baseTotal;
|
||||
// `arrival` already contains the authored pauses, so strip them before
|
||||
// scaling and put them back untouched afterwards.
|
||||
let pausedBefore = 0;
|
||||
const arrivalMs = schedule.arrival.map((value, index) => {
|
||||
const scaled = (value - pausedBefore) * factor + pausedBefore;
|
||||
pausedBefore += schedule.pauses[index] ?? 0;
|
||||
return scaled;
|
||||
});
|
||||
const durationMs = Math.max(target, schedule.explicitTotal);
|
||||
return {
|
||||
arrivalMs: schedule.arrival.map((value) => value * factor),
|
||||
arrivalMs,
|
||||
tickMs: schedule.ticks.map((value) => value * factor),
|
||||
durationMs: target,
|
||||
durationMs,
|
||||
};
|
||||
}
|
||||
|
||||
/** Longest a silent line may take. A safety rail for a wall of text, not a pace:
|
||||
* past this a line is compressed, and compression is what made long lines read
|
||||
* as if the typing had sped up. */
|
||||
export const MAX_LINE_MS = 20_000;
|
||||
/** Floor for a very short line, so "Yes." is not a single frame. */
|
||||
export const MIN_LINE_MS = 500;
|
||||
|
||||
/**
|
||||
* How long one line should take. A recorded clip sets the target so text and
|
||||
* speech stay together; otherwise the schedule's own total is used, never
|
||||
* compressed below the base pace. An authored pause outlasts a short clip.
|
||||
*/
|
||||
export function lineDurationMs(schedule: RevealSchedule, voicedMs?: number | null): number {
|
||||
if (voicedMs !== null && voicedMs !== undefined && voicedMs > 0) {
|
||||
return Math.max(voicedMs, schedule.explicitTotal);
|
||||
}
|
||||
return Math.min(MAX_LINE_MS, Math.max(MIN_LINE_MS, schedule.total));
|
||||
}
|
||||
|
||||
/** How many units have arrived by `elapsedMs`. Counted with the same comparison
|
||||
* the reveal loop uses, so "finished" and "how much is shown" cannot disagree. */
|
||||
export function shownAt(arrivalMs: readonly number[], elapsedMs: number): number {
|
||||
|
|
|
|||
|
|
@ -98,6 +98,20 @@ export function previewEffectLines(effect: NpcDialogueEffect | undefined): strin
|
|||
return [`Would write an event: ${effect.message || "(empty)"}`];
|
||||
case "reward":
|
||||
return [`Would reward the player: ${effect.message || "(no detail)"}`];
|
||||
case "poll": {
|
||||
const poll = effect.poll;
|
||||
const options = (poll?.options ?? []).filter((option) => option.label?.trim());
|
||||
const hours = poll?.durationHours ?? 24;
|
||||
const audience = poll?.eligibleRoleIds?.length ? "a role-gated" : "a unit-wide";
|
||||
return [
|
||||
`Would open ${audience} poll: ${poll?.title || "(untitled)"}`,
|
||||
`${options.length} option${options.length === 1 ? "" : "s"}, open ${hours}h, ` +
|
||||
`${poll?.multiSelect ? "multiple answers" : "one answer"}, ${poll?.anonymity ?? "public"}`,
|
||||
poll?.resultFlag
|
||||
? `Would write flag ${poll.resultFlag} when it resolves`
|
||||
: "No result flag configured",
|
||||
];
|
||||
}
|
||||
default:
|
||||
return [`Would run an effect (${String((effect as { type?: unknown }).type)})`];
|
||||
}
|
||||
|
|
|
|||
20
src/lib/polls/realtime.ts
Normal file
20
src/lib/polls/realtime.ts
Normal file
|
|
@ -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<void> {
|
||||
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.
|
||||
}
|
||||
}
|
||||
694
src/lib/polls/service.ts
Normal file
694
src/lib/polls/service.ts
Normal file
|
|
@ -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<string>();
|
||||
|
||||
(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<PollLaunchResult> {
|
||||
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<PollVoteRow[]> {
|
||||
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<Map<number, number[]>> {
|
||||
const ids = [...new Set(userIds)].filter((id) => Number.isFinite(id));
|
||||
const map = new Map<number, number[]>();
|
||||
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<number, number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<PollTallySnapshot> {
|
||||
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<PollOutcome>;
|
||||
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<Poll> {
|
||||
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<Poll> {
|
||||
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<Poll> {
|
||||
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<Poll> {
|
||||
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<Poll> {
|
||||
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<CastPollVoteResult> {
|
||||
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 };
|
||||
}
|
||||
207
src/lib/polls/surface.ts
Normal file
207
src/lib/polls/surface.ts
Normal file
|
|
@ -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<PollView> {
|
||||
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<string, string[]>();
|
||||
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<PollView[]> {
|
||||
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));
|
||||
}
|
||||
226
src/lib/polls/tally.ts
Normal file
226
src/lib/polls/tally.ts
Normal file
|
|
@ -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<string, PollOptionCount>;
|
||||
|
||||
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<number>;
|
||||
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<number, readonly number[]>;
|
||||
tiers: readonly PollWeightTier[];
|
||||
defaultWeight?: number;
|
||||
}): Map<number, number> {
|
||||
const weights = new Map<number, number>();
|
||||
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<number, number>;
|
||||
}): PollTally {
|
||||
const counts: PollCounts = {};
|
||||
for (const option of input.options) counts[option.key] = { raw: 0, weighted: 0 };
|
||||
|
||||
const scaled: Record<string, number> = {};
|
||||
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] };
|
||||
}
|
||||
48218
src/migrations/20261201_175529_add_polls.json
Normal file
48218
src/migrations/20261201_175529_add_polls.json
Normal file
File diff suppressed because it is too large
Load diff
188
src/migrations/20261201_175529_add_polls.ts
Normal file
188
src/migrations/20261201_175529_add_polls.ts
Normal file
File diff suppressed because one or more lines are too long
48252
src/migrations/20261201_180344_add_npc_dialogue_typing_pace.json
Normal file
48252
src/migrations/20261201_180344_add_npc_dialogue_typing_pace.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,17 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
CREATE TYPE "public"."enum_npc_dialogue_settings_presentation_pacing" AS ENUM('subtle', 'natural', 'pronounced');
|
||||
CREATE TYPE "public"."enum__npc_dialogue_settings_v_version_presentation_pacing" AS ENUM('subtle', 'natural', 'pronounced');
|
||||
ALTER TABLE "npc_dialogue_settings" ADD COLUMN "presentation_pacing" "enum_npc_dialogue_settings_presentation_pacing" DEFAULT 'natural';
|
||||
ALTER TABLE "_npc_dialogue_settings_v" ADD COLUMN "version_presentation_pacing" "enum__npc_dialogue_settings_v_version_presentation_pacing" DEFAULT 'natural';`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogue_settings" DROP COLUMN "presentation_pacing";
|
||||
ALTER TABLE "_npc_dialogue_settings_v" DROP COLUMN "version_presentation_pacing";
|
||||
DROP TYPE "public"."enum_npc_dialogue_settings_presentation_pacing";
|
||||
DROP TYPE "public"."enum__npc_dialogue_settings_v_version_presentation_pacing";`)
|
||||
}
|
||||
48253
src/migrations/20261201_183001_add_polls_event_target.json
Normal file
48253
src/migrations/20261201_183001_add_polls_event_target.json
Normal file
File diff suppressed because it is too large
Load diff
14
src/migrations/20261201_183001_add_polls_event_target.ts
Normal file
14
src/migrations/20261201_183001_add_polls_event_target.ts
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TYPE "public"."enum_game_event_logs_target_collection" ADD VALUE 'polls';`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE text;
|
||||
DROP TYPE "public"."enum_game_event_logs_target_collection";
|
||||
CREATE TYPE "public"."enum_game_event_logs_target_collection" AS ENUM('game-structures', 'game-vehicles', 'game-npcs', 'npc-staffing', 'structures', 'resources', 'assets', 'vehicles', 'factions', 'missions', 'campaigns', 'users', 'technologies', 'tech-researches', 'tech-ballots', 'maps', 'shipments', 'bank-accounts', 'bank-transactions', 'ledger-entries', 'locker-storages', 'loadouts', 'market-listings', 'market-negotiations', 'market-state', 'evaluations', 'tickets', 'wiki-pages', 'wiki-revisions', 'wiki-templates', 'form-submissions', 'mission-map-markers', 'map-objectives', 'contribution-entries', 'game-servers', 'assignment-transfers', 'voice-scripts', 'voice-submissions', 'story-beats', 'journals', 'awards', 'story-beat-states', 'custom-minefields', 'custom-minefield-scores', 'custom-radio-tests', 'custom-radio-test-scores', 'ribbon-submissions', 'promotion-nominations', 'leadership-transfers', 'player-flags', 'reinforcement-pools');
|
||||
ALTER TABLE "game_event_logs" ALTER COLUMN "target_collection" SET DATA TYPE "public"."enum_game_event_logs_target_collection" USING "target_collection"::"public"."enum_game_event_logs_target_collection";`)
|
||||
}
|
||||
|
|
@ -171,6 +171,9 @@ import * as migration_20261124_223724_add_conversation_typewriter_setting from '
|
|||
import * as migration_20261124_225400_add_conversation_voice_preference from './20261124_225400_add_conversation_voice_preference';
|
||||
import * as migration_20261124_232253_add_npc_dialogue_testing_flag from './20261124_232253_add_npc_dialogue_testing_flag';
|
||||
import * as migration_20261125_000236_add_dialogue_typing_sound_preference from './20261125_000236_add_dialogue_typing_sound_preference';
|
||||
import * as migration_20261201_175529_add_polls from './20261201_175529_add_polls';
|
||||
import * as migration_20261201_180344_add_npc_dialogue_typing_pace from './20261201_180344_add_npc_dialogue_typing_pace';
|
||||
import * as migration_20261201_183001_add_polls_event_target from './20261201_183001_add_polls_event_target';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -1036,6 +1039,21 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261125_000236_add_dialogue_typing_sound_preference.up,
|
||||
down: migration_20261125_000236_add_dialogue_typing_sound_preference.down,
|
||||
name: '20261125_000236_add_dialogue_typing_sound_preference'
|
||||
name: '20261125_000236_add_dialogue_typing_sound_preference',
|
||||
},
|
||||
{
|
||||
up: migration_20261201_175529_add_polls.up,
|
||||
down: migration_20261201_175529_add_polls.down,
|
||||
name: '20261201_175529_add_polls',
|
||||
},
|
||||
{
|
||||
up: migration_20261201_180344_add_npc_dialogue_typing_pace.up,
|
||||
down: migration_20261201_180344_add_npc_dialogue_typing_pace.down,
|
||||
name: '20261201_180344_add_npc_dialogue_typing_pace',
|
||||
},
|
||||
{
|
||||
up: migration_20261201_183001_add_polls_event_target.up,
|
||||
down: migration_20261201_183001_add_polls_event_target.down,
|
||||
name: '20261201_183001_add_polls_event_target'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -83,6 +83,8 @@ export interface Config {
|
|||
'game-event-logs': GameEventLog;
|
||||
'structure-rooms': StructureRoom;
|
||||
'interior-jobs': InteriorJob;
|
||||
polls: Poll;
|
||||
'poll-votes': PollVote;
|
||||
users: User;
|
||||
roles: Role;
|
||||
ranks: Rank;
|
||||
|
|
@ -202,6 +204,8 @@ export interface Config {
|
|||
'game-event-logs': GameEventLogsSelect<false> | GameEventLogsSelect<true>;
|
||||
'structure-rooms': StructureRoomsSelect<false> | StructureRoomsSelect<true>;
|
||||
'interior-jobs': InteriorJobsSelect<false> | InteriorJobsSelect<true>;
|
||||
polls: PollsSelect<false> | PollsSelect<true>;
|
||||
'poll-votes': PollVotesSelect<false> | PollVotesSelect<true>;
|
||||
users: UsersSelect<false> | UsersSelect<true>;
|
||||
roles: RolesSelect<false> | RolesSelect<true>;
|
||||
ranks: RanksSelect<false> | RanksSelect<true>;
|
||||
|
|
@ -1024,6 +1028,11 @@ export interface Role {
|
|||
| 'form-submissions:delete'
|
||||
| 'admin:forms:manage'
|
||||
| 'admin:form-submissions:manage'
|
||||
| 'polls:create'
|
||||
| 'polls:read'
|
||||
| 'polls:update'
|
||||
| 'polls:delete'
|
||||
| 'admin:polls:manage'
|
||||
| 'contribution-entries:read'
|
||||
| 'contribution-entries:create'
|
||||
| 'contribution-entries:update'
|
||||
|
|
@ -3602,6 +3611,11 @@ export interface GameEventLog {
|
|||
| 'form-submissions:delete'
|
||||
| 'admin:forms:manage'
|
||||
| 'admin:form-submissions:manage'
|
||||
| 'polls:create'
|
||||
| 'polls:read'
|
||||
| 'polls:update'
|
||||
| 'polls:delete'
|
||||
| 'admin:polls:manage'
|
||||
| 'contribution-entries:read'
|
||||
| 'contribution-entries:create'
|
||||
| 'contribution-entries:update'
|
||||
|
|
@ -3714,6 +3728,7 @@ export interface GameEventLog {
|
|||
| 'leadership-transfers'
|
||||
| 'player-flags'
|
||||
| 'reinforcement-pools'
|
||||
| 'polls'
|
||||
)
|
||||
| null;
|
||||
targetId?: number | null;
|
||||
|
|
@ -3856,6 +3871,146 @@ export interface InteriorJob {
|
|||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Unit-wide polls raised by NPC conversations. Read-only here: they are created by the dialogue effect and resolved by the poll service.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "polls".
|
||||
*/
|
||||
export interface Poll {
|
||||
id: number;
|
||||
/**
|
||||
* The question, as it appears on both surfaces.
|
||||
*/
|
||||
title: string;
|
||||
/**
|
||||
* Optional context under the question. Plain text with **bold** and line breaks; both surfaces render it the same way.
|
||||
*/
|
||||
body?: string | null;
|
||||
/**
|
||||
* The answers on offer. Keys are stable and never shown.
|
||||
*/
|
||||
options: {
|
||||
/**
|
||||
* Stable slug, e.g. 'accept'. Votes reference this, never the row.
|
||||
*/
|
||||
key: string;
|
||||
label: string;
|
||||
/**
|
||||
* Optional emoji shown before the label on both surfaces.
|
||||
*/
|
||||
emoji?: string | null;
|
||||
description?: string | null;
|
||||
id?: string | null;
|
||||
}[];
|
||||
status: 'open' | 'pending_decision' | 'closed';
|
||||
/**
|
||||
* When voting stops. Voting is also refused past this moment by the service.
|
||||
*/
|
||||
closesAt: string;
|
||||
/**
|
||||
* Allow more than one answer per voter.
|
||||
*/
|
||||
multiSelect?: boolean | null;
|
||||
/**
|
||||
* Anonymous hides voter identities from everyone except superusers. Counts are always visible.
|
||||
*/
|
||||
anonymity: 'public' | 'anonymous';
|
||||
/**
|
||||
* Leave empty for the whole unit. When set, only holders of these roles may vote.
|
||||
*/
|
||||
eligibleRoles?: (number | Role)[] | null;
|
||||
/**
|
||||
* Voting weight for everyone without a matching tier. Tiers pick the HIGHEST matching multiplier, never a sum.
|
||||
*/
|
||||
defaultWeight?: number | null;
|
||||
/**
|
||||
* Optional role-based weight, e.g. Logistics 1.5. Resolved at close, from the roles each voter holds then.
|
||||
*/
|
||||
weightTiers?:
|
||||
| {
|
||||
label: string;
|
||||
roles: (number | Role)[];
|
||||
/**
|
||||
* 1.5 means this role's vote counts 50% more.
|
||||
*/
|
||||
multiplier: number;
|
||||
id?: string | null;
|
||||
}[]
|
||||
| null;
|
||||
/**
|
||||
* Optional global player-flag key written with the winning option's key when the poll resolves. Must already exist in Player Flags.
|
||||
*/
|
||||
resultFlag?: string | null;
|
||||
/**
|
||||
* How long a superuser has to break a tie before a random tied option is chosen.
|
||||
*/
|
||||
tieGraceHours?: number | null;
|
||||
/**
|
||||
* `<dialogueId>:<nodeId>`. Makes the dialogue trigger idempotent.
|
||||
*/
|
||||
sourceKey: string;
|
||||
dialogue?: (number | null) | NpcDialogue;
|
||||
nodeId?: string | null;
|
||||
/**
|
||||
* The player who reached the node first. Their vote is the first tie-breaker.
|
||||
*/
|
||||
initiatedBy?: (number | null) | User;
|
||||
openedAt?: string | null;
|
||||
/**
|
||||
* When voting stopped and the tally froze.
|
||||
*/
|
||||
closedAt?: string | null;
|
||||
/**
|
||||
* A tied poll: when a random tied option wins if no superuser decides.
|
||||
*/
|
||||
decisionDeadline?: string | null;
|
||||
decidedBy?: (number | null) | User;
|
||||
resolvedAt?: string | null;
|
||||
winnerKey?: string | null;
|
||||
resolutionMethod?: ('votes' | 'initiator' | 'superuser' | 'random' | 'no_votes') | null;
|
||||
/**
|
||||
* The tally frozen at close: per-option raw and weighted counts, top options, and the resolution.
|
||||
*/
|
||||
outcome?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
discordMessageId?: string | null;
|
||||
discordChannelId?: string | null;
|
||||
discordPostedAt?: string | null;
|
||||
/**
|
||||
* Content hash of the last message the bot rendered; drift triggers an edit.
|
||||
*/
|
||||
discordPollHash?: string | null;
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* Ballots. Readable only by the superuser tier, which is what keeps anonymous polls anonymous for everyone else.
|
||||
*
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "poll-votes".
|
||||
*/
|
||||
export interface PollVote {
|
||||
id: number;
|
||||
poll: number | Poll;
|
||||
user: number | User;
|
||||
/**
|
||||
* The option keys this voter chose. One row on a single-answer poll; the service dedupes and rejects keys the poll does not carry.
|
||||
*/
|
||||
answers: {
|
||||
key: string;
|
||||
id?: string | null;
|
||||
}[];
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "ranks".
|
||||
|
|
@ -7934,6 +8089,42 @@ export interface PayloadMcpApiKey {
|
|||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
polls?: {
|
||||
/**
|
||||
* Allow clients to find polls.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create polls.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update polls.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete polls.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
pollVotes?: {
|
||||
/**
|
||||
* Allow clients to find poll-votes.
|
||||
*/
|
||||
find?: boolean | null;
|
||||
/**
|
||||
* Allow clients to create poll-votes.
|
||||
*/
|
||||
create?: boolean | null;
|
||||
/**
|
||||
* Allow clients to update poll-votes.
|
||||
*/
|
||||
update?: boolean | null;
|
||||
/**
|
||||
* Allow clients to delete poll-votes.
|
||||
*/
|
||||
delete?: boolean | null;
|
||||
};
|
||||
users?: {
|
||||
/**
|
||||
* Allow clients to find users.
|
||||
|
|
@ -9573,6 +9764,14 @@ export interface PayloadLockedDocument {
|
|||
relationTo: 'interior-jobs';
|
||||
value: number | InteriorJob;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'polls';
|
||||
value: number | Poll;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'poll-votes';
|
||||
value: number | PollVote;
|
||||
} | null)
|
||||
| ({
|
||||
relationTo: 'users';
|
||||
value: number | User;
|
||||
|
|
@ -10467,6 +10666,73 @@ export interface InteriorJobsSelect<T extends boolean = true> {
|
|||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "polls_select".
|
||||
*/
|
||||
export interface PollsSelect<T extends boolean = true> {
|
||||
title?: T;
|
||||
body?: T;
|
||||
options?:
|
||||
| T
|
||||
| {
|
||||
key?: T;
|
||||
label?: T;
|
||||
emoji?: T;
|
||||
description?: T;
|
||||
id?: T;
|
||||
};
|
||||
status?: T;
|
||||
closesAt?: T;
|
||||
multiSelect?: T;
|
||||
anonymity?: T;
|
||||
eligibleRoles?: T;
|
||||
defaultWeight?: T;
|
||||
weightTiers?:
|
||||
| T
|
||||
| {
|
||||
label?: T;
|
||||
roles?: T;
|
||||
multiplier?: T;
|
||||
id?: T;
|
||||
};
|
||||
resultFlag?: T;
|
||||
tieGraceHours?: T;
|
||||
sourceKey?: T;
|
||||
dialogue?: T;
|
||||
nodeId?: T;
|
||||
initiatedBy?: T;
|
||||
openedAt?: T;
|
||||
closedAt?: T;
|
||||
decisionDeadline?: T;
|
||||
decidedBy?: T;
|
||||
resolvedAt?: T;
|
||||
winnerKey?: T;
|
||||
resolutionMethod?: T;
|
||||
outcome?: T;
|
||||
discordMessageId?: T;
|
||||
discordChannelId?: T;
|
||||
discordPostedAt?: T;
|
||||
discordPollHash?: T;
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "poll-votes_select".
|
||||
*/
|
||||
export interface PollVotesSelect<T extends boolean = true> {
|
||||
poll?: T;
|
||||
user?: T;
|
||||
answers?:
|
||||
| T
|
||||
| {
|
||||
key?: T;
|
||||
id?: T;
|
||||
};
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
/**
|
||||
* This interface was referenced by `Config`'s JSON-Schema
|
||||
* via the `definition` "users_select".
|
||||
|
|
@ -13242,6 +13508,22 @@ export interface PayloadMcpApiKeysSelect<T extends boolean = true> {
|
|||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
polls?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
pollVotes?:
|
||||
| T
|
||||
| {
|
||||
find?: T;
|
||||
create?: T;
|
||||
update?: T;
|
||||
delete?: T;
|
||||
};
|
||||
users?:
|
||||
| T
|
||||
| {
|
||||
|
|
@ -14307,6 +14589,10 @@ export interface NpcDialogueSetting {
|
|||
* The default for everyone. Players can override it in their account preferences, and a player whose device asks for reduced motion never sees the animation.
|
||||
*/
|
||||
typewriterDefault?: boolean | null;
|
||||
/**
|
||||
* How fast conversation lines type out and how long the pauses at punctuation last. Applies to the next conversation opened, with no deploy. Authors can still hold a specific line with {1.2s} or {400ms}.
|
||||
*/
|
||||
pacing?: ('subtle' | 'natural' | 'pronounced') | null;
|
||||
};
|
||||
/**
|
||||
* Incremented automatically when the voice or house rules change. Recorded on each stored draft so you can tell which prompt produced it.
|
||||
|
|
@ -14476,6 +14762,7 @@ export interface NpcDialogueSettingsSelect<T extends boolean = true> {
|
|||
| T
|
||||
| {
|
||||
typewriterDefault?: T;
|
||||
pacing?: T;
|
||||
};
|
||||
revision?: T;
|
||||
updatedAt?: T;
|
||||
|
|
|
|||
|
|
@ -100,6 +100,8 @@ import { StoryBeats } from "@/collections/story/StoryBeats";
|
|||
import { Journals } from "@/collections/story/Journals";
|
||||
import { StoryBeatStates } from "@/collections/story/StoryBeatStates";
|
||||
import { Voiceovers } from "@/collections/story/Voiceovers";
|
||||
import { Polls } from "@/collections/polls/Polls";
|
||||
import { PollVotes } from "@/collections/polls/PollVotes";
|
||||
import { Shims } from "@/collections/Shims";
|
||||
import { Announcements } from "@/collections/Announcements";
|
||||
import { CustomMinefields } from "@/collections/minigames/CustomMinefields";
|
||||
|
|
@ -255,6 +257,10 @@ const collections = [
|
|||
StructureRooms,
|
||||
InteriorJobs,
|
||||
|
||||
// Polls
|
||||
Polls,
|
||||
PollVotes,
|
||||
|
||||
// Users
|
||||
Users,
|
||||
Roles,
|
||||
|
|
|
|||
|
|
@ -790,6 +790,16 @@ export const PERMISSION_GROUPS: PermissionGroup[] = [
|
|||
{ value: "admin:form-submissions:manage", label: "Manage Submissions Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Polls",
|
||||
permissions: [
|
||||
{ value: "polls:create", label: "Create" },
|
||||
{ value: "polls:read", label: "Read" },
|
||||
{ value: "polls:update", label: "Update (close a poll early)" },
|
||||
{ value: "polls:delete", label: "Delete" },
|
||||
{ value: "admin:polls:manage", label: "Manage Admin Page" },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: "Contributions",
|
||||
permissions: [
|
||||
|
|
@ -1281,6 +1291,11 @@ export const ALL_PERMISSION_VALUES = PERMISSION_GROUPS.flatMap((g) =>
|
|||
"form-submissions:delete",
|
||||
"admin:forms:manage",
|
||||
"admin:form-submissions:manage",
|
||||
"polls:create",
|
||||
"polls:read",
|
||||
"polls:update",
|
||||
"polls:delete",
|
||||
"admin:polls:manage",
|
||||
"contribution-entries:read",
|
||||
"contribution-entries:create",
|
||||
"contribution-entries:update",
|
||||
|
|
|
|||
|
|
@ -60,7 +60,8 @@ interface GameEventInput {
|
|||
| "map-objectives"
|
||||
| "contribution-entries"
|
||||
| "journals"
|
||||
| "awards";
|
||||
| "awards"
|
||||
| "polls";
|
||||
targetId?: number;
|
||||
data?: Record<string, unknown>;
|
||||
/**
|
||||
|
|
|
|||
|
|
@ -142,6 +142,11 @@ export const EventTypes = {
|
|||
// Attendance
|
||||
MissionAttendanceChange: "mission:attendance-change",
|
||||
|
||||
// Polls
|
||||
PollOpen: "poll:open",
|
||||
PollTiePending: "poll:tie-pending",
|
||||
PollClose: "poll:close",
|
||||
|
||||
// Mission role sign-ups
|
||||
MissionRoleSignup: "mission:role-signup",
|
||||
MissionRoleWithdraw: "mission:role-withdraw",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,8 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { StructuredStreamFactory } from "@/lib/ai/generate";
|
||||
import { generateStructured } from "@/lib/ai/generate";
|
||||
|
||||
/**
|
||||
* Regression: `streamObject`'s stream is lazy, so `result.object` never resolves
|
||||
|
|
@ -7,34 +10,26 @@ import { describe, expect, it, vi } from "vitest";
|
|||
* what made every NPC draft hang on "Drafting..." against OpenRouter, with the
|
||||
* provider having delivered a complete answer.
|
||||
*
|
||||
* The stub below models that laziness: `object` resolves only after the text
|
||||
* stream has been read.
|
||||
* The stub models that laziness: `object` is released by the first pull of the
|
||||
* text stream, with no timers. Reaching the object means the drain ran. It is
|
||||
* injected through the factory seam rather than by mocking `ai`, because a test
|
||||
* worker shares one module registry across files and a mock registered here is
|
||||
* ignored when another spec has already loaded the real module.
|
||||
*/
|
||||
vi.mock("ai", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("ai")>();
|
||||
const lazyStream: StructuredStreamFactory = () => {
|
||||
const holder: { release?: (value: unknown) => void } = {};
|
||||
const object = new Promise((resolve) => {
|
||||
holder.release = resolve;
|
||||
});
|
||||
return {
|
||||
...actual,
|
||||
streamObject: () => {
|
||||
let drained = false;
|
||||
return {
|
||||
textStream: (async function* () {
|
||||
drained = true;
|
||||
yield '{"nodes":[{"id":"n1"}]}';
|
||||
})(),
|
||||
object: new Promise((resolve) => {
|
||||
const timer = setInterval(() => {
|
||||
if (!drained) return;
|
||||
clearInterval(timer);
|
||||
resolve({ nodes: [{ id: "n1" }] });
|
||||
}, 5);
|
||||
}),
|
||||
finishReason: Promise.resolve("stop"),
|
||||
};
|
||||
},
|
||||
textStream: (async function* () {
|
||||
holder.release?.({ nodes: [{ id: "n1" }] });
|
||||
yield '{"nodes":[{"id":"n1"}]}';
|
||||
})(),
|
||||
object,
|
||||
finishReason: Promise.resolve("stop"),
|
||||
};
|
||||
});
|
||||
|
||||
const { generateStructured } = await import("@/lib/ai/generate");
|
||||
};
|
||||
|
||||
describe("structured generation drives the stream", () => {
|
||||
it("resolves the object instead of waiting on a lazy stream", async () => {
|
||||
|
|
@ -50,6 +45,7 @@ describe("structured generation drives the stream", () => {
|
|||
structuredMode: "json_schema",
|
||||
sendReasoningOff: false,
|
||||
},
|
||||
streamFactory: lazyStream,
|
||||
});
|
||||
|
||||
expect(result.object.nodes).toHaveLength(1);
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
// @vitest-environment node
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { MAX_PAUSE_MS, visibleSegments } from "@/lib/npc-dialogue/DialogueText";
|
||||
import {
|
||||
BASE_UNIT_MS,
|
||||
DEFAULT_PACING_PRESET,
|
||||
MAX_LINE_MS,
|
||||
MIN_LINE_MS,
|
||||
PACING_PRESETS,
|
||||
beatMs,
|
||||
buildRevealSchedule,
|
||||
lineDurationMs,
|
||||
scaleSchedule,
|
||||
shownAt,
|
||||
} from "@/lib/npc-dialogue/pacing";
|
||||
|
|
@ -145,7 +149,7 @@ describe("reveal pacing", () => {
|
|||
|
||||
it("has nothing to schedule for an empty line", () => {
|
||||
const empty = buildRevealSchedule("");
|
||||
expect(empty).toEqual({ arrival: [], total: 0, ticks: [], text: "" });
|
||||
expect(empty).toMatchObject({ arrival: [], total: 0, ticks: [], text: "" });
|
||||
expect(scaleSchedule(empty, 900)).toEqual({ arrivalMs: [], tickMs: [], durationMs: 900 });
|
||||
});
|
||||
|
||||
|
|
@ -155,14 +159,79 @@ describe("reveal pacing", () => {
|
|||
const text = "Hold, trooper.";
|
||||
const comma = text.indexOf(",");
|
||||
|
||||
// Each preset moves speed and pauses together, so a character and the pause
|
||||
// after a comma both cost its own base.
|
||||
expect(gapAfter(buildRevealSchedule(text, "subtle").arrival, comma)).toBe(
|
||||
BASE_UNIT_MS + subtle.clauseMs,
|
||||
subtle.baseMs + subtle.clauseMs,
|
||||
);
|
||||
expect(gapAfter(buildRevealSchedule(text, "pronounced").arrival, comma)).toBe(
|
||||
BASE_UNIT_MS + pronounced.clauseMs,
|
||||
pronounced.baseMs + pronounced.clauseMs,
|
||||
);
|
||||
expect(subtle.baseMs).toBeLessThan(PACING_PRESETS.natural.baseMs);
|
||||
expect(PACING_PRESETS.natural.baseMs).toBeLessThan(pronounced.baseMs);
|
||||
expect(BASE_UNIT_MS).toBe(PACING_PRESETS.natural.baseMs);
|
||||
expect(beatMs("subtle")).toBeLessThan(beatMs("natural"));
|
||||
expect(beatMs("natural")).toBeLessThan(beatMs("pronounced"));
|
||||
expect(beatMs("unknown" as never)).toBe(beatMs("natural"));
|
||||
});
|
||||
});
|
||||
|
||||
describe("authored pauses", () => {
|
||||
it("keeps the marker out of the line and reports where it sat", () => {
|
||||
const segments = visibleSegments("Hold{1.2s} there.");
|
||||
expect(segments.text).toBe("Hold there.");
|
||||
expect(segments.pauses).toEqual([{ at: 4, ms: 1200 }]);
|
||||
});
|
||||
|
||||
it("reads both units, and refuses nonsense", () => {
|
||||
expect(visibleSegments("a{400ms}b").pauses).toEqual([{ at: 1, ms: 400 }]);
|
||||
expect(visibleSegments("a{2S}b").pauses).toEqual([{ at: 1, ms: 2000 }]);
|
||||
// Not a pause token: it stays literal text, like any unknown brace run.
|
||||
expect(visibleSegments("a{1.2x}b").text).toBe("a{1.2x}b");
|
||||
expect(visibleSegments("a{1.2x}b").pauses).toEqual([]);
|
||||
// Clamped, so a typo cannot park a player for minutes.
|
||||
expect(visibleSegments("a{90s}b").pauses).toEqual([{ at: 1, ms: MAX_PAUSE_MS }]);
|
||||
});
|
||||
|
||||
it("costs exactly the authored time, on top of the base pace", () => {
|
||||
const plain = buildRevealSchedule("ab");
|
||||
const paused = buildRevealSchedule("a{1.2s}b");
|
||||
expect(paused.text).toBe("ab");
|
||||
expect(paused.explicitTotal).toBe(1200);
|
||||
expect(paused.pauses).toEqual([1200, 0]);
|
||||
expect(gapAfter(paused.arrival, 0)).toBe(BASE_UNIT_MS + 1200);
|
||||
expect(paused.total - plain.total).toBe(1200);
|
||||
});
|
||||
|
||||
it("stays absolute when the line is stretched or squeezed to fit", () => {
|
||||
const schedule = buildRevealSchedule("a{1.2s}bcd");
|
||||
const stretched = scaleSchedule(schedule, schedule.total * 3);
|
||||
const squeezed = scaleSchedule(schedule, 2000);
|
||||
// Two neighbouring units across the pause: the extra 1.2s is still there.
|
||||
const gap = (arrival: readonly number[]) => arrival[1] - arrival[0];
|
||||
expect(gap(stretched.arrivalMs) - BASE_UNIT_MS * 3).toBeGreaterThanOrEqual(1200);
|
||||
expect(gap(squeezed.arrivalMs)).toBeGreaterThanOrEqual(1200);
|
||||
});
|
||||
});
|
||||
|
||||
describe("line duration", () => {
|
||||
it("does not compress a long line below the base pace", () => {
|
||||
// 400 characters at the old 3s ceiling ran at 7.5ms per character.
|
||||
const schedule = buildRevealSchedule("word ".repeat(80).trim());
|
||||
const duration = lineDurationMs(schedule);
|
||||
expect(duration).toBe(schedule.total);
|
||||
expect(duration / schedule.text.length).toBeGreaterThanOrEqual(BASE_UNIT_MS - 1);
|
||||
});
|
||||
|
||||
it("still has a ceiling, and a floor for a very short line", () => {
|
||||
const wall = buildRevealSchedule("word ".repeat(400).trim());
|
||||
expect(lineDurationMs(wall)).toBe(MAX_LINE_MS);
|
||||
expect(lineDurationMs(buildRevealSchedule("Hi."))).toBeGreaterThanOrEqual(MIN_LINE_MS);
|
||||
});
|
||||
|
||||
it("lets a clip set the target but never cuts an authored pause", () => {
|
||||
const schedule = buildRevealSchedule("a{1.2s}bcd");
|
||||
expect(lineDurationMs(schedule, 4000)).toBe(4000);
|
||||
expect(lineDurationMs(schedule, 600)).toBeGreaterThanOrEqual(1200);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,10 @@ beforeAll(async () => {
|
|||
const update = (data: {
|
||||
voice?: string | null;
|
||||
extraRules?: string | null;
|
||||
presentation?: { typewriterDefault?: boolean | null };
|
||||
presentation?: {
|
||||
typewriterDefault?: boolean | null;
|
||||
pacing?: "subtle" | "natural" | "pronounced" | null;
|
||||
};
|
||||
}) =>
|
||||
payload.updateGlobal({
|
||||
slug: "npc-dialogue-settings",
|
||||
|
|
@ -109,6 +112,7 @@ describe("npc-dialogue-settings global", () => {
|
|||
extraRules: null,
|
||||
revision: null,
|
||||
typewriterDefault: true,
|
||||
pacing: "natural",
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -127,4 +131,24 @@ describe("npc-dialogue-settings global", () => {
|
|||
expect(on.revision).toBe(revision);
|
||||
expect((await loadDialogueSettings(payload)).typewriterDefault).toBe(true);
|
||||
});
|
||||
|
||||
it("carries the typing pace, and falls back to natural for a value it does not know", async () => {
|
||||
const voice = unique("Unchanged by pace.");
|
||||
const before = await update({ voice, presentation: { pacing: "pronounced" } });
|
||||
expect((await loadDialogueSettings(payload)).pacing).toBe("pronounced");
|
||||
// Pace is presentation, not prompt copy: stored drafts are unaffected.
|
||||
expect(before.revision).toBe((await loadDialogueSettings(payload)).revision);
|
||||
|
||||
// A row written with a value this build does not know (an older or newer
|
||||
// admin) must still render at a real pace rather than none.
|
||||
const stale = await loadDialogueSettings({
|
||||
findGlobal: async () => ({ presentation: { pacing: "molasses" } }),
|
||||
logger: { warn: () => undefined },
|
||||
} as unknown as Payload);
|
||||
expect(stale.pacing).toBe("natural");
|
||||
|
||||
await update({ presentation: { pacing: "subtle" } });
|
||||
expect((await loadDialogueSettings(payload)).pacing).toBe("subtle");
|
||||
await update({ presentation: { pacing: "natural" } });
|
||||
});
|
||||
});
|
||||
|
|
|
|||
218
tests/int/polls-embed.int.spec.ts
Normal file
218
tests/int/polls-embed.int.spec.ts
Normal file
|
|
@ -0,0 +1,218 @@
|
|||
import { beforeAll, describe, expect, it } from "vitest";
|
||||
|
||||
// The bot config validates its environment at import time, the same way
|
||||
// `bot-commands.int.spec.ts` handles it.
|
||||
process.env.DISCORD_TOKEN ||= "poll-embed-test-token";
|
||||
process.env.DISCORD_GUILD_ID ||= "1";
|
||||
process.env.APP_URL ||= "https://polaris.test";
|
||||
|
||||
import type { Poll } from "@/payload-types";
|
||||
import type { PollTally } from "@/lib/polls/tally";
|
||||
|
||||
type PollEmbeds = typeof import("@/bot/services/pollEmbeds");
|
||||
let mod: PollEmbeds;
|
||||
|
||||
beforeAll(async () => {
|
||||
mod = await import("@/bot/services/pollEmbeds");
|
||||
});
|
||||
|
||||
const HOUR = 3_600_000;
|
||||
|
||||
const poll = (over: Partial<Poll> = {}): Poll =>
|
||||
({
|
||||
id: 42,
|
||||
title: "Should the Task Force work with the Vanguard?",
|
||||
body: "They want a shared comms channel and a monthly tithe.",
|
||||
options: [
|
||||
{ key: "accept", label: "Work with the Vanguard", emoji: "🤝", description: null, id: "a" },
|
||||
{ key: "decline", label: "Stay independent", emoji: null, description: null, id: "b" },
|
||||
],
|
||||
status: "open",
|
||||
closesAt: new Date(Date.now() + 6 * HOUR).toISOString(),
|
||||
multiSelect: false,
|
||||
anonymity: "public",
|
||||
defaultWeight: 1,
|
||||
weightTiers: [],
|
||||
tieGraceHours: 24,
|
||||
sourceKey: "1:node",
|
||||
openedAt: new Date().toISOString(),
|
||||
initiatedBy: 1,
|
||||
eligibleRoles: [],
|
||||
updatedAt: "",
|
||||
createdAt: "",
|
||||
...over,
|
||||
}) as unknown as Poll;
|
||||
|
||||
const tally = (over: Partial<PollTally> = {}): PollTally => ({
|
||||
counts: {
|
||||
accept: { raw: 2, weighted: 3 },
|
||||
decline: { raw: 1, weighted: 1.5 },
|
||||
},
|
||||
totalVotes: 3,
|
||||
totalWeight: 4.5,
|
||||
topScore: 3,
|
||||
topKeys: ["accept"],
|
||||
...over,
|
||||
});
|
||||
|
||||
const render = (input: Partial<Parameters<PollEmbeds["renderPollEmbed"]>[0]> = {}) =>
|
||||
mod
|
||||
.renderPollEmbed({
|
||||
poll: poll(),
|
||||
tally: tally(),
|
||||
votersByOption: new Map(),
|
||||
...input,
|
||||
})
|
||||
.toJSON();
|
||||
|
||||
describe("Poll embed", () => {
|
||||
it("names the question, both answers and the weighted tally", () => {
|
||||
const embed = render();
|
||||
|
||||
expect(embed.title).toBe("Should the Task Force work with the Vanguard?");
|
||||
// The host comes from APP_URL, so assert the path the link must carry.
|
||||
expect(embed.url).toMatch(/\/polls\/42$/);
|
||||
const fields = embed.fields ?? [];
|
||||
expect(fields[0].name).toContain("Work with the Vanguard");
|
||||
// Weighted differs from raw, so both are shown.
|
||||
expect(fields[0].name).toContain("2");
|
||||
expect(fields[0].name).toContain("3");
|
||||
expect(fields[1].name).toContain("1.5");
|
||||
expect(embed.description).toContain("3 voters");
|
||||
expect(embed.description).toContain("One answer");
|
||||
expect(embed.description).toContain("Public");
|
||||
});
|
||||
|
||||
it("shows voter names on a public poll", () => {
|
||||
const embed = render({
|
||||
votersByOption: new Map([["accept", ["Alpha", "Bravo"]]]),
|
||||
});
|
||||
expect(embed.fields?.[0].value).toContain("Alpha, Bravo");
|
||||
});
|
||||
|
||||
it("never shows voter names on an anonymous poll", () => {
|
||||
const embed = render({
|
||||
poll: poll({ anonymity: "anonymous" }),
|
||||
votersByOption: new Map([["accept", ["Alpha", "Bravo"]]]),
|
||||
});
|
||||
|
||||
const body = JSON.stringify(embed);
|
||||
expect(body).not.toContain("Alpha");
|
||||
expect(body).not.toContain("Bravo");
|
||||
expect(embed.description).toContain("Anonymous");
|
||||
// Counts still render.
|
||||
expect(embed.fields?.[0].name).toContain("Work with the Vanguard");
|
||||
});
|
||||
|
||||
it("announces the winner once closed", () => {
|
||||
const embed = render({
|
||||
poll: poll({
|
||||
status: "closed",
|
||||
winnerKey: "decline",
|
||||
resolutionMethod: "initiator",
|
||||
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
||||
}),
|
||||
});
|
||||
|
||||
expect(embed.description).toContain("Closed");
|
||||
expect(embed.description).toContain("Stay independent");
|
||||
});
|
||||
|
||||
it("reports no decision when a closed poll never resolved", () => {
|
||||
const embed = render({
|
||||
poll: poll({
|
||||
status: "closed",
|
||||
winnerKey: null,
|
||||
resolutionMethod: "no_votes",
|
||||
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
||||
}),
|
||||
});
|
||||
expect(embed.description).toContain("No decision");
|
||||
});
|
||||
|
||||
it("marks a pending tie and its deadline", () => {
|
||||
const embed = render({
|
||||
poll: poll({
|
||||
status: "pending_decision",
|
||||
closesAt: new Date(Date.now() - HOUR).toISOString(),
|
||||
decisionDeadline: new Date(Date.now() + HOUR).toISOString(),
|
||||
}),
|
||||
});
|
||||
|
||||
expect(embed.description).toContain("Tied");
|
||||
expect(embed.description).toContain("superuser");
|
||||
expect(embed.description).toContain("random tied option");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Poll buttons", () => {
|
||||
it("one neutral button per option, keyed by poll and option", () => {
|
||||
const rows = mod.buildPollRows(poll()).map((row) => row.toJSON());
|
||||
|
||||
expect(rows).toHaveLength(1);
|
||||
const buttons = rows[0].components;
|
||||
expect(buttons).toHaveLength(2);
|
||||
expect(buttons[0]).toMatchObject({
|
||||
custom_id: "ptf-poll:42:accept",
|
||||
style: 2,
|
||||
disabled: false,
|
||||
label: "🤝 Work with the Vanguard",
|
||||
});
|
||||
expect(buttons[1]).toMatchObject({ custom_id: "ptf-poll:42:decline", style: 2 });
|
||||
});
|
||||
|
||||
it("chunks into rows of five", () => {
|
||||
const many = Array.from({ length: 7 }, (_, index) => ({
|
||||
key: `o${index}`,
|
||||
label: `Option ${index}`,
|
||||
emoji: null,
|
||||
description: null,
|
||||
id: `id${index}`,
|
||||
}));
|
||||
const rows = mod.buildPollRows(poll({ options: many })).map((row) => row.toJSON());
|
||||
|
||||
expect(rows.map((row) => row.components.length)).toEqual([5, 2]);
|
||||
});
|
||||
|
||||
it("disables every button once voting is over", () => {
|
||||
const closed = mod
|
||||
.buildPollRows(poll({ closesAt: new Date(Date.now() - HOUR).toISOString() }))
|
||||
.map((row) => row.toJSON());
|
||||
expect(closed[0].components.every((button) => button.disabled === true)).toBe(true);
|
||||
|
||||
const pending = mod
|
||||
.buildPollRows(poll({ status: "pending_decision" }))
|
||||
.map((row) => row.toJSON());
|
||||
expect(pending[0].components.every((button) => button.disabled === true)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Poll hash", () => {
|
||||
const base = {
|
||||
poll: poll(),
|
||||
tally: tally(),
|
||||
votersByOption: new Map<string, string[]>(),
|
||||
};
|
||||
|
||||
it("is stable for identical content", () => {
|
||||
expect(mod.pollHash(base)).toBe(mod.pollHash({ ...base }));
|
||||
});
|
||||
|
||||
it("changes when a vote lands", () => {
|
||||
const voted = {
|
||||
...base,
|
||||
tally: tally({ counts: { accept: { raw: 3, weighted: 4 }, decline: { raw: 1, weighted: 1.5 } } }),
|
||||
};
|
||||
expect(mod.pollHash(voted)).not.toBe(mod.pollHash(base));
|
||||
});
|
||||
|
||||
it("changes when a public voter's name appears", () => {
|
||||
const named = { ...base, votersByOption: new Map([["accept", ["Alpha"]]]) };
|
||||
expect(mod.pollHash(named)).not.toBe(mod.pollHash(base));
|
||||
});
|
||||
|
||||
it("changes when the poll resolves", () => {
|
||||
const closed = { ...base, poll: poll({ status: "closed", winnerKey: "accept" }) };
|
||||
expect(mod.pollHash(closed)).not.toBe(mod.pollHash(base));
|
||||
});
|
||||
});
|
||||
504
tests/int/polls-service.int.spec.ts
Normal file
504
tests/int/polls-service.int.spec.ts
Normal file
|
|
@ -0,0 +1,504 @@
|
|||
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> = {}): NpcDialoguePollConfig => ({
|
||||
title: `${RUN} question`,
|
||||
options: [{ label: "Work with them" }, { label: "Stay independent" }],
|
||||
durationHours: 24,
|
||||
...overrides,
|
||||
});
|
||||
|
||||
const launch = async (
|
||||
nodeId: string,
|
||||
initiatorId: number,
|
||||
overrides: Partial<NpcDialoguePollConfig> = {},
|
||||
): Promise<Poll> => {
|
||||
const { poll } = await launchDialoguePoll(payload, {
|
||||
dialogueId,
|
||||
nodeId,
|
||||
initiatorId,
|
||||
config: config(overrides),
|
||||
});
|
||||
return poll;
|
||||
};
|
||||
|
||||
const reload = async (id: number): Promise<Poll> =>
|
||||
(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<number> => {
|
||||
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);
|
||||
});
|
||||
});
|
||||
295
tests/int/polls-tally.int.spec.ts
Normal file
295
tests/int/polls-tally.int.spec.ts
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
breakTieWithInitiator,
|
||||
buildPollWeights,
|
||||
pickRandomTiedOption,
|
||||
resolvePollTally,
|
||||
resolvePollWeight,
|
||||
tallyPoll,
|
||||
type PollOption,
|
||||
type PollWeightTier,
|
||||
} from "@/lib/polls/tally";
|
||||
|
||||
const OPTIONS: PollOption[] = [
|
||||
{ key: "accept", label: "Work with the faction" },
|
||||
{ key: "decline", label: "Stay independent" },
|
||||
{ key: "defer", label: "Defer the decision" },
|
||||
];
|
||||
|
||||
const tiers: PollWeightTier[] = [
|
||||
{ label: "Logistics", roleIds: [4], multiplier: 1.5 },
|
||||
{ label: "Command", roleIds: [1, 2], multiplier: 2 },
|
||||
];
|
||||
|
||||
const tallyOf = (
|
||||
votes: { userId: number; answers: string[] }[],
|
||||
weights: Map<number, number> = new Map(),
|
||||
) => tallyPoll({ options: OPTIONS, votes, weights });
|
||||
|
||||
describe("resolvePollWeight", () => {
|
||||
it("falls back to the default when no tier matches", () => {
|
||||
expect(resolvePollWeight({ roleIds: [9], tiers })).toEqual({ multiplier: 1, label: null });
|
||||
expect(
|
||||
resolvePollWeight({ roleIds: [], tiers, defaultWeight: 1.25 }),
|
||||
).toEqual({ multiplier: 1.25, label: null });
|
||||
});
|
||||
|
||||
it("uses the highest matching tier instead of stacking them", () => {
|
||||
// Holds Logistics and Command: 2 wins, 1.5 + 2 = 3.5 would not.
|
||||
expect(resolvePollWeight({ roleIds: [4, 2], tiers })).toEqual({
|
||||
multiplier: 2,
|
||||
label: "Command",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the earlier tier when two matching multipliers are equal", () => {
|
||||
const flat: PollWeightTier[] = [
|
||||
{ label: "First", roleIds: [7], multiplier: 1.5 },
|
||||
{ label: "Second", roleIds: [8], multiplier: 1.5 },
|
||||
];
|
||||
expect(resolvePollWeight({ roleIds: [8, 7], tiers: flat })).toEqual({
|
||||
multiplier: 1.5,
|
||||
label: "First",
|
||||
});
|
||||
});
|
||||
|
||||
it("clamps a non-positive multiplier to 1 rather than muting the vote", () => {
|
||||
const broken: PollWeightTier[] = [{ label: "Broken", roleIds: [4], multiplier: 0 }];
|
||||
expect(resolvePollWeight({ roleIds: [4], tiers: broken })).toEqual({
|
||||
multiplier: 1,
|
||||
label: "Broken",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("buildPollWeights", () => {
|
||||
it("weights each voter once, from the roles they hold now", () => {
|
||||
const weights = buildPollWeights({
|
||||
votes: [
|
||||
{ userId: 1, answers: ["accept"] },
|
||||
{ userId: 2, answers: ["decline"] },
|
||||
{ userId: 3, answers: ["defer"] },
|
||||
],
|
||||
roleIdsByUser: new Map([
|
||||
[1, [4]],
|
||||
[2, [1]],
|
||||
[3, [99]],
|
||||
]),
|
||||
tiers,
|
||||
});
|
||||
|
||||
expect([...weights.entries()].sort()).toEqual([
|
||||
[1, 1.5],
|
||||
[2, 2],
|
||||
[3, 1],
|
||||
]);
|
||||
});
|
||||
|
||||
it("gives an unlisted voter the default weight", () => {
|
||||
const weights = buildPollWeights({
|
||||
votes: [{ userId: 5, answers: ["accept"] }],
|
||||
roleIdsByUser: new Map(),
|
||||
tiers,
|
||||
defaultWeight: 1,
|
||||
});
|
||||
expect(weights.get(5)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("tallyPoll", () => {
|
||||
it("counts raw and weighted scores separately", () => {
|
||||
const tally = tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept"] },
|
||||
{ userId: 2, answers: ["accept"] },
|
||||
{ userId: 3, answers: ["decline"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
[3, 1.5],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(tally.counts.accept).toEqual({ raw: 2, weighted: 3 });
|
||||
expect(tally.counts.decline).toEqual({ raw: 1, weighted: 1.5 });
|
||||
expect(tally.totalVotes).toBe(3);
|
||||
expect(tally.totalWeight).toBe(4.5);
|
||||
expect(tally.topKeys).toEqual(["accept"]);
|
||||
});
|
||||
|
||||
it("counts every answer on a multi-select poll", () => {
|
||||
const tally = tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept", "defer"] },
|
||||
{ userId: 2, answers: ["decline"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(tally.counts.accept.raw).toBe(1);
|
||||
expect(tally.counts.defer.raw).toBe(1);
|
||||
// Turnout is per voter, not per answer.
|
||||
expect(tally.totalVotes).toBe(2);
|
||||
expect(tally.totalWeight).toBe(2);
|
||||
});
|
||||
|
||||
it("dedupes a repeated key inside one vote", () => {
|
||||
const tally = tallyOf(
|
||||
[{ userId: 1, answers: ["accept", "accept", "accept"] }],
|
||||
new Map([[1, 2]]),
|
||||
);
|
||||
expect(tally.counts.accept).toEqual({ raw: 1, weighted: 2 });
|
||||
});
|
||||
|
||||
it("ignores answers naming an option that is not on the poll", () => {
|
||||
const tally = tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept", "ghost"] },
|
||||
{ userId: 2, answers: ["ghost"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(tally.counts.accept.raw).toBe(1);
|
||||
expect(tally.counts.ghost).toBeUndefined();
|
||||
// The vote naming only a dead option is not turnout.
|
||||
expect(tally.totalVotes).toBe(1);
|
||||
});
|
||||
|
||||
it("compares weights exactly, so decimal multipliers cannot fake a tie", () => {
|
||||
// 1.1 + 1.1 against a single 2.2: float addition would miss the tie.
|
||||
const tally = tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept"] },
|
||||
{ userId: 2, answers: ["accept"] },
|
||||
{ userId: 3, answers: ["decline"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 1.1],
|
||||
[2, 1.1],
|
||||
[3, 2.2],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(tally.counts.accept.weighted).toBe(2.2);
|
||||
expect(tally.topKeys).toEqual(["accept", "decline"]);
|
||||
});
|
||||
|
||||
it("reports no top option when nobody voted", () => {
|
||||
const tally = tallyOf([]);
|
||||
expect(tally.topScore).toBe(0);
|
||||
expect(tally.topKeys).toEqual([]);
|
||||
expect(tally.totalVotes).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("breakTieWithInitiator", () => {
|
||||
it("picks the one tied option the initiator voted for", () => {
|
||||
expect(
|
||||
breakTieWithInitiator({
|
||||
tiedKeys: ["accept", "decline"],
|
||||
initiatorAnswers: ["decline"],
|
||||
}),
|
||||
).toBe("decline");
|
||||
});
|
||||
|
||||
it("refuses when the initiator picked several tied options", () => {
|
||||
expect(
|
||||
breakTieWithInitiator({
|
||||
tiedKeys: ["accept", "decline"],
|
||||
initiatorAnswers: ["accept", "decline"],
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses when the initiator voted outside the tie, or not at all", () => {
|
||||
expect(
|
||||
breakTieWithInitiator({ tiedKeys: ["accept", "decline"], initiatorAnswers: ["defer"] }),
|
||||
).toBeNull();
|
||||
expect(breakTieWithInitiator({ tiedKeys: ["accept"], initiatorAnswers: [] })).toBeNull();
|
||||
expect(breakTieWithInitiator({ tiedKeys: ["accept"], initiatorAnswers: null })).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolvePollTally", () => {
|
||||
const tiedTally = () =>
|
||||
tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept"] },
|
||||
{ userId: 2, answers: ["decline"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
]),
|
||||
);
|
||||
|
||||
it("decides a unique winner on votes", () => {
|
||||
const tally = tallyOf(
|
||||
[
|
||||
{ userId: 1, answers: ["accept"] },
|
||||
{ userId: 2, answers: ["accept"] },
|
||||
{ userId: 3, answers: ["decline"] },
|
||||
],
|
||||
new Map([
|
||||
[1, 1],
|
||||
[2, 1],
|
||||
[3, 1],
|
||||
]),
|
||||
);
|
||||
|
||||
expect(resolvePollTally({ tally, initiatorAnswers: ["decline"] })).toEqual({
|
||||
status: "decided",
|
||||
winnerKey: "accept",
|
||||
method: "votes",
|
||||
});
|
||||
});
|
||||
|
||||
it("breaks a tie with the initiator's vote", () => {
|
||||
expect(resolvePollTally({ tally: tiedTally(), initiatorAnswers: ["decline"] })).toEqual({
|
||||
status: "decided",
|
||||
winnerKey: "decline",
|
||||
method: "initiator",
|
||||
});
|
||||
});
|
||||
|
||||
it("escalates a tie the initiator cannot break", () => {
|
||||
expect(
|
||||
resolvePollTally({ tally: tiedTally(), initiatorAnswers: ["accept", "decline"] }),
|
||||
).toEqual({ status: "pending", tiedKeys: ["accept", "decline"] });
|
||||
expect(resolvePollTally({ tally: tiedTally(), initiatorAnswers: null })).toEqual({
|
||||
status: "pending",
|
||||
tiedKeys: ["accept", "decline"],
|
||||
});
|
||||
});
|
||||
|
||||
it("returns none when nothing counted", () => {
|
||||
expect(resolvePollTally({ tally: tallyOf([]), initiatorAnswers: ["accept"] })).toEqual({
|
||||
status: "none",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("pickRandomTiedOption", () => {
|
||||
it("is deterministic under an injected rng", () => {
|
||||
expect(pickRandomTiedOption(["a", "b", "c"], () => 0)).toBe("a");
|
||||
expect(pickRandomTiedOption(["a", "b", "c"], () => 0.5)).toBe("b");
|
||||
expect(pickRandomTiedOption(["a", "b", "c"], () => 0.999)).toBe("c");
|
||||
});
|
||||
|
||||
it("clamps an rng that returns exactly 1", () => {
|
||||
expect(pickRandomTiedOption(["a", "b"], () => 1)).toBe("b");
|
||||
});
|
||||
|
||||
it("returns null with nothing to pick", () => {
|
||||
expect(pickRandomTiedOption([])).toBeNull();
|
||||
});
|
||||
});
|
||||
Loading…
Reference in a new issue