diff --git a/src/app/(frontend)/polls/[id]/page.tsx b/src/app/(frontend)/polls/[id]/page.tsx
new file mode 100644
index 00000000..1ad86ef7
--- /dev/null
+++ b/src/app/(frontend)/polls/[id]/page.tsx
@@ -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 (
+
+ );
+}
diff --git a/src/app/(frontend)/polls/actions.ts b/src/app/(frontend)/polls/actions.ts
new file mode 100644
index 00000000..364236c6
--- /dev/null
+++ b/src/app/(frontend)/polls/actions.ts
@@ -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 {
+ 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>,
+ user: { id: number | string; roleDocs?: unknown },
+): Promise {
+ 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): 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> {
+ 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> {
+ 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> {
+ 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> {
+ 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 };
+ }
+}
diff --git a/src/app/(frontend)/polls/page.tsx b/src/app/(frontend)/polls/page.tsx
new file mode 100644
index 00000000..dd75c819
--- /dev/null
+++ b/src/app/(frontend)/polls/page.tsx
@@ -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 (
+
+
+
+
+
+ {statusLabel(view)}
+
+
+ {view.multiSelect ? "Multiple answers" : "One answer"}
+
+
+ {view.anonymity === "anonymous" ? "Anonymous" : "Public"}
+
+ {view.initiated && (
+
+ You opened this
+
+ )}
+
+ {view.title}
+
+
+
+
+ {view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"}
+
+
+ {view.closed
+ ? `Closed ${new Date(view.closesAt).toLocaleDateString()}`
+ : `Closes ${new Date(view.closesAt).toLocaleString()}`}
+
+ {view.closed && view.winnerLabel && Outcome: {view.winnerLabel} }
+
+
+ {leading && (
+
+
+
+ {leading.emoji ? `${leading.emoji} ` : ""}
+ {leading.label}
+
+
+ {leading.raw} · weight {Number.isInteger(leading.weighted) ? leading.weighted : leading.weighted.toFixed(2)}
+
+
+
+
+ )}
+
+
+
+ );
+}
+
+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 (
+
+
+
+
+
Unit polls
+
+
+ Questions the unit answers together. A conversation with an NPC can raise one; your vote
+ here and on Discord are the same vote.
+
+
+
+ {live.length === 0 && past.length === 0 && (
+
+
+ No polls yet. They appear here when a conversation raises one.
+
+
+ )}
+
+ {live.length > 0 && (
+
+
+ Live
+
+ {live.map((view) => (
+
+ ))}
+
+ )}
+
+ {past.length > 0 && (
+
+
+ Closed
+
+ {past.map((view) => (
+
+ ))}
+
+ )}
+
+ );
+}
diff --git a/src/components/frontend/blocks/sidebarData.ts b/src/components/frontend/blocks/sidebarData.ts
index a1975e5f..9a798c6c 100644
--- a/src/components/frontend/blocks/sidebarData.ts
+++ b/src/components/frontend/blocks/sidebarData.ts
@@ -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: [
{
diff --git a/src/components/frontend/polls/PollVotePanel.tsx b/src/components/frontend/polls/PollVotePanel.tsx
new file mode 100644
index 00000000..41fa5bd7
--- /dev/null
+++ b/src/components/frontend/polls/PollVotePanel.tsx
@@ -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 Tied ;
+ }
+ if (view.closed) {
+ return Closed ;
+ }
+ return Open ;
+}
+
+/**
+ * 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(initialView);
+ const [error, setError] = useState(null);
+ const [notice, setNotice] = useState(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 (
+
+
+
+
+
+
+ {view.multiSelect ? "Multiple answers" : "One answer"}
+
+
+ {view.anonymity === "anonymous" ? "Anonymous" : "Public"}
+
+ {view.eligibleRoleCount > 0 && (
+
+ {view.eligibleRoleCount} eligible role{view.eligibleRoleCount === 1 ? "" : "s"}
+
+ )}
+ {view.initiated && (
+
+ You opened this
+
+ )}
+
+ {view.title}
+ {view.body && {view.body}
}
+
+
+
+
+
+ {view.closed
+ ? `Closed ${formatWhen(view.closesAt)}`
+ : `Closes ${formatWhen(view.closesAt)} (${relative(view.closesAt)})`}
+
+
+
+ {view.totalVotes} voter{view.totalVotes === 1 ? "" : "s"} · weight{" "}
+ {formatWeight(view.totalWeight)}
+
+ {view.anonymity === "anonymous" && (
+
+
+ {view.showsVoters
+ ? "Anonymous to members; you can see voters"
+ : "Voter identities are hidden"}
+
+ )}
+
+
+
+
+
+ {view.options.map((option) => {
+ const chosen = option.chosen;
+ const selectable = view.canVote;
+ return (
+
+
+
+
+ {option.emoji && {option.emoji} }
+ {option.label}
+ {chosen && }
+
+ {option.description && (
+
{option.description}
+ )}
+
+
+
{option.raw}
+
weight {formatWeight(option.weighted)}
+
+
+
+
+
+ {option.voters.length > 0 && (
+
+ {option.voters.join(", ")}
+
+ )}
+
+ {selectable && (
+
toggleOption(option.key)}
+ >
+ {chosen
+ ? view.multiSelect
+ ? "Remove my answer"
+ : "Withdraw my vote"
+ : view.multiSelect
+ ? "Add my answer"
+ : "Vote for this"}
+
+ )}
+
+ );
+ })}
+
+
+ {error && {error}
}
+ {notice && !error && {notice}
}
+
+ {!view.canVote && !view.closed && view.eligibleRoleCount > 0 && (
+
+ Only members holding one of this poll's eligible roles may vote.
+
+ )}
+
+ {view.resolved && (
+
+ {view.winnerKey ? (
+ <>
+ Outcome:
+ {view.winnerLabel}
+
+ {" "}
+ ({view.resolutionMethod?.replace("_", " ")})
+
+ >
+ ) : (
+
+ {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."}
+
+ )}
+
+ )}
+
+
+
+ {view.awaitingDecision && (
+
+
+
+
+ Tied vote
+
+
+ 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.`
+ : ""}
+
+
+
+ {tiedOptions.map((option) => (
+
+
+ {option.emoji ? `${option.emoji} ` : ""}
+ {option.label}
+
+ weight {formatWeight(option.weighted)}
+
+
+ {view.canResolve ? (
+ settleTie(option.key)}
+ >
+ Decide
+
+ ) : null}
+
+ ))}
+ {!view.canResolve && (
+
+ A superuser will settle this.
+
+ )}
+
+
+ )}
+
+
+
+ All polls
+
+ {isPending ? "Updating..." : `Refreshes every ${REFRESH_MS / 1000}s`}
+
+
+ );
+}