Starlette backend with sqlite, rotating HMAC QR tokens pushed to a key-protected projector page, multi-scan enrollment, optional one-time paper codes, anonymous ballots split from participation, live question push over websockets, e2e tests over HTTP and TLS.
251 lines
9.4 KiB
JavaScript
251 lines
9.4 KiB
JavaScript
import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct } from "./common.js";
|
||
|
||
const pid = pollId();
|
||
const key = takeKey(`rv_admin_${pid}`);
|
||
const base = `/api/polls/${pid}`;
|
||
let state = null;
|
||
let settingsDirty = false;
|
||
|
||
const TEMPLATES = [
|
||
{ label: "Pour / Contre / Abstention", opts: ["Pour", "Contre", "Abstention"], blank: false },
|
||
{ label: "Oui / Non", opts: ["Oui", "Non"], blank: true },
|
||
{ label: "Élection (candidats)", opts: ["Candidat·e A", "Candidat·e B", "Candidat·e C"], blank: true, text: "Élection : " },
|
||
{ label: "Satisfaction 1–5", opts: ["1", "2", "3", "4", "5"], blank: true },
|
||
];
|
||
|
||
const call = (method, path, data) => api(method, base + path, data, key);
|
||
|
||
function errMsg(e) {
|
||
const m = {
|
||
not_draft: "La question n'est plus en brouillon",
|
||
not_open: "La question n'est pas ouverte",
|
||
not_closed: "La question n'est pas close",
|
||
};
|
||
return m[e.code] || e.message;
|
||
}
|
||
|
||
|
||
function render() {
|
||
const p = state.poll;
|
||
$("#title").textContent = p.title;
|
||
document.title = `Admin · ${p.title}`;
|
||
$("#voters").textContent = state.voters;
|
||
const parts = [];
|
||
if (p.expected) parts.push(`sur ${p.expected} attendus`);
|
||
if (p.max_voters) parts.push(`${p.max_voters} max`);
|
||
$("#voters-of").textContent = `inscrits${parts.length ? ", " + parts.join(", ") : ""}`;
|
||
|
||
const es = $("#enroll-state");
|
||
es.hidden = !p.enrollment_open && !(p.expected && state.voters > p.expected);
|
||
if (p.enrollment_open) {
|
||
es.className = "notice ok";
|
||
es.textContent = "Ouvertes";
|
||
} else {
|
||
es.className = "notice info";
|
||
es.textContent = "Fermées";
|
||
}
|
||
if (p.expected && state.voters > p.expected) {
|
||
es.className = "notice bad";
|
||
es.textContent = `${state.voters} inscrits pour ${p.expected} attendus`;
|
||
}
|
||
const tb = $("#toggle-enroll");
|
||
tb.textContent = p.enrollment_open ? "Fermer les inscriptions" : "Ouvrir les inscriptions";
|
||
tb.className = "block " + (p.enrollment_open ? "danger" : "go");
|
||
|
||
$("#screens").textContent = state.screens ? `Projecteur connecté (${state.screens})` : "Aucun projecteur connecté";
|
||
|
||
if (!settingsDirty) {
|
||
$("#s-interval").value = p.interval_ms;
|
||
$("#s-scans").value = p.scans_required;
|
||
$("#s-expected").value = p.expected ?? "";
|
||
$("#s-max").value = p.max_voters ?? "";
|
||
$("#s-code").checked = p.require_code;
|
||
}
|
||
$("#codes-card").hidden = !p.require_code && !state.codes.total;
|
||
$("#codes-summary").textContent = `${state.codes.used} utilisé(s) sur ${state.codes.total}.`;
|
||
|
||
renderQuestions();
|
||
}
|
||
|
||
function renderQuestions() {
|
||
const box = $("#questions");
|
||
box.replaceChildren();
|
||
if (!state.questions.length) {
|
||
box.append(h("p", { class: "muted" }, "Aucune question."));
|
||
return;
|
||
}
|
||
const voters = state.voters;
|
||
for (const q of state.questions) {
|
||
const focused = state.poll.focus_qid === q.id;
|
||
const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])];
|
||
if (q.results_public) badges.push(h("span", { class: "badge public" }, "Résultats publiés"));
|
||
if (focused) badges.push(h("span", { class: "focus-mark" }, "● à l'écran"));
|
||
|
||
const actions = [];
|
||
const act = (label, action, cls = "small", confirmMsg) =>
|
||
h("button", {
|
||
class: cls, type: "button",
|
||
onclick: async () => {
|
||
if (confirmMsg && !confirm(confirmMsg)) return;
|
||
try { await call("POST", `/questions/${q.id}/${action}`); } catch (e) { toast(errMsg(e), "bad"); }
|
||
},
|
||
}, label);
|
||
if (q.state === "draft") {
|
||
actions.push(act("Lancer le vote", "open", "small go"));
|
||
actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?"));
|
||
}
|
||
if (q.state === "open") {
|
||
actions.push(act("Clore le vote", "close", "small primary",
|
||
`Clore le vote (${q.participants} votants) ? Définitif.`));
|
||
}
|
||
if (q.state === "closed") {
|
||
actions.push(q.results_public ? act("Masquer les résultats", "unpublish") : act("Publier les résultats", "publish", "small primary"));
|
||
}
|
||
if (q.state !== "draft" && !focused) actions.push(act("Afficher à l'écran", "focus"));
|
||
|
||
const turnout = q.state !== "draft"
|
||
? h("div", {},
|
||
h("div", { class: "q-meta" }, `${q.participants} / ${voters} votants`),
|
||
h("div", { class: "progress" }, fill(pct(q.participants, voters), "")))
|
||
: null;
|
||
|
||
box.append(h("article", { class: `q ${q.state}` },
|
||
h("div", { class: "q-head" }, h("div", {}, badges), h("span", { class: "q-meta" }, `#${q.id}`)),
|
||
h("div", { class: "q-text" }, q.text),
|
||
q.state === "closed" ? resultsView(q) : h("ol", { class: "q-opts" }, q.options.map((o) => h("li", {}, o))),
|
||
h("div", { class: "q-meta" },
|
||
q.kind === "multi" ? `Max ${q.max_choices} choix` : "",
|
||
q.kind === "multi" && q.allow_blank ? ", " : "",
|
||
q.allow_blank ? "blanc possible" : ""),
|
||
turnout,
|
||
h("div", { class: "actions" }, actions),
|
||
));
|
||
}
|
||
}
|
||
|
||
|
||
for (const t of TEMPLATES) {
|
||
$("#templates").append(h("button", {
|
||
class: "small", type: "button",
|
||
onclick: () => {
|
||
$("#q-opts").value = t.opts.join("\n");
|
||
$("#q-blank").checked = t.blank;
|
||
if (t.text && !$("#q-text").value) $("#q-text").value = t.text;
|
||
$("#q-text").focus();
|
||
},
|
||
}, t.label));
|
||
}
|
||
$("#q-kind").addEventListener("change", () => { $("#q-max-box").hidden = $("#q-kind").value !== "multi"; });
|
||
|
||
async function submitQuestion(open) {
|
||
const options = $("#q-opts").value.split("\n").map((s) => s.trim()).filter(Boolean);
|
||
const data = {
|
||
text: $("#q-text").value.trim(),
|
||
options,
|
||
kind: $("#q-kind").value,
|
||
max_choices: +$("#q-max").value || 1,
|
||
allow_blank: $("#q-blank").checked,
|
||
open,
|
||
};
|
||
if (!data.text) return toast("Saisissez la question", "bad");
|
||
if (options.length < 2) return toast("Au moins deux réponses", "bad");
|
||
try {
|
||
await call("POST", "/questions", data);
|
||
$("#q-text").value = "";
|
||
$("#q-opts").value = "";
|
||
toast(open ? "Vote lancé" : "Question préparée", "ok");
|
||
} catch (e) { toast(errMsg(e), "bad"); }
|
||
}
|
||
$("#q-draft").addEventListener("click", () => submitQuestion(false));
|
||
$("#q-push").addEventListener("click", () => submitQuestion(true));
|
||
|
||
|
||
$("#toggle-enroll").addEventListener("click", async () => {
|
||
const open = !state.poll.enrollment_open;
|
||
if (!open && !confirm(`Fermer les inscriptions (${state.voters} inscrits) ?`)) return;
|
||
try { await call("PATCH", "", { enrollment_open: open }); } catch (e) { toast(errMsg(e), "bad"); }
|
||
});
|
||
|
||
for (const id of ["#s-interval", "#s-scans", "#s-expected", "#s-max", "#s-code"]) {
|
||
$(id).addEventListener("input", () => { settingsDirty = true; });
|
||
}
|
||
$("#save-settings").addEventListener("click", async () => {
|
||
try {
|
||
await call("PATCH", "", {
|
||
interval_ms: +$("#s-interval").value,
|
||
scans_required: +$("#s-scans").value,
|
||
expected: $("#s-expected").value ? +$("#s-expected").value : null,
|
||
max_voters: $("#s-max").value ? +$("#s-max").value : null,
|
||
require_code: $("#s-code").checked,
|
||
});
|
||
settingsDirty = false;
|
||
toast("Réglages enregistrés", "ok");
|
||
} catch (e) { toast(errMsg(e), "bad"); }
|
||
});
|
||
|
||
|
||
$("#codes-gen").addEventListener("click", async () => {
|
||
try {
|
||
await call("POST", "/codes", { count: +$("#codes-count").value });
|
||
toast("Codes générés", "ok");
|
||
} catch (e) { toast(errMsg(e), "bad"); }
|
||
});
|
||
$("#codes-print").addEventListener("click", async () => {
|
||
const { codes } = await call("GET", "/codes");
|
||
$("#codes-title").textContent = `Codes d'accès, ${state.poll.title}`;
|
||
$("#codes-grid").replaceChildren(...codes.map((c) => h("div", { class: "code-cell" + (c.used ? " used" : "") }, c.code)));
|
||
$("#codes-sheet").hidden = false;
|
||
$("#codes-sheet").scrollIntoView({ behavior: "smooth" });
|
||
});
|
||
$("#codes-close").addEventListener("click", () => { $("#codes-sheet").hidden = true; });
|
||
$("#codes-do-print").addEventListener("click", () => window.print());
|
||
|
||
|
||
$("#open-screen").href = `/screen/${pid}#${encodeURIComponent(key)}`;
|
||
// the key is hidden from the address bar, so a bookmark would lose it
|
||
$("#copy-admin").addEventListener("click", async () => {
|
||
const link = `${location.origin}/admin/${pid}#${encodeURIComponent(key)}`;
|
||
try { await navigator.clipboard.writeText(link); toast("Lien admin copié"); }
|
||
catch { prompt("Lien admin", link); }
|
||
});
|
||
$("#screen-rotate").addEventListener("click", async () => {
|
||
if (!confirm("Révoquer l'ancien lien projecteur ?")) return;
|
||
try {
|
||
const r = await call("POST", "/screen-key");
|
||
$("#screen-link").value = `${location.origin}/screen/${pid}#${r.screen_key}`;
|
||
$("#screen-link").select();
|
||
} catch (e) { toast(errMsg(e), "bad"); }
|
||
});
|
||
$("#export").addEventListener("click", async () => {
|
||
try {
|
||
const data = await call("GET", "/export");
|
||
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
|
||
const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.json` });
|
||
a.click();
|
||
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
|
||
} catch (e) { toast(errMsg(e), "bad"); }
|
||
});
|
||
|
||
|
||
liveSocket(`/ws/${pid}/admin`, {
|
||
auth: key,
|
||
onMessage(msg) {
|
||
if (msg.type !== "state") return;
|
||
state = msg;
|
||
$("#app").hidden = false;
|
||
$("#denied").hidden = true;
|
||
render();
|
||
},
|
||
onStatus(s) {
|
||
const c = $("#conn");
|
||
if (s.startsWith("denied")) {
|
||
$("#denied").hidden = false;
|
||
c.className = "conn offline";
|
||
c.textContent = "refusé";
|
||
return;
|
||
}
|
||
c.className = `conn ${s}`;
|
||
c.textContent = s === "online" ? "en direct" : "reconnexion…";
|
||
},
|
||
});
|