Implement governed voting module
This commit is contained in:
@@ -0,0 +1,287 @@
|
||||
import { CheckCircle2, Pencil, Plus, RefreshCw, ShieldCheck, XCircle } from "lucide-react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
DismissibleAlert,
|
||||
FormField,
|
||||
IconButton,
|
||||
LoadingIndicator,
|
||||
PageScrollViewport,
|
||||
StatusBadge,
|
||||
hasScope,
|
||||
type PlatformRouteContext
|
||||
} from "@govoplan/core-webui";
|
||||
import {
|
||||
castVotingBallot,
|
||||
getVotingBallot,
|
||||
listVotingBallots,
|
||||
listVotingHistory,
|
||||
reasonedVotingTransition,
|
||||
transitionVotingBallot,
|
||||
type VotingBallot,
|
||||
type VotingEvent
|
||||
} from "../../api/voting";
|
||||
import VotingBallotDialog from "./VotingBallotDialog";
|
||||
|
||||
|
||||
export default function VotingPage({ settings, auth }: PlatformRouteContext) {
|
||||
const [items, setItems] = useState<VotingBallot[]>([]);
|
||||
const [selectedId, setSelectedId] = useState<string | null>(null);
|
||||
const [selected, setSelected] = useState<VotingBallot | null>(null);
|
||||
const [history, setHistory] = useState<VotingEvent[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState("");
|
||||
const [notice, setNotice] = useState("");
|
||||
const [editing, setEditing] = useState<VotingBallot | "new" | null>(null);
|
||||
const [reasonAction, setReasonAction] = useState<"challenge" | "annul" | null>(null);
|
||||
const [selections, setSelections] = useState<string[]>([]);
|
||||
const canManage = hasScope(auth, "voting:ballot:manage");
|
||||
const canCast = hasScope(auth, "voting:ballot:cast");
|
||||
const canCertify = hasScope(auth, "voting:ballot:certify");
|
||||
const canAdmin = hasScope(auth, "voting:ballot:admin");
|
||||
|
||||
const loadList = useCallback(async (signal?: AbortSignal, preferredId?: string) => {
|
||||
setLoading(true);
|
||||
setError("");
|
||||
try {
|
||||
const result = await listVotingBallots(settings, undefined, signal);
|
||||
setItems(result.ballots);
|
||||
setSelectedId((current) => preferredId ?? current ?? result.ballots[0]?.id ?? null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [settings]);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
void loadList(controller.signal).catch((reason) => {
|
||||
if ((reason as Error).name !== "AbortError") setError(message(reason, "Ballots could not be loaded."));
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [loadList]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!selectedId) {
|
||||
setSelected(null);
|
||||
setHistory([]);
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
Promise.all([
|
||||
getVotingBallot(settings, selectedId, controller.signal),
|
||||
listVotingHistory(settings, selectedId, controller.signal)
|
||||
]).then(([ballot, events]) => {
|
||||
setSelected(ballot);
|
||||
setHistory(events);
|
||||
setSelections([]);
|
||||
}).catch((reason) => {
|
||||
if ((reason as Error).name !== "AbortError") setError(message(reason, "Ballot details could not be loaded."));
|
||||
});
|
||||
return () => controller.abort();
|
||||
}, [selectedId, settings]);
|
||||
|
||||
const eligible = useMemo(() => Boolean(
|
||||
selected?.electorate.some((item) => item.subject_id === auth.account.id)
|
||||
), [auth.account.id, selected]);
|
||||
|
||||
async function run(action: "open" | "close" | "certify") {
|
||||
if (!selected) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setNotice("");
|
||||
try {
|
||||
await transitionVotingBallot(settings, selected, action, action === "certify" ? { evidence: [] } : {});
|
||||
await reloadSelected(`${humanize(action)} completed.`);
|
||||
} catch (reason) {
|
||||
setError(message(reason, `The ballot could not be ${action}ed.`));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function cast() {
|
||||
if (!selected || selections.length === 0) return;
|
||||
setBusy(true);
|
||||
setError("");
|
||||
setNotice("");
|
||||
try {
|
||||
const receipt = await castVotingBallot(settings, selected.id, selections);
|
||||
setNotice(`${receipt.replaced_previous ? "Vote replaced" : "Vote recorded"}. Receipt ${receipt.receipt_sha256.slice(0, 12)}...`);
|
||||
const events = await listVotingHistory(settings, selected.id);
|
||||
setHistory(events);
|
||||
} catch (reason) {
|
||||
setError(message(reason, "The vote could not be recorded."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function reloadSelected(success?: string) {
|
||||
if (!selectedId) return;
|
||||
const [ballot, events] = await Promise.all([
|
||||
getVotingBallot(settings, selectedId),
|
||||
listVotingHistory(settings, selectedId)
|
||||
]);
|
||||
setSelected(ballot);
|
||||
setHistory(events);
|
||||
await loadList(undefined, selectedId);
|
||||
if (success) setNotice(success);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="voting-page">
|
||||
<div className="voting-shell">
|
||||
<aside className="voting-catalogue">
|
||||
<div className="voting-toolbar">
|
||||
<IconButton label="Refresh ballots" icon={<RefreshCw size={16} />} disabled={loading || busy} onClick={() => void loadList()} />
|
||||
{canManage && <Button variant="primary" onClick={() => setEditing("new")}><Plus size={16} aria-hidden="true" />New ballot</Button>}
|
||||
</div>
|
||||
<PageScrollViewport className="voting-list-viewport">
|
||||
{loading && <LoadingIndicator label="Loading ballots" />}
|
||||
{!loading && items.length === 0 && <div className="voting-empty">No ballots.</div>}
|
||||
<div className="voting-list" role="list">
|
||||
{items.map((item) => <button type="button" role="listitem" className={`voting-list-row${item.id === selectedId ? " is-selected" : ""}`} key={item.id} onClick={() => setSelectedId(item.id)}>
|
||||
<span><strong>{item.title}</strong><small>{humanize(item.assurance_profile)}</small></span>
|
||||
<StatusBadge status={statusTone(item.state)} label={humanize(item.state)} />
|
||||
</button>)}
|
||||
</div>
|
||||
</PageScrollViewport>
|
||||
</aside>
|
||||
<section className="voting-workspace">
|
||||
{error && <DismissibleAlert tone="danger" resetKey={error}>{error}</DismissibleAlert>}
|
||||
{notice && <DismissibleAlert tone="success" resetKey={notice}>{notice}</DismissibleAlert>}
|
||||
{!selected && !loading && <div className="voting-empty">Select a ballot.</div>}
|
||||
{selected && <PageScrollViewport className="voting-detail-viewport">
|
||||
<div className="voting-detail-heading">
|
||||
<div><h2>{selected.title}</h2><span>Revision {selected.revision}</span></div>
|
||||
<div className="voting-actions">
|
||||
<StatusBadge status={statusTone(selected.state)} label={humanize(selected.state)} />
|
||||
{canManage && selected.state === "draft" && <IconButton label={`Edit ${selected.title}`} icon={<Pencil size={16} />} disabled={busy} onClick={() => setEditing(selected)} />}
|
||||
{canManage && selected.state === "draft" && <Button variant="primary" disabled={busy} onClick={() => void run("open")}><CheckCircle2 size={16} aria-hidden="true" />Open</Button>}
|
||||
{canManage && selected.state === "open" && <Button variant="primary" disabled={busy} onClick={() => void run("close")}><XCircle size={16} aria-hidden="true" />Close and tally</Button>}
|
||||
{canCertify && selected.state === "closed" && <Button variant="primary" disabled={busy} onClick={() => void run("certify")}><ShieldCheck size={16} aria-hidden="true" />Certify</Button>}
|
||||
{canCertify && ["closed", "certified"].includes(selected.state) && <Button disabled={busy} onClick={() => setReasonAction("challenge")}>Challenge</Button>}
|
||||
{canAdmin && selected.state !== "annulled" && <Button variant="danger" disabled={busy} onClick={() => setReasonAction("annul")}>Annul</Button>}
|
||||
</div>
|
||||
</div>
|
||||
<div className="voting-metrics">
|
||||
<Metric label="Electors" value={selected.electorate.length} />
|
||||
<Metric label="Eligible weight" value={selected.electorate.reduce((total, item) => total + item.weight, 0)} />
|
||||
<Metric label="Quorum" value={selected.quorum_weight} />
|
||||
<Metric label="Assurance" value={humanize(selected.assurance_profile)} />
|
||||
</div>
|
||||
{selected.description && <p className="voting-description">{selected.description}</p>}
|
||||
{selected.state === "open" && selected.assurance_profile === "recorded" && canCast && eligible && <section className="voting-cast-panel">
|
||||
<h3>Cast vote</h3>
|
||||
<div className="voting-options">
|
||||
{selected.options.map((option) => <label key={option.key}>
|
||||
<input
|
||||
type={selected.method === "approval" ? "checkbox" : "radio"}
|
||||
name="voting-selection"
|
||||
checked={selections.includes(option.key)}
|
||||
onChange={(event) => setSelections((current) => selected.method === "approval"
|
||||
? event.target.checked ? [...current, option.key] : current.filter((item) => item !== option.key)
|
||||
: [option.key])}
|
||||
/>
|
||||
<span><strong>{option.label}</strong>{option.description && <small>{option.description}</small>}</span>
|
||||
</label>)}
|
||||
</div>
|
||||
<Button variant="primary" disabled={busy || selections.length === 0} onClick={() => void cast()}>Submit vote</Button>
|
||||
</section>}
|
||||
<section className="voting-section">
|
||||
<h3>Options</h3>
|
||||
<div className="voting-option-results">
|
||||
{selected.options.map((option) => <div key={option.key}>
|
||||
<span><strong>{option.label}</strong><small>{option.key}</small></span>
|
||||
{selected.result && <span>{selected.result.counts[option.key] ?? 0} votes / {selected.result.weighted_counts[option.key] ?? 0} weight</span>}
|
||||
</div>)}
|
||||
</div>
|
||||
</section>
|
||||
{selected.result && <section className="voting-section">
|
||||
<h3>Result</h3>
|
||||
<div className="voting-metrics">
|
||||
<Metric label="Votes" value={`${selected.result.cast_count} / ${selected.result.eligible_count}`} />
|
||||
<Metric label="Cast weight" value={`${selected.result.cast_weight} / ${selected.result.eligible_weight}`} />
|
||||
<Metric label="Quorum" value={selected.result.quorum_met ? "Met" : "Not met"} />
|
||||
<Metric label="Threshold" value={selected.result.threshold_met ? "Met" : "Not met"} />
|
||||
</div>
|
||||
<Hash label="Result hash" value={selected.result.result_sha256} />
|
||||
</section>}
|
||||
<section className="voting-section voting-assurance">
|
||||
<h3>Frozen assurance</h3>
|
||||
<Hash label="Definition" value={selected.definition_sha256} />
|
||||
<Hash label="Electorate" value={selected.electorate_sha256} />
|
||||
</section>
|
||||
<section className="voting-section">
|
||||
<h3>History</h3>
|
||||
<div className="voting-history">
|
||||
{history.map((item) => <div key={item.sequence}><span>{item.sequence}</span><strong>{humanize(item.event_type)}</strong><time>{new Date(item.recorded_at).toLocaleString()}</time></div>)}
|
||||
</div>
|
||||
</section>
|
||||
</PageScrollViewport>}
|
||||
</section>
|
||||
</div>
|
||||
{editing && <VotingBallotDialog
|
||||
open
|
||||
settings={settings}
|
||||
ballot={editing === "new" ? null : editing}
|
||||
currentAccountId={auth.account.id}
|
||||
onClose={() => setEditing(null)}
|
||||
onSaved={(ballot) => {
|
||||
setEditing(null);
|
||||
setSelectedId(ballot.id);
|
||||
void loadList(undefined, ballot.id);
|
||||
}}
|
||||
/>}
|
||||
{selected && reasonAction && <ReasonDialog
|
||||
action={reasonAction}
|
||||
busy={busy}
|
||||
onClose={() => setReasonAction(null)}
|
||||
onConfirm={async (reason) => {
|
||||
setBusy(true);
|
||||
setError("");
|
||||
try {
|
||||
await reasonedVotingTransition(settings, selected, reasonAction, reason);
|
||||
setReasonAction(null);
|
||||
await reloadSelected(`${humanize(reasonAction)} recorded.`);
|
||||
} catch (failure) {
|
||||
setError(message(failure, "The transition could not be recorded."));
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}}
|
||||
/>}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function Metric({ label, value }: { label: string; value: string | number }) {
|
||||
return <div><span>{label}</span><strong>{value}</strong></div>;
|
||||
}
|
||||
|
||||
function Hash({ label, value }: { label: string; value?: string | null }) {
|
||||
return <div className="voting-hash"><span>{label}</span><code>{value || "Not frozen"}</code></div>;
|
||||
}
|
||||
|
||||
function ReasonDialog({ action, busy, onClose, onConfirm }: { action: "challenge" | "annul"; busy: boolean; onClose: () => void; onConfirm: (reason: string) => Promise<void> }) {
|
||||
const [reason, setReason] = useState("");
|
||||
return <Dialog open title={`${humanize(action)} ballot`} onClose={onClose} closeDisabled={busy} portal footer={<><Button onClick={onClose} disabled={busy}>Cancel</Button><Button variant={action === "annul" ? "danger" : "primary"} disabled={busy || !reason.trim()} onClick={() => void onConfirm(reason.trim())}>Confirm</Button></>}>
|
||||
<FormField label="Reason"><textarea rows={5} value={reason} disabled={busy} onChange={(event) => setReason(event.target.value)} /></FormField>
|
||||
</Dialog>;
|
||||
}
|
||||
|
||||
function statusTone(state: VotingBallot["state"]): "active" | "inactive" | "warning" {
|
||||
if (state === "open" || state === "certified") return "active";
|
||||
if (state === "challenged") return "warning";
|
||||
return "inactive";
|
||||
}
|
||||
|
||||
function humanize(value: string): string {
|
||||
return value.replace(/[_:.-]+/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
|
||||
}
|
||||
|
||||
function message(reason: unknown, fallback: string): string {
|
||||
return reason instanceof Error ? reason.message : fallback;
|
||||
}
|
||||
Reference in New Issue
Block a user