From c924107f1dee3ee9da892cfc4d1d65ba7d8b0c86 Mon Sep 17 00:00:00 2001 From: Showdown76py Date: Tue, 17 Nov 2026 14:42:54 +0100 Subject: [PATCH] Hand-added votes per question (paper, show of hands): counted in the turnout and shown hatched orange at the end of each result bar, kept apart from phone ballots --- README.md | 2 +- rotatyvote/app.py | 22 +++++++++++++++++++++- rotatyvote/db.py | 13 +++++++++++-- static/admin.html | 14 ++++++++++++++ static/css/admin.css | 15 +++++++++------ static/css/app.css | 8 ++++++++ static/css/screen.css | 2 +- static/js/admin.js | 35 ++++++++++++++++++++++++++++++++--- static/js/common.js | 33 ++++++++++++++++++++++++--------- static/js/screen.js | 27 ++++++++++++++++++--------- tests/test_e2e.py | 25 +++++++++++++++++++++++++ 11 files changed, 164 insertions(+), 32 deletions(-) diff --git a/README.md b/README.md index 25ca8b1..7352311 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,7 @@ location / { 2. Ouvrir les inscriptions. Le projecteur affiche le code dyanmique et le nombre d'inscriptions. 3. Fermer les inscriptions quand tout le monde est inscrit. 4. Lancer les questions préparées ou en créer en direct. Les téléphones les reçoivent en temps réel. -5. Clore, publier les résultats à l'écran. Vous pouvez à la fin, exporter les résultats en JSON. +5. Clore, publier les résultats à l'écran. Les votes comptés à la main (bulletins papier, main levée) s'ajoutent avec « Votes en plus » : ils restent séparés des votes par téléphone et s'affichent en orange hachuré. Vous pouvez à la fin, exporter les résultats en JSON. Avant votre vote, `/essai` lance un scrutin jetable sur l'écran à tester. On vise l'écran avec son téléphone depuis le fond de la salle. Dès la première inscription, une question d'essai s'ouvre pour essayer aussi le vote et ses 3 secondes de confirmation. Personne ne reçoit le lien d'administration, et l'essai est effacé au bout de 2 h, même sans mot de passe de création. diff --git a/rotatyvote/app.py b/rotatyvote/app.py index aff5ab9..960997d 100644 --- a/rotatyvote/app.py +++ b/rotatyvote/app.py @@ -55,6 +55,8 @@ def q_public(q, with_results: bool): "id": q["id"], "text": q["text"], "kind": q["kind"], "options": json.loads(q["options"]), "max_choices": q["max_choices"], "allow_blank": bool(q["allow_blank"]), "state": q["state"], "results_public": bool(q["results_public"]), "shown": bool(q["shown"]), "participants": db.participants(q["id"]), + # how many were added by hand, never how they split while the vote is open + "extra_ballots": db.extra(q)["ballots"], } # nobody, admin included, sees tallies while a question is open if with_results and q["state"] == "closed": @@ -75,7 +77,7 @@ def admin_state(pid): }, "voters": db.voter_count(pid), "codes": codes_summary(pid), - "questions": [q_public(q, True) for q in db.questions(pid)], + "questions": [{**q_public(q, True), "extra": db.extra(q)} for q in db.questions(pid)], "screens": len(hub.screens.get(pid, ())), "public_url": config.PUBLIC_URL, } @@ -533,6 +535,24 @@ async def admin_question_action(request: Request): db.set_question(qid, shown=1) if action == "publish": db.update_poll(pid, focus_qid=qid) + elif action == "extra": + if st == "draft": + return err("not_open") + d = await body(request) + n = len(json.loads(q["options"])) + counts = d.get("counts") + if not isinstance(counts, list) or len(counts) != n: + return err("bad_extra") + counts = [clamp_int(c, 0, 100000, "counts") for c in counts] + blank = clamp_int(d.get("blank", 0), 0, 100000, "blank") if q["allow_blank"] else 0 + # single choice: one ballot per answer. multi: the count of ballots is given (at least the biggest answer) + if q["kind"] == "multi": + ballots = clamp_int(d.get("ballots", max(counts, default=0) + blank), 0, 100000, "ballots") + if ballots < max(counts, default=0) + blank or ballots > sum(counts) + blank: + return err("bad_extra") + else: + ballots = sum(counts) + blank + db.set_question(qid, extra=json.dumps({"counts": counts, "blank": blank, "ballots": ballots})) elif action == "focus": db.update_poll(pid, focus_qid=qid) elif action == "delete": diff --git a/rotatyvote/db.py b/rotatyvote/db.py index dfa9a3d..3659c19 100644 --- a/rotatyvote/db.py +++ b/rotatyvote/db.py @@ -90,6 +90,7 @@ class DB: ("polls", "trial", "INTEGER NOT NULL DEFAULT 0"), ("questions", "shown", "INTEGER NOT NULL DEFAULT 0"), ("polls", "entry_big", "INTEGER NOT NULL DEFAULT 0"), + ("questions", "extra", "TEXT"), ): cols = {r[1] for r in self.c.execute(f"PRAGMA table_info({table})")} if col not in cols: @@ -224,7 +225,7 @@ class DB: return self.all("SELECT * FROM questions WHERE poll_id=? ORDER BY position", pid) def set_question(self, qid, **fields): - allowed = {"state", "results_public", "shown"} + allowed = {"state", "results_public", "shown", "extra"} fields = {k: v for k, v in fields.items() if k in allowed} sets = ",".join(f"{k}=?" for k in fields) self.c.execute(f"UPDATE questions SET {sets} WHERE id=?", (*fields.values(), qid)) @@ -268,7 +269,15 @@ class DB: for i in ch: if 0 <= i < len(counts): counts[i] += 1 - return {"counts": counts, "blank": blank, "ballots": total} + return {"counts": counts, "blank": blank, "ballots": total, "extra": self.extra(q)} + + def extra(self, q): + """votes added by hand (paper, show of hands), kept apart from the phone ballots""" + n = len(json.loads(q["options"])) + e = json.loads(q["extra"]) if q["extra"] else {} + counts = (e.get("counts") or [0] * n)[:n] + [0] * max(0, n - len(e.get("counts") or [])) + blank = e.get("blank", 0) + return {"counts": counts, "blank": blank, "ballots": e.get("ballots", sum(counts) + blank)} def ballots(self, qid): # pk is random so this order is meaningless, which is the point diff --git a/static/admin.html b/static/admin.html index 1174fc3..d09e91c 100644 --- a/static/admin.html +++ b/static/admin.html @@ -131,6 +131,20 @@ + +
+

Votes en plus

+

+
+

Bulletins papier, vote à main levée… Ils s'ajoutent aux votes par téléphone et s'affichent en orange hachuré.

+
+ + + +
+
+
+

Nouvelle question

diff --git a/static/css/admin.css b/static/css/admin.css index f78eb3e..6ddbe0f 100644 --- a/static/css/admin.css +++ b/static/css/admin.css @@ -54,15 +54,18 @@ .share-row > div:first-child { display: grid; } .share-row .muted { font-size: .85rem; } -#composer { border: none; border-radius: 24px; padding: 24px; width: min(94vw, 560px); background: var(--surface); color: var(--ink); } -#composer::backdrop { background: rgba(28, 32, 54, .45); backdrop-filter: blur(2px); } -#composer[open] { animation: rise .2s ease-out; } -#composer h2 { font-size: 1.3rem; } +#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; } .spacer { flex: 1; } @media (max-width: 560px) { .summary-row > * { flex: 1 1 auto; } - #composer .actions button { flex: 1 1 100%; } - #composer .spacer { display: none; } + #composer .actions button, #extra-dlg .actions button { flex: 1 1 100%; } + #composer .spacer, #extra-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; } diff --git a/static/css/app.css b/static/css/app.css index b32ba4a..0753efb 100644 --- a/static/css/app.css +++ b/static/css/app.css @@ -116,6 +116,11 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; } .bar-label { overflow-wrap: anywhere; } .bar-track { height: 12px; background: var(--bg); border-radius: 99px; overflow: hidden; } .bar-fill { height: 100%; background: var(--ink-3); border-radius: 99px; transition: width .6s cubic-bezier(.2, .8, .2, 1); } +/* one bar = phone ballots then hand-added votes, hatched orange */ +.bar-stack { height: 100%; display: flex; border-radius: 99px; overflow: hidden; transition: width .6s cubic-bezier(.2, .8, .2, 1); } +.bar-stack > div { flex: 1 1 0; border-radius: 0; height: 100%; } +.bar-extra, .progress > .p-extra { background: repeating-linear-gradient(-45deg, #f08a24 0 5px, #f9c58f 5px 10px); } +.extra-note { color: #b85e0b; font-weight: 600; } .bar-row.lead .bar-fill { background: var(--mark); } .bar-row.lead .bar-label { font-weight: 700; } .bar-num { font: 700 1rem var(--round); min-width: 80px; text-align: right; } @@ -124,6 +129,9 @@ button:disabled { opacity: .35; cursor: not-allowed; transform: none; } .progress { height: 8px; background: var(--bg); border-radius: 99px; overflow: hidden; margin-top: 6px; } .progress > div { height: 100%; background: var(--ink); border-radius: 99px; transition: width .3s; } +.progress { display: flex; } +.progress > .p-extra { border-radius: 0 99px 99px 0; } +.progress > div:not(:last-child) { border-radius: 99px 0 0 99px; } .ring { display: block; overflow: visible; } .ring .seg, .ring .fill { fill: none; stroke-linecap: round; } diff --git a/static/css/screen.css b/static/css/screen.css index b6b524d..4e923cf 100644 --- a/static/css/screen.css +++ b/static/css/screen.css @@ -134,7 +134,7 @@ body.entry-q-on { --dock-qr: clamp(160px, min(46vh, 30vw), 520px); } #focus.enter :is(.opts li, .bar-row):nth-child(4) { animation-delay: .26s; } #focus.enter :is(.opts li, .bar-row):nth-child(n+5) { animation-delay: .32s; } #focus.enter .turnout, #focus.enter .results-foot, #focus.enter .status { animation: s-in .45s .3s cubic-bezier(.2, .7, .2, 1) both; } -#focus.enter .bar-fill { transform-origin: left; animation: s-grow .9s .25s cubic-bezier(.2, .7, .2, 1) both; } +#focus.enter .bar-stack { transform-origin: left; animation: s-grow .9s .25s cubic-bezier(.2, .7, .2, 1) both; } .turnout .progress > div { transition: width .5s cubic-bezier(.2, .7, .2, 1); } #voters { display: inline-block; } #voters.bump { animation: s-bump .35s ease; } diff --git a/static/js/admin.js b/static/js/admin.js index 6c018c5..127d405 100644 --- a/static/js/admin.js +++ b/static/js/admin.js @@ -116,13 +116,14 @@ function questionCard(q) { 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} vote${q.participants > 1 ? "s" : ""}) ?`)); + 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")); const badges = [h("span", { class: `badge ${q.state}` }, STATE_LABEL[q.state])]; @@ -132,17 +133,45 @@ function questionCard(q) { 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}`) : null), + 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), "")) : 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"); diff --git a/static/js/common.js b/static/js/common.js index 087b801..373fd15 100644 --- a/static/js/common.js +++ b/static/js/common.js @@ -117,23 +117,38 @@ export function fill(percent, cls = "bar-fill") { export function resultsView(q) { const r = q.results; if (!r) return null; - const base = r.ballots - r.blank; - const max = Math.max(1, ...r.counts); - const rows = q.options.map((label, i) => - h("div", { class: "bar-row" + (r.counts[i] === max && r.counts[i] > 0 ? " lead" : "") }, + // 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 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); + 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), - h("div", { class: "bar-track" }, fill(pct(r.counts[i], max))), - h("div", { class: "bar-num" }, r.counts[i], h("small", {}, ` ${pct(r.counts[i], base).toLocaleString("fr-FR")} %`)), - )); + h("div", { class: "bar-track" }, stack), + h("div", { class: "bar-num" }, tot[i], h("small", {}, ` ${pct(tot[i], base).toLocaleString("fr-FR")} %`)), + ); + }); return h("div", { class: "results" }, rows, h("p", { class: "results-foot" }, - `${r.ballots} bulletin${r.ballots > 1 ? "s" : ""}`, - q.allow_blank ? `, dont ${r.blank} blanc${r.blank > 1 ? "s" : ""}` : "", + `${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`) : "", ), ); } +// a flex share of a bar (CSSOM write, the CSP blocks style="") +function seg(cls, n) { + const el = h("div", { class: cls }); + el.style.flexGrow = String(n); + return el; +} + export const STATE_LABEL = { draft: "Brouillon", open: "Vote ouvert", closed: "Clos" }; export function toast(msg, kind = "info") { diff --git a/static/js/screen.js b/static/js/screen.js index f4311d1..b9bcf6a 100644 --- a/static/js/screen.js +++ b/static/js/screen.js @@ -1,4 +1,4 @@ -import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, fill, pct } from "./common.js"; +import { $, h, pollId, takeKey, liveSocket, drawQR, resultsView, pct } from "./common.js"; import { render as drawRing, DISC } from "./ringcode.js"; const pid = pollId(); @@ -80,13 +80,10 @@ function render() { const f = st.focus; const box = $("#focus"); - const view = f ? `${f.id}|${f.state}|${f.results ? 1 : 0}|${f.text}` : ""; + const view = f ? `${f.id}|${f.state}|${f.results ? JSON.stringify(f.results) : 0}|${f.text}` : ""; if (f && view === focusView && f.state === "open") { // same question still open: only the turnout moves, in place so the bar slides - const t = box.querySelector(".turnout"); - t.querySelector("b").textContent = f.participants; - t.querySelector(".t-of").textContent = ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`; - t.querySelector(".progress > div").style.width = `${pct(f.participants, st.voters)}%`; + paintTurnout(box.querySelector(".turnout"), f); } else if (view !== focusView) { focusView = view; if (f) { @@ -95,9 +92,9 @@ function render() { if (f.state === "open") { box.append( h("ul", { class: "opts" }, f.options.map((o) => h("li", {}, o))), - h("div", { class: "turnout" }, - h("b", {}, f.participants), h("span", { class: "t-of" }, ` vote${f.participants > 1 ? "s" : ""} sur ${st.voters}`), - h("div", { class: "progress" }, fill(pct(f.participants, st.voters), ""))), + paintTurnout(h("div", { class: "turnout" }, + h("b", {}), h("span", { class: "t-of" }), + h("div", { class: "progress" }, h("div", {}), h("div", { class: "p-extra" }))), f), ); } else if (f.results) { box.append(resultsView(f)); @@ -110,6 +107,18 @@ function render() { layout(); } +// "9 votes sur 10, dont 3 ajoutés": hand-added votes count in, and show hatched at the end of the bar +function paintTurnout(t, f) { + const extra = f.extra_ballots || 0, all = f.participants + extra, of = st.voters + extra; + t.querySelector("b").textContent = all; + t.querySelector(".t-of").textContent = ` vote${all > 1 ? "s" : ""} sur ${of}` + + (extra ? `, dont ${extra} ajouté${extra > 1 ? "s" : ""}` : ""); + const [phone, added] = t.querySelectorAll(".progress > div"); + phone.style.width = `${pct(f.participants, of)}%`; + added.style.width = `${pct(extra, of)}%`; + return t; +} + function paintQR() { if (!qr || qr.type !== "qr") return; const c = $("#qr"); diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 9834b16..ebd53d2 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -708,3 +708,28 @@ def test_trial_enrolls_then_expires(server): assert con.execute("SELECT COUNT(*) FROM voters WHERE poll_id=?", (p["id"],)).fetchone()[0] == 0 con.close() assert httpx.get(f"{server['base']}/screen/{p['id']}", verify=server["verify"]).status_code == 404 + + +def test_hand_added_votes(server): + p = create(server, vote_scans=0) + admin(server, p, "PATCH", "", json={"enrollment_open": True}) + + async def run(): + async with projector(server, p) as next_token: + a = await enroll(server, p, next_token) + qid = admin(server, p, "POST", "/questions", json={"text": "Q", "options": ["A", "B"], "open": True}).json()["id"] + assert (await a.post(f"/api/v/{p['id']}/vote", json={"question_id": qid, "choices": [0]})).status_code == 200 + # paper ballots counted at the desk + assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [2, 5], "blank": 1}).status_code == 200 + q = admin(server, p, "GET", "").json()["questions"][0] + assert q["extra_ballots"] == 8 and q["extra"] == {"counts": [2, 5], "blank": 1, "ballots": 8} + assert "results" not in q # still open: no tally, hand-added or not + assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [1]}).status_code == 400 + assert admin(server, p, "POST", f"/questions/{qid}/extra", json={"counts": [-1, 0]}).status_code == 400 + admin(server, p, "POST", f"/questions/{qid}/close") + r = admin(server, p, "GET", "").json()["questions"][0]["results"] + # phone ballots and hand-added ones stay apart + assert r["counts"] == [1, 0] and r["ballots"] == 1 and r["extra"]["counts"] == [2, 5] + await a.aclose() + + asyncio.run(run())