import { $, h, api, pollId, takeKey, liveSocket, resultsView, STATE_LABEL, toast, fill, pct, icon } from "./common.js"; import { FORMATS, exportText } from "./export.js"; const pid = pollId(); const key = takeKey(`rv_admin_${pid}`); const base = `/api/polls/${pid}`; const TAB_KEY = "rv_admin_tab"; const FMT_KEY = "rv_export_fmt"; let state = null; const TEMPLATES = [ { label: "Pour / Contre / Abst. / NPPPAV", opts: ["Pour", "Contre", "Abstention", "Ne prend pas part au vote"], blank: false }, { label: "Pour / Contre / Abstention", opts: ["Pour", "Contre", "Abstention"], blank: false }, { label: "Oui / Non", opts: ["Oui", "Non"], blank: true }, { label: "Élection", opts: ["Candidat·e A", "Candidat·e B", "Candidat·e C"], blank: true, text: "Élection : " }, { label: "Note 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", already_shown: "Résultats déjà publiés, le vote ne peut plus être rouvert", }; return m[e.code] || e.message; } function showTab(name) { for (const b of document.querySelectorAll("[data-tab]")) b.setAttribute("aria-selected", String(b.dataset.tab === name)); for (const p of document.querySelectorAll("[data-panel]")) p.hidden = p.dataset.panel !== name; try { localStorage.setItem(TAB_KEY, name); } catch { /* private mode */ } } for (const b of document.querySelectorAll("[data-tab]")) b.addEventListener("click", () => showTab(b.dataset.tab)); let initialTab = "questions"; try { initialTab = localStorage.getItem(TAB_KEY) || "questions"; } catch { /* private mode */ } showTab(initialTab); function render() { const p = state.poll; $("#title").textContent = p.title; document.title = `Admin · ${p.title}`; $("#voters").textContent = state.voters; $("#voters-of").textContent = `inscription${state.voters > 1 ? "s" : ""}` + (p.expected ? ` sur ${p.expected}` : ""); const over = p.expected && state.voters > p.expected; $("#over").hidden = !over; if (over) $("#over").textContent = `Plus d'inscriptions que de personnes attendues (${state.voters} pour ${p.expected}).`; const tb = $("#toggle-enroll"); // the switch itself carries the state, no status wording tb.replaceChildren(h("span", { class: "switch", "aria-hidden": "true" }), "Inscriptions"); tb.className = "enroll-toggle " + (p.enrollment_open ? "on" : "off"); tb.setAttribute("role", "switch"); tb.setAttribute("aria-checked", String(p.enrollment_open)); $("#open-screen").classList.toggle("connected", state.screens > 0); $("#open-screen").title = state.screens ? "Projecteur connecté" : "Aucun projecteur connecté"; const open = state.questions.filter((q) => q.state === "open").length; $("#open-count").hidden = !open; $("#open-count").textContent = open; renderSettings(p); renderQuestions(); renderShare(p); } function renderSettings(p) { // never overwrite a field the admin is typing in const active = document.activeElement; const sel = $("#s-interval"); if (![...sel.options].some((o) => +o.value === p.interval_ms)) { sel.append(h("option", { value: p.interval_ms }, `${(p.interval_ms / 1000).toLocaleString("fr-FR")} s`)); } if (active !== sel) sel.value = String(p.interval_ms); if (active !== $("#s-scans")) $("#s-scans").value = p.scans_required; if (active !== $("#s-expected")) $("#s-expected").value = p.expected ?? ""; if (active !== $("#s-max")) $("#s-max").value = p.max_voters ?? ""; if (active !== $("#s-vote-scans")) $("#s-vote-scans").value = String(p.vote_scans); if (active !== $("#s-code-style")) $("#s-code-style").value = p.code_style; if (active !== $("#s-entry-big")) $("#s-entry-big").value = p.entry_big ? "1" : "0"; $("#s-entry-big").disabled = p.code_style !== "ring"; if (active !== $("#s-camera")) $("#s-camera").value = p.camera_pass ? "1" : "0"; // the classic qr is the camera app code itself $("#s-camera").disabled = p.code_style !== "ring"; $("#s-code").checked = p.require_code; $("#access-row").hidden = !p.require_code && !state.codes.access.total; const sum = (c, none) => (c.total ? `${c.used} utilisé${c.used > 1 ? "s" : ""} sur ${c.total}` : none); $("#access-summary").textContent = sum(state.codes.access, "Un code par personne, avec le scan"); $("#rescue-summary").textContent = sum(state.codes.rescue, "Inscription sans caméra"); } function renderQuestions() { const box = $("#questions"); box.replaceChildren(); if (!state.questions.length) { box.append(h("p", { class: "empty" }, "Aucune question pour l'instant.")); return; } // the open vote first, then newest first: a question just created or just closed stays at the top const qs = [...state.questions].sort((a, b) => (b.state === "open") - (a.state === "open") || b.id - a.id); for (const q of qs) box.append(questionCard(q)); } function questionCard(q) { const voters = state.voters; const focused = state.poll.focus_qid === q.id; 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); const actions = []; if (q.state === "draft") { actions.push(act("Lancer le vote", "open", "small go")); actions.push(act("Supprimer", "delete", "small danger", "Supprimer ce brouillon ?")); } else if (q.state === "open") { actions.push(act("Clore le vote", "close", "small primary", `Clore le vote (${q.participants + q.extra_ballots} vote${q.participants + q.extra_ballots > 1 ? "s" : ""}) ?`)); } else { actions.push(q.results_public ? act("Masquer les résultats", "unpublish") : act("Publier les résultats", "publish", "small primary", "Publier les résultats ? Le vote ne pourra plus être rouvert.")); if (!q.shown) actions.push(act("Rouvrir le vote", "reopen")); } if (q.state !== "draft") actions.push(h("button", { class: "small", type: "button", onclick: () => editExtra(q) }, "Votes en plus")); if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus")); if (q.state === "closed") { actions.push(h("button", { class: "small copy-btn", type: "button", title: "Exporter les résultats", "aria-label": "Exporter les résultats", onclick: () => openExport(q.id), }, icon("copy", 16))); } const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])]; if (q.results_public) badges.push(h("span", { class: "badge public" }, "Publiés")); if (q.shared && state.poll.share_key) badges.push(h("span", { class: "badge public" }, "Partagés")); if (focused) badges.push(h("span", { class: "focus-mark" }, icon("screen", 14), "À l'écran")); if (q.kind === "multi") badges.push(h("span", { class: "badge" }, `${q.max_choices} choix max`)); return h("article", { class: `q ${q.state}` }, h("div", { class: "q-head" }, h("div", {}, badges), q.state !== "draft" ? h("span", { class: "q-meta" }, `${q.participants} / ${voters}`, q.extra_ballots ? h("span", { class: "extra-note" }, ` + ${q.extra_ballots}`) : null) : null), h("div", { class: "q-text" }, q.text), q.state === "closed" ? resultsView(q) : h("div", { class: "chips" }, q.options.map((o) => h("span", { class: "chip" }, o)), q.allow_blank ? h("span", { class: "chip ghost" }, "Blanc") : null), q.state === "open" ? h("div", { class: "progress" }, fill(pct(q.participants, voters + q.extra_ballots), ""), q.extra_ballots ? fill(pct(q.extra_ballots, voters + q.extra_ballots), "p-extra") : null) : null, h("div", { class: "actions" }, actions), ); } // votes added by hand, in a dialog: the question list re-renders on every incoming vote async function editExtra(q) { const dlg = $("#extra-dlg"), e = q.extra, inputs = []; const field = (label, value) => { const inp = h("input", { type: "number", min: 0, max: 100000, value: String(value), inputmode: "numeric" }); inputs.push(inp); return h("label", { class: "extra-row" }, h("span", {}, label), inp); }; $("#extra-q").textContent = q.text; $("#extra-fields").replaceChildren(...[ ...q.options.map((o, i) => field(o, e.counts[i] || 0)), q.allow_blank ? field("Blanc", e.blank) : null, q.kind === "multi" ? field("Bulletins (choix multiple)", e.ballots) : null, ].filter(Boolean)); dlg.returnValue = ""; dlg.showModal(); await new Promise((res) => dlg.addEventListener("close", res, { once: true })); if (dlg.returnValue !== "ok") return; const vals = inputs.map((i) => Math.max(0, Math.floor(+i.value || 0))); const n = q.options.length; const payload = { counts: vals.slice(0, n), blank: q.allow_blank ? vals[n] : 0 }; if (q.kind === "multi") payload.ballots = vals[vals.length - 1]; try { await call("POST", `/questions/${q.id}/extra`, payload); toast("Votes ajoutés", "ok"); } catch (err) { toast(err.code === "bad_extra" ? "Nombre de bulletins incohérent" : errMsg(err), "bad"); } } // composer const composer = $("#composer"); function applyTemplate(t) { $("#q-opts").value = t.opts.join("\n"); $("#q-blank").checked = t.blank; if (t.text && !$("#q-text").value) $("#q-text").value = t.text; } $("#new-q").addEventListener("click", () => { // the first template is the default answer set if (!$("#q-opts").value.trim()) applyTemplate(TEMPLATES[0]); composer.showModal(); $("#q-text").focus(); }); for (const t of TEMPLATES) { $("#templates").append(h("button", { class: "small", type: "button", onclick: () => { applyTemplate(t); $("#q-text").focus(); }, }, t.label)); } $("#q-cancel").addEventListener("click", () => composer.close()); // enter in a field must not submit (and close) the dialog $("#q-form").addEventListener("submit", (e) => e.preventDefault()); $("#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-form").reset(); $("#q-max-box").hidden = true; composer.close(); showTab("questions"); toast(open ? "Vote lancé" : "Brouillon enregistré"); } catch (e) { toast(errMsg(e), "bad"); } } $("#q-draft").addEventListener("click", () => submitQuestion(false)); $("#q-push").addEventListener("click", () => submitQuestion(true)); // enrollment + settings, saved as soon as a field changes $("#toggle-enroll").addEventListener("click", async () => { const open = !state.poll.enrollment_open; if (!open && !confirm(`Fermer les inscriptions (${state.voters} inscription${state.voters > 1 ? "s" : ""}) ?`)) return; try { await call("PATCH", "", { enrollment_open: open }); } catch (e) { toast(errMsg(e), "bad"); } }); const intOrNull = (v) => (v ? +v : null); const SETTINGS = { "#s-interval": (el) => ({ interval_ms: +el.value }), "#s-scans": (el) => ({ scans_required: +el.value }), "#s-expected": (el) => ({ expected: intOrNull(el.value) }), "#s-max": (el) => ({ max_voters: intOrNull(el.value) }), "#s-code": (el) => ({ require_code: el.checked }), "#s-vote-scans": (el) => ({ vote_scans: +el.value }), "#s-code-style": (el) => ({ code_style: el.value }), "#s-entry-big": (el) => ({ entry_big: el.value === "1" }), "#s-camera": (el) => ({ camera_pass: el.value === "1" }), }; for (const [sel, build] of Object.entries(SETTINGS)) { $(sel).addEventListener("change", async (e) => { try { await call("PATCH", "", build(e.target)); toast("Enregistré"); } catch (err) { toast(errMsg(err), "bad"); } }); } const CODE_LABEL = { access: "Codes papier", rescue: "Codes de secours" }; for (const b of document.querySelectorAll("[data-gen]")) { b.addEventListener("click", async () => { const kind = b.dataset.gen; try { await call("POST", "/codes", { count: +$(`#${kind}-count`).value, rescue: kind === "rescue" }); toast(`${CODE_LABEL[kind]} générés`); } catch (e) { toast(errMsg(e), "bad"); } }); } for (const b of document.querySelectorAll("[data-print]")) { b.addEventListener("click", async () => { const kind = b.dataset.print; const { codes } = await call("GET", "/codes"); const list = codes.filter((c) => Boolean(c.rescue) === (kind === "rescue")); $("#codes-title").textContent = `${CODE_LABEL[kind]}, ${state.poll.title}`; $("#codes-grid").replaceChildren(...list.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()); // sharing $("#open-screen").href = `/screen/${pid}#${encodeURIComponent(key)}`; $("#screen-icon").replaceWith(icon("screen", 16)); async function copy(text, label) { try { await navigator.clipboard.writeText(text); toast(`${label} copié`); } catch { prompt(label, text); } } // the key is hidden from the address bar, so a bookmark would lose it $("#copy-admin").addEventListener("click", () => copy(`${location.origin}/admin/${pid}#${encodeURIComponent(key)}`, "Lien admin")); $("#screen-rotate").addEventListener("click", async () => { if (!confirm("Créer un nouveau lien projecteur ? L'ancien cessera de fonctionner.")) return; try { const r = await call("POST", "/screen-key"); await copy(`${location.origin}/screen/${pid}#${r.screen_key}`, "Lien projecteur"); } 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"); } }); // read-only results link, the admin ticks which closed questions it shows const shareUrl = (k) => `${location.origin}/r/${pid}#${k}`; function renderShare(p) { const btn = (label, onclick, cls = "small") => h("button", { class: cls, type: "button", onclick }, label); const rotate = async (msg) => { if (msg && !confirm(msg)) return; try { const r = await call("POST", "/share-key"); await copy(shareUrl(r.share_key), "Lien des résultats"); } catch (e) { toast(errMsg(e), "bad"); } }; const off = async () => { if (!confirm("Désactiver le lien des résultats ?")) return; try { await call("DELETE", "/share-key"); } catch (e) { toast(errMsg(e), "bad"); } }; const closed = state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id); const n = closed.filter((q) => q.shared).length; $("#share-summary").textContent = p.share_key ? `${n} question${n > 1 ? "s" : ""} visible${n > 1 ? "s" : ""}` : "Lecture seule"; $("#share-actions").replaceChildren(...(p.share_key ? [btn("Copier", () => copy(shareUrl(p.share_key), "Lien des résultats")), btn("Nouveau lien", () => rotate("Créer un nouveau lien ? L'ancien cessera de fonctionner.")), btn("Désactiver", off, "small danger")] : [btn("Créer", () => rotate())])); if (!p.share_key) return $("#share-qs").replaceChildren(); $("#share-qs").replaceChildren(...(closed.length ? closed.map((q) => h("label", { class: "share-q" }, h("input", { type: "checkbox", checked: q.shared, onchange: async (e) => { const on = e.target.checked; if (on && !q.shown && !confirm("Partager ces résultats ? Le vote ne pourra plus être rouvert.")) { e.target.checked = false; return; } try { await call("POST", `/questions/${q.id}/${on ? "share" : "unshare"}`); } catch (err) { e.target.checked = !on; toast(errMsg(err), "bad"); } }, }), h("span", {}, q.text))) : [h("p", { class: "muted share-none" }, "Aucune question close.")])); } // text export, built in the browser from the closed tallies the socket already sends const exDlg = $("#export-dlg"); let fmt = FORMATS[0]; try { fmt = FORMATS.find((f) => f.id === localStorage.getItem(FMT_KEY)) || fmt; } catch { /* private mode */ } let exText = ""; for (const f of FORMATS) { $("#ex-formats").append(h("button", { class: "small", type: "button", role: "radio", dataset: { fmt: f.id }, onclick: () => { fmt = f; try { localStorage.setItem(FMT_KEY, f.id); } catch { /* private mode */ } renderExport(); }, }, f.label)); } function closedQuestions() { return state.questions.filter((q) => q.state === "closed").sort((a, b) => a.id - b.id); } function renderExport() { for (const b of $("#ex-formats").children) b.setAttribute("aria-checked", String(b.dataset.fmt === fmt.id)); const scope = $("#ex-scope").value; const qs = closedQuestions().filter((q) => scope === "all" || String(q.id) === scope); const now = new Date().toLocaleString("fr-FR", { dateStyle: "long", timeStyle: "short" }); exText = qs.length ? exportText(fmt, state.poll, state.voters, qs, now) : ""; const pre = $("#ex-preview"); pre.classList.toggle("empty", !exText); pre.textContent = exText || "Aucune question close."; $("#ex-copy").disabled = $("#ex-download").disabled = !exText; } function openExport(qid = "all") { const qs = closedQuestions(); const sel = $("#ex-scope"); sel.replaceChildren(h("option", { value: "all" }, "Toutes les questions closes"), ...qs.map((q) => h("option", { value: String(q.id) }, q.text))); sel.value = String(qid); sel.hidden = qs.length < 2; renderExport(); exDlg.showModal(); } $("#ex-scope").addEventListener("change", renderExport); $("#export-text").addEventListener("click", () => openExport()); $("#ex-copy").addEventListener("click", async () => { try { await navigator.clipboard.writeText(exText); toast("Copié"); } catch { // prompt() would flatten the lines, select the preview so cmd+c works getSelection().selectAllChildren($("#ex-preview")); toast("Texte sélectionné"); } }); $("#ex-download").addEventListener("click", () => { // bom so excel reads the accents in the csv const body = fmt.ext === "csv" ? "\ufeff" + exText : exText; const blob = new Blob([body], { type: `${fmt.mime};charset=utf-8` }); const a = h("a", { href: URL.createObjectURL(blob), download: `rotatyvote-${pid}.${fmt.ext}` }); a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000); }); 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.hidden = s === "online"; c.className = "conn offline"; c.textContent = "Reconnexion…"; }, }); // duplicated screen: the projector view with this admin in a drawer, same admin key $("#open-present").href = `/present/${pid}#${encodeURIComponent(key)}`;