From 41b4ac1a78a35cbdc1a4c6142e4a5dd50fd0b475 Mon Sep 17 00:00:00 2001 From: Showdown76py Date: Thu, 19 Nov 2026 01:01:54 +0100 Subject: [PATCH] =?UTF-8?q?Results=20export=20as=20plain=20text:=20proc?= =?UTF-8?q?=C3=A8s-verbal,=20compact,=20liste,=20barres,=20markdown=20and?= =?UTF-8?q?=20csv=20templates=20with=20a=20preview,=20copy=20and=20downloa?= =?UTF-8?q?d,=20from=20the=20share=20tab=20or=20a=20closed=20question;=20t?= =?UTF-8?q?ally=20maths=20shared=20with=20the=20results=20bars?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- static/admin.html | 22 ++++++- static/css/admin.css | 22 +++++-- static/js/admin.js | 67 ++++++++++++++++++++ static/js/common.js | 17 ++--- static/js/export.js | 148 +++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 258 insertions(+), 18 deletions(-) create mode 100644 static/js/export.js diff --git a/static/admin.html b/static/admin.html index bb97022..98c808a 100644 --- a/static/admin.html +++ b/static/admin.html @@ -126,8 +126,11 @@ Ouvrir
-
RésultatsBulletins anonymes et décomptes
- +
RésultatsExporter en texte ou JSON (anonyme)
+
+ + +
@@ -154,6 +157,21 @@ + +
+

Exporter les résultats

+ +
+

+    
+ + + + +
+
+
+

Nouvelle question

