1
0
Fork 0

feat(polls): raise a unit poll from an NPC dialogue event node

A fifth effect type, `poll`, alongside notify/emit/reward/flag. The node holds
only the authoring config; the poll itself is a document created on first
trigger, so the conversation cannot rewrite a live poll.

- Node editor: question, context, options (keys derived from the labels, so two
  options that read the same still get distinct keys), duration, multi-select,
  anonymity, role eligibility, weight tiers and the result flag. Role pickers
  are native checkboxes: the admin bundle never loads the frontend stylesheet,
  so portaled selects render unstyled and only respond to the keyboard.
- The effect is idempotent by construction: a player who reaches the node twice
  gets the same poll back, and the action returns its id.
- The conversation keeps a link to the poll it raised, so the player does not
  have to hunt for it in the notification inbox.
- Drafts can never emit a poll: the generation schema only allows none/flag/
  notify, and the validator rejects anything else.
This commit is contained in:
Jason Fraley 2026-12-01 14:17:40 -05:00
parent 90d6435b71
commit c05ef12110
9 changed files with 478 additions and 17 deletions

View file

@ -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 };
}
}
}

View file

@ -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 = {

View file

@ -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) =>
@ -737,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&apos;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
@ -750,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"}
@ -764,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}

View file

@ -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>
) : (

View file

@ -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";
@ -548,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;
}
@ -596,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 = () => {
@ -975,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

View file

@ -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",
];
/**

View file

@ -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)})`];
}

View file

@ -60,7 +60,8 @@ interface GameEventInput {
| "map-objectives"
| "contribution-entries"
| "journals"
| "awards";
| "awards"
| "polls";
targetId?: number;
data?: Record<string, unknown>;
/**

View file

@ -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",