diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts
index 095fd188..8ac1e234 100644
--- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts
+++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts
@@ -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 {
+): Promise> {
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>,
- userId: number,
- npcId: number,
- effect: NpcDialogueEffect,
-): Promise {
+ 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 };
+ }
}
}
diff --git a/src/collections/game/GameEventLogs.ts b/src/collections/game/GameEventLogs.ts
index f12a1fb3..182ebfbc 100644
--- a/src/collections/game/GameEventLogs.ts
+++ b/src/collections/game/GameEventLogs.ts
@@ -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 = {
diff --git a/src/components/admin/npc-dialogue/NodeEditDialog.tsx b/src/components/admin/npc-dialogue/NodeEditDialog.tsx
index be68d532..99f073f3 100644
--- a/src/components/admin/npc-dialogue/NodeEditDialog.tsx
+++ b/src/components/admin/npc-dialogue/NodeEditDialog.tsx
@@ -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 = {
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 No roles loaded.
;
+ }
+ return (
+
+ {roles.map((role) => (
+
+
+ onChange(
+ e.target.checked ? [...value, role.id] : value.filter((id) => id !== role.id),
+ )
+ }
+ className="accent-emerald-500"
+ />
+ {role.name}
+
+ ))}
+
+ );
+}
+
const FLAG_OP_LABELS: Record = {
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) =>
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) =>
+ patchEffect({ poll: { ...draft.effect?.poll, ...partial } });
+ const pollOptions = draft.effect?.poll?.options ?? [];
+ const setPollOption = (index: number, partial: Partial) =>
+ 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) =>
+ 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({
)}
- {draft.effect && (
+ {draft.effect?.type === "poll" && (
+
+
+
+ Question
+
+ 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"
+ />
+
+
+
+ Context (optional)
+
+
+
+
+
+ Options
+
+ {pollOptions.map((option, index) => (
+
+ ))}
+
= 10}
+ className="self-start border-white/20 text-white/70 hover:text-white"
+ >
+ Add option
+
+
+ Option keys are derived from the labels. Two options that read the same
+ still get distinct keys.
+
+
+
+
+
+
+
+ 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
+
+
+
+
+ Voter identities
+
+
+ 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"
+ >
+ Public: everyone sees who voted
+
+ Anonymous: counts for members, names for superusers
+
+
+
+
+
+
+ Who may vote
+
+
patchPoll({ eligibleRoleIds })}
+ />
+
+ Leave empty for the whole unit.
+
+
+
+
+
+ Voting weight tiers
+
+ {pollTiers.map((tier, index) => (
+
+ ))}
+
+ Add weight tier
+
+
+ A member in several tiers gets the highest multiplier, never the sum.
+ Weight is resolved from roles when the poll closes.
+
+
+
+
+
+ Result flag (optional)
+
+
patchPoll({ resultFlag: e.target.value })}
+ placeholder="vanguard_alignment"
+ className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
+ />
+
+ 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.
+
+
+
+ )}
+ {draft.effect && draft.effect.type !== "poll" && (
Message
)}
- {draft.effect && draft.effect.type !== "notify" && (
+ {draft.effect &&
+ draft.effect.type !== "notify" &&
+ draft.effect.type !== "poll" && (
)}
- {draft.effect && draft.effect.type !== "notify" && (
+ {draft.effect &&
+ draft.effect.type !== "notify" &&
+ draft.effect.type !== "poll" && (
) : (
diff --git a/src/components/frontend/personnel/NpcConversation.tsx b/src/components/frontend/personnel/NpcConversation.tsx
index 223b7d57..ba50b663 100644
--- a/src/components/frontend/personnel/NpcConversation.tsx
+++ b/src/components/frontend/personnel/NpcConversation.tsx
@@ -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(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(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({
+ {/* 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 && (
+
+
+
+ The unit is being polled on this. Open the poll.
+
+
+ )}
+
{/* 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
diff --git a/src/lib/npc-dialogue/dialogue.ts b/src/lib/npc-dialogue/dialogue.ts
index cc504e93..3326a46d 100644
--- a/src/lib/npc-dialogue/dialogue.ts
+++ b/src/lib/npc-dialogue/dialogue.ts
@@ -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",
];
/**
diff --git a/src/lib/npc-dialogue/preview.ts b/src/lib/npc-dialogue/preview.ts
index 8112b9b9..7304d1f4 100644
--- a/src/lib/npc-dialogue/preview.ts
+++ b/src/lib/npc-dialogue/preview.ts
@@ -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)})`];
}
diff --git a/src/utils/event-log/emit.ts b/src/utils/event-log/emit.ts
index 0384f290..457ad6e1 100644
--- a/src/utils/event-log/emit.ts
+++ b/src/utils/event-log/emit.ts
@@ -60,7 +60,8 @@ interface GameEventInput {
| "map-objectives"
| "contribution-entries"
| "journals"
- | "awards";
+ | "awards"
+ | "polls";
targetId?: number;
data?: Record;
/**
diff --git a/src/utils/event-log/eventTypes.ts b/src/utils/event-log/eventTypes.ts
index bb0cd7e1..ec611660 100644
--- a/src/utils/event-log/eventTypes.ts
+++ b/src/utils/event-log/eventTypes.ts
@@ -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",