diff --git a/static/css/admin.css b/static/css/admin.css index 6ddbe0f..e0a24dd 100644 --- a/static/css/admin.css +++ b/static/css/admin.css @@ -54,18 +54,28 @@ .share-row > div:first-child { display: grid; } .share-row .muted { font-size: .85rem; } -#composer, #extra-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); } -#composer::backdrop, #extra-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); } -#composer[open], #extra-dlg[open] { animation: rise .2s ease-out; } -#composer h2, #extra-dlg h2 { font-size: 1.3rem; } +#composer, #extra-dlg, #export-dlg { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); } +#composer::backdrop, #extra-dlg::backdrop, #export-dlg::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); } +#composer[open], #extra-dlg[open], #export-dlg[open] { animation: rise .2s ease-out; } +#composer h2, #extra-dlg h2, #export-dlg h2 { font-size: 1.3rem; } .spacer { flex: 1; } @media (max-width: 560px) { .summary-row > * { flex: 1 1 auto; } - #composer .actions button, #extra-dlg .actions button { flex: 1 1 100%; } - #composer .spacer, #extra-dlg .spacer { display: none; } + #composer .actions button, #extra-dlg .actions button, #export-dlg .actions button { flex: 1 1 100%; } + #composer .spacer, #extra-dlg .spacer, #export-dlg .spacer { display: none; } } #q-opts { min-height: 132px; } .extra-row { margin: 8px 0; display: grid; grid-template-columns: 1fr 110px; gap: 12px; align-items: center; font-weight: 600; } .extra-row input { text-align: right; } + +#export-dlg { width: min(94vw, 720px); } +#ex-scope { margin-bottom: 12px; } +#ex-scope[hidden] { display: none; } +#ex-formats button[aria-checked="true"] { background: var(--mark); border-color: var(--mark); color: var(--ink); } +#ex-preview { + margin: 12px 0 0; padding: 14px 16px; max-height: 50vh; overflow: auto; background: var(--bg); border-radius: var(--r-field); + font: .82rem/1.5 ui-monospace, "SF Mono", Menlo, Consolas, monospace; white-space: pre; tab-size: 4; +} +#ex-preview.empty { white-space: normal; color: var(--ink-3); font-family: var(--sans); text-align: center; padding: 32px 16px; } diff --git a/static/js/admin.js b/static/js/admin.js index ce8f764..601e51a 100644 --- a/static/js/admin.js +++ b/static/js/admin.js @@ -1,9 +1,11 @@ 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 = [ @@ -127,6 +129,7 @@ function questionCard(q) { 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 === "closed") actions.push(h("button", { class: "small", type: "button", onclick: () => openExport(q.id) }, "Exporter")); if (q.state !== "draft" && !focused) actions.push(act([icon("screen", 15), "Afficher à l'écran"], "focus")); const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])]; @@ -303,6 +306,70 @@ $("#export").addEventListener("click", async () => { } catch (e) { toast(errMsg(e), "bad"); } }); +// 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) { diff --git a/static/js/common.js b/static/js/common.js index 90ca516..d4c1dfc 100644 --- a/static/js/common.js +++ b/static/js/common.js @@ -1,3 +1,6 @@ +import { tally, pct } from "./export.js"; + +export { pct }; export const $ = (sel, root = document) => root.querySelector(sel); // tiny element builder, children are always text nodes or elements so no html injection @@ -103,9 +106,6 @@ export function drawQR(canvas, modules, px) { } } -export function pct(n, d) { - return d ? Math.round((n / d) * 1000) / 10 : 0; -} // CSSOM write, a style="" attribute would be blocked by the CSP export function fill(percent, cls = "bar-fill") { @@ -115,16 +115,13 @@ export function fill(percent, cls = "bar-fill") { } export function resultsView(q) { - const r = q.results; - if (!r) return null; + if (!q.results) return null; // votes added by hand ride at the end of each bar, hatched orange, so nobody mistakes them for phone ballots - const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 }; - const tot = r.counts.map((c, i) => c + (ex.counts[i] || 0)); - const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank, base = ballots - blank; + const { phone, extra, tot, ballots, blank, base, exBallots } = tally(q); const max = Math.max(1, ...tot); const rows = q.options.map((label, i) => { const stack = h("div", { class: "bar-stack" }, - seg("bar-fill", r.counts[i]), ex.counts[i] ? seg("bar-extra", ex.counts[i]) : null); + seg("bar-fill", phone[i]), extra[i] ? seg("bar-extra", extra[i]) : null); stack.style.width = `${pct(tot[i], max)}%`; return h("div", { class: "bar-row" + (tot[i] === max && tot[i] > 0 ? " lead" : "") }, h("div", { class: "bar-label" }, label), @@ -137,7 +134,7 @@ export function resultsView(q) { h("p", { class: "results-foot" }, `${ballots} bulletin${ballots > 1 ? "s" : ""}`, q.allow_blank ? `, dont ${blank} blanc${blank > 1 ? "s" : ""}` : "", - ex.ballots ? h("span", { class: "extra-note" }, `, dont ${ex.ballots} ajouté${ex.ballots > 1 ? "s" : ""} à la main`) : "", + exBallots ? h("span", { class: "extra-note" }, `, dont ${exBallots} ajouté${exBallots > 1 ? "s" : ""} à la main`) : "", ), ); } diff --git a/static/js/export.js b/static/js/export.js new file mode 100644 index 0000000..d188acb --- /dev/null +++ b/static/js/export.js @@ -0,0 +1,148 @@ +// plain text results export, pure functions (no dom) so node can run them too + +export function tally(q) { + const r = q.results; + const ex = r.extra || { counts: r.counts.map(() => 0), blank: 0, ballots: 0 }; + const extra = r.counts.map((_, i) => ex.counts[i] || 0); + const tot = r.counts.map((c, i) => c + extra[i]); + const ballots = r.ballots + ex.ballots, blank = r.blank + ex.blank; + return { phone: r.counts, extra, tot, ballots, blank, base: ballots - blank, exBallots: ex.ballots, exBlank: ex.blank }; +} + +export function pct(n, d) { + return d ? Math.round((n / d) * 1000) / 10 : 0; +} + +// fr-FR toLocaleString puts a narrow nbsp in thousands, which breaks column alignment +const num = (n) => String(n).replace(".", ","); +const pctTxt = (n, d) => `${num(pct(n, d))} %`; +const plural = (n, word) => `${n} ${word}${n > 1 ? "s" : ""}`; + +function foot(q, t) { + let s = plural(t.ballots, "bulletin"); + if (q.allow_blank) s += `, dont ${plural(t.blank, "blanc")}`; + if (t.exBallots) s += `, dont ${t.exBallots} ajouté${t.exBallots > 1 ? "s" : ""} à la main`; + return s; +} + +const nb = (qs, k) => (qs.length > 1 ? `${k + 1}. ` : ""); +const kindNote = (q) => (q.kind === "multi" ? `Choix multiple, ${q.max_choices} max` : ""); + +function header(poll, voters, now) { + return [poll.title, `Résultats du ${now} · ${plural(voters, "inscription")}`]; +} + +// visible length, emoji and accents count as one column +const width = (s) => [...s].length; +const padEnd = (s, n) => s + " ".repeat(Math.max(0, n - width(s))); +const padStart = (s, n) => " ".repeat(Math.max(0, n - width(s))) + s; + +function rows(q, t) { + const out = q.options.map((label, i) => ({ label, n: t.tot[i], p: pctTxt(t.tot[i], t.base) })); + if (q.allow_blank) out.push({ label: "Blanc", n: t.blank, p: "" }); + return out; +} + +function minutes(poll, voters, qs, now) { + const out = [...header(poll, voters, now)]; + qs.forEach((q, k) => { + const t = tally(q), rs = rows(q, t); + const lw = Math.max(...rs.map((r) => width(r.label))); + const nw = Math.max(...rs.map((r) => String(r.n).length)); + out.push("", `${nb(qs, k)}${q.text}`); + if (kindNote(q)) out.push(` ${kindNote(q)}`); + for (const r of rs) out.push(` ${padEnd(r.label, lw)} ${padStart(String(r.n), nw)} ${padStart(r.p, 7)}`.trimEnd()); + out.push(` ${foot(q, t)}`); + }); + return out.join("\n"); +} + +// no column alignment, survives a paste in an email or a chat +function compact(poll, voters, qs) { + const out = [poll.title]; + for (const q of qs) { + const t = tally(q); + const parts = rows(q, t).map((r) => (r.p ? `${r.label} ${r.n} (${r.p})` : `${r.label} ${r.n}`)); + out.push("", q.text + (kindNote(q) ? ` (${kindNote(q).toLowerCase()})` : ""), + `${parts.join(" · ")} · ${plural(t.ballots, "bulletin")}`); + } + return out.join("\n"); +} + +// the long npppav label would eat the whole line +const SHORT = { "ne prend pas part au vote": "NPPPAV" }; + +function list(poll, voters, qs) { + const out = [poll.title]; + for (const q of qs) { + const t = tally(q); + const parts = rows(q, t).map((r) => `${SHORT[r.label.toLowerCase()] || r.label} (${r.n})`); + out.push("", `${q.text} [${plural(t.ballots, "bulletin")}]`, parts.join(" / ")); + } + return out.join("\n"); +} + +function bars(poll, voters, qs) { + const out = [poll.title]; + const W = 20; + for (const q of qs) { + const t = tally(q), rs = rows(q, t); + const lw = Math.max(...rs.map((r) => width(r.label))); + out.push("", q.text); + for (const r of rs) { + const full = Math.round((t.base ? r.n / t.base : 0) * W); + const bar = r.p ? "█".repeat(Math.min(W, full)) + "░".repeat(Math.max(0, W - full)) : " ".repeat(W); + out.push(`${padEnd(r.label, lw)} ${bar} ${r.n}${r.p ? ` · ${r.p}` : ""}`); + } + out.push(foot(q, t)); + } + return out.join("\n"); +} + +const mdCell = (s) => String(s).replace(/\|/g, "\\|"); + +function markdown(poll, voters, qs, now) { + const [title, sub] = header(poll, voters, now); + const out = [`# ${mdCell(title)}`, "", sub]; + qs.forEach((q, k) => { + const t = tally(q); + out.push("", `## ${nb(qs, k)}${q.text}`, ""); + if (kindNote(q)) out.push(`*${kindNote(q)}*`, ""); + out.push("| Réponse | Voix | % |", "| --- | ---: | ---: |"); + for (const r of rows(q, t)) out.push(`| ${mdCell(r.label)} | ${r.n} | ${r.p} |`); + out.push("", `${foot(q, t)}.`); + }); + return out.join("\n"); +} + +// semicolons, the decimal comma makes plain commas ambiguous in french spreadsheets +const csvCell = (v) => { + const s = String(v); + return /[;"\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s; +}; + +function csv(poll, voters, qs) { + const out = [["n", "question", "réponse", "voix", "dont ajoutées", "% exprimés"]]; + qs.forEach((q, k) => { + const t = tally(q); + q.options.forEach((o, i) => out.push([k + 1, q.text, o, t.tot[i], t.extra[i], num(pct(t.tot[i], t.base))])); + if (q.allow_blank) out.push([k + 1, q.text, "Blanc", t.blank, t.exBlank, ""]); + out.push([k + 1, q.text, "Bulletins", t.ballots, t.exBallots, ""]); + }); + return out.map((r) => r.map(csvCell).join(";")).join("\n"); +} + +export const FORMATS = [ + { id: "pv", label: "Procès-verbal", ext: "txt", mime: "text/plain", build: minutes }, + { id: "compact", label: "Compact", ext: "txt", mime: "text/plain", build: compact }, + { id: "list", label: "Liste", ext: "txt", mime: "text/plain", build: list }, + { id: "bars", label: "Barres", ext: "txt", mime: "text/plain", build: bars }, + { id: "md", label: "Markdown", ext: "md", mime: "text/markdown", build: markdown }, + { id: "csv", label: "CSV", ext: "csv", mime: "text/csv", build: csv }, +]; + +// closed questions only (nobody sees open tallies), in the order they were asked +export function exportText(fmt, poll, voters, questions, now) { + const qs = questions.filter((q) => q.state === "closed" && q.results).sort((a, b) => a.id - b.id); + return fmt.build(poll, voters, qs, now); +}