A6: public home with the six states, confirmed prize, countdown and polling (WEB-05, WEB-10, WEB-11, WEB-14; LIM-24, WEB-55)

public_state() feeds both the server-rendered home (works without JavaScript)
and GET /stato/, so they cannot disagree: none, open, closing, drawing, paying
and maintenance, the round's own quota, the winner's 70% of the *confirmed*
pool, bets in flight apart, and the closing time on the server's clock. home.js
counts down against the server clock and polls every 5 s while visible. Checked
in headless Chromium on mobile and desktop widths. Also records the profile
reports (WEB-55, roadmap A9) and the name-lock trade-off (LIM-24).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 14:19:56 +01:00
1 parent efb3e2e702
commit 939c113043
16 files changed
+627 -11

No files matched your search

+2 -2
View File
@@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status
All 10 stages of the original build order are code-complete and unit-tested — 992 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below.
All 10 stages of the original build order are code-complete and unit-tested — 1041 tests, the old stack's under `tests/unit/` and the Django ones under `tests/django/` (`tests/integration/` is an empty package). Beyond them: Docker + Caddy deployment, admin dashboard (`/admin`), static test UI (`/`), pending-inclusive balance display, an SSE push channel layered over the original polling, self-service password change + admin password reset, and the reconciliation/corroboration machinery below.
Verified on mainnet with real money: registration + address derivation, deposit crediting (at the time, 1-conf; deposits now need `deposit_confirmations`), a real 10 PLM bet (broadcast → confirmed → change credited back), and one full round cycle (close → draw on a real block hash → 70/30 payout with sat math checked against the broadcast tx → confirmation → close → next round auto-opened). **Withdrawal and the RBF bump path have never been exercised against a live broadcast** — unit-tested only.
@@ -61,7 +61,7 @@ PYTHONPATH=. python scripts/decrypt_master_key.py # ops recovery: decrypt+pr
PYTHONPATH=. python scripts/encrypt_master_key.py # ops bootstrap: import an externally-generated xprv (--overwrite to replace)
PYTHONPATH=. python scripts/electrum_smoke_test.py # manual check: connect, handshake, subscribe to headers, print the tip
python -m pytest # all 992 tests
python -m pytest # all 1041 tests
python -m pytest tests/unit/test_hd.py # one file
python -m pytest tests/unit/test_hd.py::test_derivation_is_deterministic # one test
```
+1 -1
View File
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
992 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
1041 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
deposits, withdrawals, the round/draw engine, RBF fee-bumping, admin config,
the pending-inclusive balance calculation, and the SSE push channel. No
automated integration tests against a live Electrum connection — mainnet
+13
View File
@@ -0,0 +1,13 @@
"""Amounts for people: integer satoshi in, Italian text out (1 PLM = 100,000,000 sat)."""
from .models import SATS_PER_PLM
def plm_text(sats: int) -> str:
"""`1000000000` -> `10 PLM`, `70000000` -> `0,7 PLM`, `123450000000` -> `1.234,5 PLM`. Never rounds: the decimals shown
are exactly the satoshi that exist."""
whole, fraction = divmod(abs(int(sats)), SATS_PER_PLM)
text = f"{whole:,}".replace(",", ".")
if fraction:
text += "," + f"{fraction:08d}".rstrip("0")
return f"{'-' if sats < 0 else ''}{text} PLM"
+103
View File
@@ -0,0 +1,103 @@
"""What a visitor sees of the lottery right now (WEB-10): one of six states, the quota, the confirmed prize
and the closing time. The same function feeds the page when it is rendered and the endpoint the page polls,
so the two can never tell different stories (WEB-05)."""
from datetime import datetime, timedelta, timezone as dt_timezone
from typing import Any
from django.db.models import Count, Sum
from django.utils import timezone
from .format import plm_text
from .lifecycle import get_active_round
from .models import LotteryConfig, Participation, Round
from .rules import round_deadline, winner_share
NONE, OPEN, CLOSING, DRAWING, PAYING, MAINTENANCE = "none", "open", "closing", "drawing", "paying", "maintenance"
LABELS = {
NONE: "Nessun round in corso",
OPEN: "Puntate aperte",
CLOSING: "In chiusura",
DRAWING: "Estrazione in corso",
PAYING: "Pagamento in attesa",
MAINTENANCE: "Manutenzione",
}
def iso(moment: datetime) -> str:
return moment.astimezone(dt_timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
def clock_text(moment: datetime) -> str:
return moment.astimezone(dt_timezone.utc).strftime("%H:%M:%S") + " UTC"
def countdown_text(total_seconds: float) -> str:
"""`mm:ss`, or `h:mm:ss` from one hour up — the same text `home.js` writes, so the page reads the same with and
without JavaScript."""
seconds = max(0, int(total_seconds))
hours, minutes, secs = seconds // 3600, seconds % 3600 // 60, seconds % 60
return f"{hours}:{minutes:02d}:{secs:02d}" if hours else f"{minutes:02d}:{secs:02d}"
def public_state(now: datetime | None = None) -> dict[str, Any]:
now = now or timezone.now()
config = LotteryConfig.get()
round_ = get_active_round()
data: dict[str, Any] = {
"server_now": iso(now), "round_id": None, "closes_at": None, "closes_at_text": "", "seconds_left": None, "countdown_text": "",
"bet_amount_sats": config.bet_amount_sats, "bet_amount_text": plm_text(config.bet_amount_sats),
"jackpot_sats": 0, "jackpot_text": plm_text(0), "confirmed_players": 0, "pending_players": 0,
"paused_after_round": config.pause_after_round, "next_round_at": None, "next_round_at_text": "",
}
if round_ is None:
return _without_round(data, config, now)
totals = Participation.objects.filter(round=round_, status=Participation.Status.CONFIRMED).aggregate(
players=Count("id"), pool=Sum("bet_amount_sats"))
confirmed_pool = totals["pool"] or 0
deadline = round_deadline(round_)
data.update(
round_id=round_.pk,
bet_amount_sats=round_.bet_amount_sats, bet_amount_text=plm_text(round_.bet_amount_sats), # the round's own quota
confirmed_players=totals["players"] or 0,
pending_players=Participation.objects.filter(round=round_, status=Participation.Status.PENDING).count(),
# "Confirmed prize": the winner's share of what is already confirmed — never more than will be paid (B-11, B-65).
jackpot_sats=winner_share(confirmed_pool), jackpot_text=plm_text(winner_share(confirmed_pool)),
)
if round_.status == Round.Status.OPEN and now < deadline:
if config.new_bets_suspended: # ADR-57: «Sospendi nuove puntate»
return _finish(data, MAINTENANCE, "Le nuove puntate sono sospese. Le puntate già inviate restano valide.")
data.update(closes_at=iso(deadline), closes_at_text=clock_text(deadline),
seconds_left=max(0, int((deadline - now).total_seconds())),
countdown_text=countdown_text((deadline - now).total_seconds()))
message = f"Quota {data['bet_amount_text']}. Il round chiude alle {data['closes_at_text']}."
if config.pause_after_round:
message += " Dopo questo round la lotteria si ferma per manutenzione."
return _finish(data, OPEN, message)
if round_.status in (Round.Status.OPEN, Round.Status.CLOSING): # past the deadline, even if the scheduler lags
return _finish(data, CLOSING, "Le puntate sono chiuse: attendiamo la conferma di quelle già inviate.")
if round_.status == Round.Status.DRAWING:
return _finish(data, DRAWING, "Il vincitore sarà scelto con un blocco della catena che ancora non esisteva alla chiusura.")
return _finish(data, PAYING, "Il vincitore è stato estratto: il pagamento è in attesa di conferma.")
def _without_round(data: dict[str, Any], config: LotteryConfig, now: datetime) -> dict[str, Any]:
if config.pause_after_round:
return _finish(data, MAINTENANCE, "La lotteria è ferma per manutenzione. Il prossimo round non è ancora fissato.")
last = Round.objects.filter(status=Round.Status.CLOSED).order_by("-id").first()
if last is not None and last.closed_at is not None:
opens = last.closed_at + timedelta(seconds=last.cooldown_seconds)
if opens > now:
data.update(next_round_at=iso(opens), next_round_at_text=clock_text(opens))
return _finish(data, NONE, f"Il prossimo round apre alle {data['next_round_at_text']}.")
return _finish(data, NONE, "Il prossimo round sta per aprirsi.")
def _finish(data: dict[str, Any], state: str, message: str) -> dict[str, Any]:
data.update(state=state, label=LABELS[state], message=message, can_participate=state == OPEN)
return data
+93
View File
@@ -0,0 +1,93 @@
/* The public home keeps itself current (WEB-05, WEB-10): the server already rendered the state, so this only
(1) runs the countdown against the *server's* clock, never the visitor's, and (2) polls /stato/ — every 5 s while
the page is visible, at once when it becomes visible again or when the countdown ends, slower after errors.
No dependencies, no inline code. */
function formatCountdown(totalSeconds) {
const s = Math.max(0, Math.floor(totalSeconds));
const hours = Math.floor(s / 3600), minutes = Math.floor((s % 3600) / 60), seconds = s % 60;
const two = (n) => String(n).padStart(2, "0");
return hours > 0 ? `${hours}:${two(minutes)}:${two(seconds)}` : `${two(minutes)}:${two(seconds)}`;
}
/* How far the visitor's clock is from the server's: add it to Date.now() to get the server's time. */
function serverOffsetMs(serverNowIso, clientNowMs) {
return Date.parse(serverNowIso) - clientNowMs;
}
function secondsLeft(closesAtIso, offsetMs, clientNowMs) {
return (Date.parse(closesAtIso) - (clientNowMs + offsetMs)) / 1000;
}
function pollDelayMs(failures) {
return Math.min(30000, 5000 * Math.pow(2, Math.max(0, failures)));
}
if (typeof module !== "undefined") {
module.exports = { formatCountdown, serverOffsetMs, secondsLeft, pollDelayMs };
}
if (typeof document !== "undefined") {
const card = document.getElementById("round-card");
if (card) {
const field = (name) => card.querySelector(`[data-field="${name}"]`);
let offsetMs = 0, closesAt = "", failures = 0, timer = null, polling = false;
const setText = (name, value) => { const el = field(name); if (el && el.textContent !== String(value)) el.textContent = value; };
const setHidden = (name, hidden) => { const el = field(name); if (el) el.hidden = hidden; };
function render(s) {
card.dataset.state = s.state;
offsetMs = serverOffsetMs(s.server_now, Date.now());
closesAt = s.closes_at || "";
setText("label", s.label);
setText("message", s.message);
setText("bet_amount_text", s.bet_amount_text);
setText("jackpot_text", s.jackpot_text);
setText("confirmed_players", s.confirmed_players);
setText("pending_players", s.pending_players);
setHidden("pending", !s.pending_players);
setHidden("participate-line", !s.can_participate);
setHidden("countdown-line", !closesAt);
tickClock();
}
function tickClock() {
if (!closesAt) return;
const left = secondsLeft(closesAt, offsetMs, Date.now());
setText("countdown", formatCountdown(left));
if (left <= 0 && !polling) poll(); // the round has just closed: ask the server what happens next
}
async function poll() {
if (polling) return;
polling = true;
clearTimeout(timer);
try {
const response = await fetch(card.dataset.pollUrl, { headers: { Accept: "application/json" }, cache: "no-store" });
if (!response.ok) throw new Error(String(response.status));
render(await response.json());
failures = 0;
setHidden("connection", true);
} catch (error) {
failures += 1;
setHidden("connection", false);
} finally {
polling = false;
schedule();
}
}
function schedule() {
clearTimeout(timer);
if (!document.hidden) timer = setTimeout(poll, pollDelayMs(failures));
}
document.addEventListener("visibilitychange", () => { if (document.hidden) clearTimeout(timer); else poll(); });
setInterval(tickClock, 1000);
offsetMs = serverOffsetMs(card.dataset.serverNow, Date.now());
closesAt = card.dataset.closesAt || "";
tickClock();
schedule();
}
}
+19
View File
@@ -68,3 +68,22 @@ input[type=text], input[type=password] { width: 100%; min-height: 2.75rem; paddi
@media (min-width: 40rem) { h1 { font-size: 2rem; } .card { padding: 1.6rem; } }
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
/* `hidden` must win over any `display` set above. */
[hidden] { display: none !important; }
/* Public home: the state of the round (WEB-10). The colour is a cue, never the only one — the label says it too. */
.lead { color: var(--muted); max-width: 40rem; }
.round-card { --state: var(--muted); border-left: .4rem solid var(--state); }
.round-card[data-state="open"] { --state: var(--ok); }
.round-card[data-state="closing"], .round-card[data-state="drawing"], .round-card[data-state="paying"] { --state: var(--accent); }
.round-card[data-state="maintenance"] { --state: var(--error); }
.state-label { font-size: 1.35rem; font-weight: 700; margin: 0 0 .3rem; color: var(--state); }
.state-message { margin: 0 0 1rem; }
.countdown { font-size: 1.1rem; margin: 0 0 1rem; }
.clock { font-size: 1.8rem; font-variant-numeric: tabular-nums; }
.stats { display: grid; gap: .8rem 1.5rem; grid-template-columns: repeat(auto-fit, minmax(9rem, 1fr)); margin: 0 0 1.2rem; }
.stats dt { color: var(--muted); font-size: .9rem; } .stats dd { margin: 0; font-size: 1.25rem; font-weight: 600; }
.stats dd .hint { font-size: .85rem; font-weight: 400; }
.actions { margin: 0; }
.button.big { min-height: 3.25rem; padding-inline: 2.2rem; font-size: 1.15rem; }
+1
View File
@@ -6,6 +6,7 @@
<meta name="color-scheme" content="light dark">
<title>{% block title %}PLM Lottery{% endblock %}</title>
<link rel="stylesheet" href="{% static 'web/site.css' %}">
{% block head %}{% endblock %}
</head>
<body>
<a class="skip-link" href="#contenuto">Vai al contenuto</a>
+27 -1
View File
@@ -1,5 +1,31 @@
{% extends "web/base.html" %}
{% load static %}
{% block head %}<script src="{% static 'web/home.js' %}" defer></script>{% endblock %}
{% block content %}
<h1>PLM Lottery</h1>
<p>Il sito è in costruzione.</p>
<p class="lead">Una lotteria a round: ogni giocatore punta la stessa quota, si estrae un vincitore, il montepremi si divide 70% a lui e 30% alla piattaforma.</p>
<section id="round-card" class="card round-card" data-state="{{ s.state }}" data-poll-url="{% url 'web:state' %}"
data-server-now="{{ s.server_now }}" data-closes-at="{{ s.closes_at|default:'' }}" aria-labelledby="round-state">
<p class="state-label" id="round-state" data-field="label" aria-live="polite">{{ s.label }}</p>
<p class="state-message" data-field="message">{{ s.message }}</p>
<p class="countdown"{% if s.seconds_left is None %} hidden{% endif %} data-field="countdown-line">
Chiude fra <strong class="clock" data-field="countdown">{{ s.countdown_text|default:'00:00' }}</strong>
<span class="hint">(ora del server)</span>
</p>
<dl class="stats">
<div><dt>Quota</dt><dd data-field="bet_amount_text">{{ s.bet_amount_text }}</dd></div>
<div><dt>Montepremi confermato</dt><dd data-field="jackpot_text">{{ s.jackpot_text }}</dd></div>
<div><dt>Giocatori</dt><dd><span data-field="confirmed_players">{{ s.confirmed_players }}</span>
<span class="hint" data-field="pending"{% if not s.pending_players %} hidden{% endif %}>+<span data-field="pending_players">{{ s.pending_players }}</span> in conferma</span></dd></div>
</dl>
<p class="actions"{% if not s.can_participate %} hidden{% endif %} data-field="participate-line">
<a class="button big" href="{% url 'web:app-home' %}" data-field="participate">Partecipa</a>
</p>
<p class="hint" data-field="connection" role="status" hidden>Connessione persa: i dati potrebbero non essere aggiornati. Riprovo…</p>
<noscript><p class="hint">Senza JavaScript la pagina non si aggiorna da sola: ricaricala per vedere lo stato più recente.</p></noscript>
</section>
{% endblock %}
+1
View File
@@ -5,6 +5,7 @@ from . import views
app_name = "web"
urlpatterns = [
path("", views.home, name="home"),
path("stato/", views.state, name="state"),
path("app/", views.app_home, name="app-home"),
path("health/live", views.health_live, name="health-live"),
]
+12 -2
View File
@@ -4,10 +4,20 @@ from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from apps.lottery.status import public_state
@never_cache
def home(request):
"""Placeholder landing page: the real home (WEB-10) arrives with A6."""
return render(request, "web/home.html")
"""The public home (WEB-10): the state is rendered by the server, so the page works without JavaScript;
`home.js` then keeps the countdown and polls `state` (WEB-05)."""
return render(request, "web/home.html", {"s": public_state()})
@never_cache
def state(request):
"""The same state as JSON, public and never cached: what the home page polls (WEB-05, WEB-10)."""
return JsonResponse(public_state())
@never_cache
+9
View File
@@ -418,3 +418,12 @@ implementato il [piano delle correzioni](piano-correzioni.md).
- ~~[LIM-23]~~ Rimosso: chiuso da B-94. `GET /admin/users` è paginato ([API-33](api.md)).
- **[LIM-24]** **Un tentativo sbagliato apposta può bloccare un nome per qualche secondo.** Il limite ai tentativi di accesso è per
nome utente e per indirizzo ([WEB-53](sito-e-app.md#7--accesso-e-account), [ADR-41](adr/ADR-41-limitazione-tentativi-su-login-registrazione.md)):
chi sbaglia di proposito la password di un nome altrui lo fa attendere (2 s dopo il quinto errore, poi il doppio a ogni errore, fino
a 300 s dall'ultimo), e il proprietario, anche con la password giusta, deve aspettare. È lo stesso compromesso del vecchio sistema: un
blocco per nome è il prezzo per fermare chi indovina una password da indirizzi diversi, e un blocco per solo indirizzo non lo
fermerebbe. *Cosa lo attenua:* l'attesa è breve e si azzera da sola dopo 900 s di quiete; l'indirizzo che sbaglia 20 volte viene
fermato a sua volta. *Per chiuderlo:* un secondo fattore (MFA, [ADR-56](adr/ADR-56-staff-account-individuali-permessi-mfa-dopo-pilota.md))
o una verifica anti-automazione sul modulo.
+27 -2
View File
@@ -46,6 +46,7 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
- **[WEB-05]** I dati che cambiano (stato del round, saldo, esito) si
aggiornano con richieste periodiche mirate e si recuperano al rientro nella
pagina; ricaricare non perde lo stato salvato.
*Stato:* implementato per la home (A6, [WEB-14]); per l'area giocatore con l'A7.
- **[WEB-06]** Le pagine sono utilizzabili da smartphone e da desktop e
navigabili da tastiera, con stati distinti di errore, attesa e conferma.
*Stato:* base implementata (A5): layout fluido da 400 px, foglio di stile unico con tema chiaro/scuro, collegamento «Vai al
@@ -70,16 +71,36 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
l'ora del server come riferimento, e uno fra gli stati: nessun round,
puntate aperte, in chiusura, estrazione in corso, pagamento in attesa,
manutenzione.
Gli stati: **nessun round** (fra due round, con l'orario di apertura quando è noto), **puntate aperte** (quota, chiusura e
conto alla rovescia), **in chiusura** (anche oltre la scadenza se lo scheduler è in ritardo, [ADR-23](adr/ADR-23-limite-scommettere-scadenza-round-stesso-suo.md)),
**estrazione in corso**, **pagamento in attesa**, **manutenzione** (nessun round si aprirà, oppure puntate sospese;
[ADR-57](adr/ADR-57-due-pause-distinte-dopo-round-e-incidente.md)). Un round in corso con la «pausa dopo il round» resta «puntate
aperte» e avvisa che poi la lotteria si ferma. Il **montepremi confermato** è la quota del vincitore (70%) di ciò che è già
confermato: mai più di ciò che sarà pagato; le puntate in volo si indicano a parte («+N in conferma»). La quota è quella del round,
non quella corrente della configurazione. La pagina è renderizzata dal server, quindi funziona anche senza JavaScript.
*Stato:* implementato (A6); il collegamento a «dove controllare il risultato» arriva con l'A8 ·
*Codice:* `apps/lottery/status.py:public_state`, `apps/web/views.py:home`, `apps/web/templates/web/home.html` ·
*Test:* `tests/django/test_home.py` (un test per stato, il montepremi confermato, la quota del round)
- **[WEB-11]** «Partecipa» porta a `/app/`; se serve il login, dopo
l'accesso riporta alla schermata di gioco. Il pulsante apre il flusso: la
puntata richiede una conferma esplicita.
*Stato:* il ritorno alla destinazione interna è implementato (A5, [WEB-52]); il pulsante con l'A6.
*Stato:* implementato (A5, [WEB-52], e A6): «Partecipa» compare solo quando le puntate sono aperte e porta a `/app/` ·
*Test:* `tests/django/test_home.py::test_participate_leads_to_the_player_area`, `test_participate_is_hidden_when_betting_is_not_possible`
- **[WEB-12]** `/risultati/` pubblica esito e prova dell'estrazione,
riproducibile con i dati del protocollo ([RND-14]…[RND-20]), senza
username né dati dell'account. Il pagamento risulta confermato solo quando lo è.
- **[WEB-13]** Guida e regole usano gli stessi termini dell'area giocatore
(quota, ripartizione 70/30, commissioni, attesa delle conferme) e non
promettono l'accredito immediato.
- **[WEB-14]** **Aggiornamento della home.** `GET /stato/` restituisce, pubblico e mai in cache, lo stesso stato che la pagina
mostra (una sola funzione li alimenta: non possono raccontare cose diverse), senza dati di account né del segreto del round;
porta l'ora del server. `home.js` (esterno, senza dipendenze) fa scorrere il conto alla rovescia sull'**ora del server**, non su
quella del visitatore; interroga `/stato/` ogni 5 secondi mentre la pagina è visibile, subito quando torna visibile o quando il
conto arriva a zero, e più di rado dopo errori (fino a 30 s), mostrando «Connessione persa». Il testo del conto alla rovescia è lo
stesso con e senza JavaScript.
*Stato:* implementato (A6) ·
*Codice:* `apps/web/views.py:state`, `apps/web/static/web/home.js` ·
*Test:* `tests/django/test_home.py::test_the_endpoint_and_the_page_tell_the_same_story`, `test_the_endpoint_exposes_no_account_data`, `test_the_script_is_valid_and_its_clock_arithmetic_is_right`, `test_the_server_and_the_script_write_the_countdown_the_same_way`
## 3 · Area giocatore
@@ -184,6 +205,10 @@ FastAPI, che non è più nel compose.
- **[WEB-54]** **Uscita e cambio password.** L'uscita è solo `POST` (con CSRF) e chiude la sessione. Il cambio password chiede la password
attuale, chiude **tutte le altre sessioni** (una sessione è legata all'impronta della password con cui nasce, [B-34]), lascia
connessa quella corrente e scrive `password_changed` nell'audit. `/app/profilo/` mostra solo i dati dell'utente connesso ([WEB-03]).
*Stato:* implementato (A5); le segnalazioni del profilo non sono ancora previste ·
*Stato:* implementato (A5); le segnalazioni del profilo sono in [WEB-55] ·
*Codice:* `apps/accounts/views.py:logout_view`, `apps/accounts/views.py:profile_view` ·
*Test:* `tests/django/test_accounts.py::test_a_password_change_signs_out_every_other_session`, `test_signing_out_ends_the_session_and_only_by_post`, `test_the_profile_shows_only_the_owner`
- **[WEB-55]** **Segnalazioni.** Dal profilo (`/app/profilo/`) l'utente invia una segnalazione di un problema e vede lo stato delle proprie
(aperta, letta, risolta); lo staff le gestisce da `/admin/` ([WEB-32]) cambiandone lo stato, e ogni cambio è nell'audit. Il testo ha
una lunghezza massima e l'invio è limitato per utente ([SEC-55]). Un utente vede solo le proprie segnalazioni ([WEB-03]).
*Stato:* da implementare (A9: modello, sezione del profilo e gestione in `/admin/`).
+2 -2
View File
@@ -29,10 +29,10 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore
- [x] **A3 · Ledger simulato.** Interfaccia dei servizi (deposito, puntata, pagamento) con implementazione simulata e **chiave di idempotenza**: un doppio invio produce una sola operazione. *Requisiti:* WEB-23, ADR-59. *Test:* doppio invio, saldo insufficiente, importi al limite.
- [x] **A4 · Ciclo del round e worker.** Apertura, chiusura, estrazione e pagamento 70/30 nel worker (`manage.py run_worker`), con l'estrazione commit-reveal dello stesso algoritmo del motore. *Requisiti:* RND esistenti riletti sul modello nuovo. *Test:* round completo deterministico, ripresa dopo riavvio del worker.
- [x] **A5 · Autenticazione e base grafica.** `/registrati/`, `/accedi/`, `/app/profilo/` (password, logout), CSRF, cookie di sessione, ritorno alla destinazione interna (`next`) solo se interna, template base e CSS responsivo. *Requisiti:* WEB-02, WEB-06. *Test:* redirect aperto rifiutato, cookie, throttling dei tentativi.
- [ ] **A6 · Home pubblica.** `/` con quota, montepremi confermato, chiusura (ora server) e i sei stati, «Partecipa», aggiornamento a polling. *Requisiti:* WEB-05, WEB-10, WEB-11. *Test:* un test per stato, polling dell'endpoint.
- [x] **A6 · Home pubblica.** `/` con quota, montepremi confermato, chiusura (ora server) e i sei stati, «Partecipa», aggiornamento a polling. *Requisiti:* WEB-05, WEB-10, WEB-11. *Test:* un test per stato, polling dell'endpoint.
- [ ] **A7 · Area giocatore.** `/app/` (puntata con conferma esplicita), `/app/portafoglio/` (saldo spendibile e in conferma, deposito simulato **solo fuori da mainnet**), `/app/movimenti/`. *Requisiti:* WEB-03, WEB-20, WEB-21, WEB-22. *Test:* isolamento tra utenti (404 su dati altrui), stato salvato dopo ricarica.
- [ ] **A8 · Pagine pubbliche di risultato e guida.** `/risultati/`, `/risultati/<id>/` con prova riproducibile senza dati dell'account, `/guida/`, `/regole/` con gli stessi termini dell'app. *Requisiti:* WEB-12, WEB-13. *Test:* la prova ricalcola il vincitore; nessuno username nelle pagine.
- [ ] **A9 · Console operativa e audit.** `/ops/` con stato del round, scadenza, salute del worker, operazioni in ritardo; i tre comandi di pausa con conferma e motivazione; `/admin/` per utenti e segnalazioni con record di gioco in sola lettura; ogni comando registrato nell'audit. *Requisiti:* WEB-30…WEB-33, WEB-40…WEB-44. *Test:* giocatore e staff senza permesso non eseguono i comandi; la pausa si riflette sul sito.
- [ ] **A9 · Console operativa e audit.** `/ops/` con stato del round, scadenza, salute del worker, operazioni in ritardo; i tre comandi di pausa con conferma e motivazione; `/admin/` per utenti e segnalazioni con record di gioco in sola lettura; **segnalazioni**: modello, sezione nel profilo del giocatore (invio e stato delle proprie) e gestione da `/admin/`; ogni comando registrato nell'audit. *Requisiti:* WEB-30…WEB-33, WEB-40…WEB-44, WEB-55. *Test:* giocatore e staff senza permesso non eseguono i comandi; la pausa si riflette sul sito.
- [ ] **A10 · Percorso completo e chiusura di fase.** Test end-to-end `home → login → deposito → puntata → estrazione → risultato pubblico`; verifica su telefono e desktop, tastiera, stati di errore, attesa e conferma (checklist in `docs/`); guida di avvio in locale in `docs/setup.md`. *Requisiti:* WEB-06.
## Fase B — Integrazione del motore PLM
+2 -1
View File
@@ -480,7 +480,8 @@ def test_password_fields_tell_the_browser_what_they_are(client):
def test_pages_use_no_inline_scripts_or_styles(client, url):
"""So the Content-Security-Policy can be tightened for them."""
html = client.get(url).content.decode()
assert "<script" not in html and " style=" not in html and not re.search(r"\son[a-z]+=", html)
inline_scripts = [m for m in re.findall(r"<script\b[^>]*>", html) if "src=" not in m]
assert not inline_scripts and " style=" not in html and not re.search(r"\son[a-z]+=", html)
def test_errors_are_announced_to_assistive_technology(client):
+314
View File
@@ -0,0 +1,314 @@
"""A6 — the public home: WEB-05, WEB-10, WEB-11, B-11, B-65, ADR-23, ADR-57."""
import json
import re
import shutil
import subprocess
from datetime import timedelta
from pathlib import Path
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.utils import timezone
from apps.lottery import lifecycle
from apps.lottery.format import plm_text
from apps.lottery.ledger import SimulatedLedger
from apps.lottery.models import LotteryConfig, Round
from apps.lottery.status import LABELS, countdown_text, public_state
ROOT = Path(__file__).resolve().parents[2]
PLM = 100_000_000
BET = 10 * PLM
pytestmark = pytest.mark.django_db
ledger = SimulatedLedger()
def make_round(status="open", **kwargs):
kwargs.setdefault("opened_at", timezone.now() - timedelta(seconds=100))
if status == "closed":
kwargs.setdefault("closed_at", timezone.now())
return Round.objects.create(status=status, **kwargs)
def bet(round_, name, *, confirm=True):
user = get_user_model().objects.create_user(name, password="x" * 12)
ledger.deposit(user, round_.bet_amount_sats)
participation = ledger.place_bet(user, round_.pk, request_id=uuid4()).obj
if confirm:
ledger.confirm_bet(participation)
return user
def set_config(**fields):
config = LotteryConfig.get()
for name, value in fields.items():
setattr(config, name, value)
config.save()
# --- the six states ----------------------------------------------------------------------------
def test_with_no_round_the_state_is_none():
state = public_state()
assert (state["state"], state["label"], state["can_participate"]) == ("none", "Nessun round in corso", False)
assert state["closes_at"] is None and state["seconds_left"] is None and state["round_id"] is None
def test_between_rounds_it_says_when_the_next_one_opens():
"""The cooldown of the round that just closed."""
now = timezone.now()
make_round("closed", closed_at=now - timedelta(seconds=10), cooldown_seconds=30)
state = public_state(now)
assert state["state"] == "none" and state["next_round_at"] is not None
assert state["next_round_at_text"] in state["message"]
assert public_state(now + timedelta(seconds=25))["next_round_at"] is None # the gap is over: about to open
def test_an_open_round_shows_quota_closing_time_and_countdown():
now = timezone.now()
round_ = make_round(opened_at=now - timedelta(seconds=100), duration_seconds=600, bet_amount_sats=7 * PLM)
state = public_state(now)
assert (state["state"], state["label"], state["can_participate"]) == ("open", "Puntate aperte", True)
assert state["seconds_left"] == 500 and state["round_id"] == round_.pk
assert state["bet_amount_text"] == "7 PLM" and state["closes_at_text"] in state["message"]
assert state["closes_at"] == (round_.opened_at + timedelta(seconds=600)).strftime("%Y-%m-%dT%H:%M:%SZ")
def test_the_quota_is_the_rounds_own_not_the_live_config():
"""ADR-10: an edit of the configuration changes nothing until the next round."""
make_round(bet_amount_sats=7 * PLM)
set_config(bet_amount_sats=99 * PLM)
assert public_state()["bet_amount_sats"] == 7 * PLM
def test_past_the_deadline_it_is_closing_even_if_the_scheduler_lags():
"""ADR-23."""
now = timezone.now()
make_round(opened_at=now - timedelta(seconds=700), duration_seconds=600) # still `open` in the database
state = public_state(now)
assert (state["state"], state["label"], state["can_participate"]) == ("closing", "In chiusura", False)
assert state["seconds_left"] is None
@pytest.mark.parametrize("status,state,label", [
("closing", "closing", "In chiusura"),
("drawing", "drawing", "Estrazione in corso"),
("paying_out", "paying", "Pagamento in attesa"),
])
def test_each_stage_after_the_betting_window(status, state, label):
shown = public_state(make_round(status) and timezone.now())
assert (shown["state"], shown["label"], shown["can_participate"]) == (state, label, False)
def test_maintenance_when_no_round_will_open():
"""ADR-57: «Pausa dopo il round in corso», once the round in progress is over."""
set_config(pause_after_round=True)
state = public_state()
assert (state["state"], state["label"], state["can_participate"]) == ("maintenance", "Manutenzione", False)
def test_a_pause_after_the_round_does_not_stop_the_round_in_progress():
"""The round still runs and is paid; the page only warns that nothing opens afterwards."""
make_round()
set_config(pause_after_round=True)
state = public_state()
assert state["state"] == "open" and state["can_participate"] and state["paused_after_round"]
assert "si ferma per manutenzione" in state["message"]
def test_suspended_bets_show_maintenance_while_the_round_runs():
"""ADR-57: «Sospendi nuove puntate» — no new bets; the bets already sent stay valid."""
make_round()
set_config(new_bets_suspended=True)
state = public_state()
assert state["state"] == "maintenance" and not state["can_participate"]
assert "già inviate restano valide" in state["message"]
assert public_state(timezone.now() + timedelta(seconds=700))["state"] == "closing" # later stages show as usual
def test_every_state_has_a_label():
assert set(LABELS) == {"none", "open", "closing", "drawing", "paying", "maintenance"}
# --- the confirmed prize -----------------------------------------------------------------------
def test_the_prize_counts_confirmed_bets_only_and_is_the_winners_share():
"""B-11, B-65: never more than will be paid; bets in flight are reported apart."""
round_ = make_round()
for name in ("a", "b", "c"):
bet(round_, name)
bet(round_, "d", confirm=False)
state = public_state()
assert state["confirmed_players"] == 3 and state["pending_players"] == 1
assert state["jackpot_sats"] == 21 * PLM and state["jackpot_text"] == "21 PLM" # 70% of 3 x 10, not of 4 x 10
def test_the_prize_ignores_a_pool_that_is_not_confirmed():
round_ = make_round()
bet(round_, "a", confirm=False)
assert public_state()["jackpot_sats"] == 0
def test_the_remainder_never_appears_in_the_prize():
round_ = make_round(bet_amount_sats=11)
bet(round_, "a")
assert public_state()["jackpot_sats"] == 7 # 70% of 11, rounded down
@pytest.mark.parametrize("sats,text", [
(0, "0 PLM"), (BET, "10 PLM"), (70_000_000, "0,7 PLM"), (1, "0,00000001 PLM"), (1_234 * PLM + 50_000_000, "1.234,5 PLM"),
(12_345_678 * PLM, "12.345.678 PLM"), (-PLM, "-1 PLM"),
])
def test_amounts_are_shown_exactly(sats, text):
assert plm_text(sats) == text
# --- the page ----------------------------------------------------------------------------------
def test_the_home_shows_the_state_without_any_script(client):
"""WEB-10: server-rendered, so it works with JavaScript off."""
round_ = make_round(bet_amount_sats=7 * PLM)
bet(round_, "a")
html = client.get("/").content.decode()
for expected in ("Puntate aperte", "7 PLM", "Montepremi confermato", "4,9 PLM", "Quota", "(ora del server)"):
assert expected in html
assert 'data-state="open"' in html and "UTC" in html
def test_participate_leads_to_the_player_area(client):
"""WEB-11."""
make_round()
html = client.get("/").content.decode()
assert re.search(r'<a class="button big" href="/app/"[^>]*>Partecipa</a>', html)
assert re.search(r'data-field="participate-line"', html) and 'hidden data-field="participate-line"' not in html
@pytest.mark.parametrize("make", [lambda: None, lambda: make_round("drawing"), lambda: set_config(pause_after_round=True)])
def test_participate_is_hidden_when_betting_is_not_possible(client, make):
make()
assert re.search(r'<p class="actions" hidden data-field="participate-line">', client.get("/").content.decode())
def test_the_player_area_sends_visitors_to_sign_in_and_back(client):
"""WEB-11: «Partecipa» then login then the play screen."""
assert client.get("/app/")["Location"] == "/accedi/?next=/app/"
def test_the_home_is_never_cached(client):
assert "no-store" in client.get("/")["Cache-Control"] or "no-cache" in client.get("/")["Cache-Control"]
def test_the_home_has_no_inline_script_and_loads_its_script_deferred(client):
html = client.get("/").content.decode()
tags = re.findall(r"<script\b[^>]*>", html)
assert tags == ['<script src="/static/web/home.js" defer>'] or all("src=" in t and "defer" in t for t in tags)
assert (ROOT / "apps/web/static/web/home.js").exists()
# --- the polling endpoint ----------------------------------------------------------------------
def test_the_state_endpoint_is_public_json_and_never_cached(client):
make_round()
response = client.get("/stato/")
assert response.status_code == 200 and response["Content-Type"].startswith("application/json")
assert "no-store" in response["Cache-Control"] or "no-cache" in response["Cache-Control"]
body = response.json()
assert set(body) >= {"state", "label", "message", "server_now", "closes_at", "seconds_left", "bet_amount_sats",
"jackpot_sats", "confirmed_players", "pending_players", "can_participate", "round_id"}
def test_the_endpoint_and_the_page_tell_the_same_story(client):
"""WEB-05: one function feeds both."""
round_ = make_round()
bet(round_, "a")
body = client.get("/stato/").json()
html = client.get("/").content.decode()
assert body["label"] in html and body["jackpot_text"] in html and body["bet_amount_text"] in html
def test_the_endpoint_exposes_no_account_data(client):
"""Only counts and amounts: no username, no address, no secret of the round."""
round_ = make_round()
bet(round_, "mariorossi")
Round.objects.filter(pk=round_.pk).update(server_seed_hash="a" * 64)
raw = client.get("/stato/").content.decode()
assert "mariorossi" not in raw and "server_seed" not in raw and "rplm1" not in raw
def test_the_countdown_follows_the_server_clock(client):
"""WEB-10: the page carries the server's time so the visitor's clock does not matter."""
make_round(opened_at=timezone.now() - timedelta(seconds=100), duration_seconds=600)
body = client.get("/stato/").json()
assert 490 <= body["seconds_left"] <= 500
assert body["server_now"].endswith("Z") and body["closes_at"].endswith("Z")
def test_the_state_follows_a_real_round_through_its_stages(settings):
"""From the worker's own steps: none -> open -> closing -> drawing -> paying -> maintenance."""
t0 = timezone.now()
assert public_state(t0)["state"] == "none"
round_ = lifecycle.open_new_round_if_needed(t0)
assert public_state(t0)["state"] == "open"
bet(round_, "a")
bet(round_, "b")
from tests.django.test_lifecycle import FakeChain
chain, end = FakeChain(1000), round_.opened_at + timedelta(seconds=round_.duration_seconds)
assert public_state(end)["state"] == "closing"
lifecycle.tick(now=end, chain=chain)
assert public_state(end)["state"] == "drawing"
chain.tip = 1003
lifecycle.tick(now=end, chain=chain)
assert public_state(end)["state"] == "paying"
set_config(pause_after_round=True)
from apps.lottery import simulation
done = end + timedelta(minutes=5)
simulation.settle(done)
lifecycle.tick(now=done, chain=chain)
assert public_state(done)["state"] == "maintenance"
# --- the script --------------------------------------------------------------------------------
NODE = shutil.which("node")
def _node(expression: str):
code = f"const m = require('{ROOT / 'apps/web/static/web/home.js'}'); console.log(JSON.stringify({expression}));"
out = subprocess.run([NODE, "-e", code], capture_output=True, text=True, check=True)
return json.loads(out.stdout)
@pytest.mark.skipif(NODE is None, reason="node is not installed")
def test_the_script_is_valid_and_its_clock_arithmetic_is_right():
subprocess.run([NODE, "--check", str(ROOT / "apps/web/static/web/home.js")], check=True)
assert _node("[m.formatCountdown(0), m.formatCountdown(59), m.formatCountdown(60), m.formatCountdown(600), "
"m.formatCountdown(3725), m.formatCountdown(-5), m.formatCountdown(61.9), m.formatCountdown(3599), "
"m.formatCountdown(3600), m.formatCountdown(7199)]") == \
["00:00", "00:59", "01:00", "10:00", "1:02:05", "00:00", "01:01", "59:59", "1:00:00", "1:59:59"]
# the visitor's clock is 10 minutes slow: the countdown still counts to the *server's* deadline
assert _node("m.secondsLeft('2026-01-01T00:10:00Z', "
"m.serverOffsetMs('2026-01-01T00:00:00Z', Date.parse('2025-12-31T23:50:00Z')), "
"Date.parse('2025-12-31T23:50:30Z'))") == 570
assert _node("[m.pollDelayMs(0), m.pollDelayMs(1), m.pollDelayMs(2), m.pollDelayMs(10)]") == [5000, 10000, 20000, 30000]
@pytest.mark.skipif(NODE is None, reason="node is not installed")
@pytest.mark.parametrize("seconds", [0, 1, 59, 60, 61, 599, 600, 3599, 3600, 3725, 7199, 86399])
def test_the_server_and_the_script_write_the_countdown_the_same_way(seconds):
"""Without JavaScript the page reads exactly as it does with it."""
assert countdown_text(seconds) == _node(f"m.formatCountdown({seconds})")
def test_the_page_renders_the_countdown_as_minutes_and_seconds(client):
make_round(opened_at=timezone.now() - timedelta(seconds=100), duration_seconds=600)
assert re.search(r'data-field="countdown">0[89]:[0-5]\d<', client.get("/").content.decode())
+1
View File
@@ -26,6 +26,7 @@ def _import_settings(**env: str) -> subprocess.CompletedProcess:
# --- WEB-01 / WEB-07: the site answers, on localhost, with no domain configured ---------------
@pytest.mark.django_db
def test_home_answers_on_localhost(client):
"""WEB-07: `http://localhost` serves the placeholder home in Italian."""
response = client.get("/", HTTP_HOST="localhost")