A10: end-to-end journey test, verification checklist and local start guide (WEB-06)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:06:48 +01:00
1 parent eab141f467
commit 6509cedd7c
9 files changed
+156 -9

No files matched your search

+1 -1
View File
@@ -8,7 +8,7 @@ The user communicates in Italian in chat — reply to them in Italian. Everythin
## Project status
The migration from FastAPI to Django is in progress on branch `django-migration` (plan: [roadmap.md](roadmap.md), steps A1–A9 done). The suite has 1156 tests: the old stack's under `tests/unit/`, the Django ones under `tests/django/` (`tests/integration/` is an empty package). Open defects of the old stack are in [BUGS.md](BUGS.md); accepted limits in [docs/limiti-noti.md](docs/limiti-noti.md); every closed `B-nn` is in [docs/storico-bug.md](docs/storico-bug.md) (`git log --all --grep 'B-nn'` finds its commit).
The migration from FastAPI to Django is in progress on branch `django-migration` (plan: [roadmap.md](roadmap.md), steps A1–A10 done). The suite has 1157 tests: the old stack's under `tests/unit/`, the Django ones under `tests/django/` (`tests/integration/` is an empty package). Open defects of the old stack are in [BUGS.md](BUGS.md); accepted limits in [docs/limiti-noti.md](docs/limiti-noti.md); every closed `B-nn` is in [docs/storico-bug.md](docs/storico-bug.md) (`git log --all --grep 'B-nn'` finds its commit).
**[docs/](docs/README.md) is the specification, and it is authoritative.** Every verifiable rule there has a stable requirement ID (`RND-04`, `BET-02`, …) with `*Codice:*`/`*Test:*` pointers to what implements it; the index is [docs/come-funziona.md](docs/come-funziona.md) and the ID convention and change workflow are in [docs/processo-di-modifica.md](docs/processo-di-modifica.md). A behaviour change starts in the spec: edit or add the requirement, implement it, cite the ID in the test docstring and the commit message, and ship spec + code + test in one commit. If this file and the spec disagree, the spec wins and this file is the one to fix. Before writing code, read the relevant spec documents and the "Architecture" section below.
+1 -1
View File
@@ -62,7 +62,7 @@ python -m pytest # all tests
python -m pytest tests/unit/test_hd.py # one file
```
1156 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
1157 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
+2 -1
View File
@@ -65,7 +65,8 @@ Punto d'ingresso narrativo: [come-funziona.md](come-funziona.md).
## Guide operative (senza requisiti)
[setup.md](setup.md) · [running-the-server.md](running-the-server.md) ·
[guida-utente.md](guida-utente.md) · [guida-admin.md](guida-admin.md). Si
[guida-utente.md](guida-utente.md) · [guida-admin.md](guida-admin.md) ·
[checklist-verifica-sito.md](checklist-verifica-sito.md). Si
aggiornano quando la specifica cambia qualcosa di visibile.
## Lingua
+37
View File
@@ -0,0 +1,37 @@
# Checklist di verifica del sito
Verifica a mano di fine Fase A ([WEB-06](sito-e-app.md)): da eseguire su `https://localhost` con lo stack avviato come in [setup.md](setup.md), su **telefono** (larghezza circa 400 px, anche con gli strumenti del browser) e su **desktop**. Il percorso completo è anche un test automatico, `tests/django/test_journey.py::test_from_the_home_page_to_the_public_result`: questa lista copre ciò che un test non vede.
Segna ogni voce con data e dispositivo; una voce fallita diventa un difetto in [BUGS.md](../BUGS.md).
## Percorso
1. **Home** `/`: stato del round, quota, montepremi confermato e conto alla rovescia leggibili; «Partecipa» visibile senza scorrere.
2. **Registrazione** `/registrati/`: creare l'account; si arriva su `/app/` già connessi.
3. **Deposito di prova** `/app/portafoglio/`: scegliere un importo; compare «in conferma», dopo pochi secondi diventa spendibile senza ricaricare.
4. **Puntata** `/app/punta/`: la pagina chiede la conferma esplicita; dopo l'invio lo stato passa da «In attesa» a «Confermata».
5. **Estrazione**: alla chiusura la home mostra «In chiusura», «Estrazione in corso», «Pagamento in attesa».
6. **Risultato pubblico** `/risultati/` e `/risultati/<id>/`: vincitore, prova verificabile, nessun nome utente.
7. **Console** `/ops/` con un account staff: i tre comandi chiedono motivo e conferma; «Sospendi nuove puntate» mostra «Manutenzione» sulla home.
## Telefono e desktop
- [ ] Nessuno scorrimento orizzontale della pagina a 400 px (le tabelle scorrono nel proprio riquadro).
- [ ] I pulsanti hanno almeno 44 px di altezza e si premono col pollice.
- [ ] Tema chiaro e scuro leggibili (impostazione del sistema).
- [ ] I movimenti sono schede impilate sul telefono e tabella sul desktop.
## Tastiera
- [ ] Tab percorre ogni pagina in ordine logico; il focus è sempre visibile.
- [ ] «Vai al contenuto» compare al primo Tab e salta l'intestazione.
- [ ] Ogni modulo si invia con Invio; ogni campo ha la sua etichetta.
- [ ] Nessuna azione è raggiungibile solo col mouse (conferma della puntata, uscita, comandi della console).
## Errori, attesa e conferma
- [ ] Password sbagliata: messaggio identico per nome inesistente e password errata; dopo 5 errori «Troppi tentativi» con l'attesa.
- [ ] Saldo insufficiente, round chiuso, puntata doppia: messaggio in italiano e nessun addebito doppio.
- [ ] Pagina inesistente (`/xyz`) ed errore del server: pagina d'errore in italiano con il collegamento alla home.
- [ ] Senza JavaScript le pagine restano leggibili (il conto alla rovescia è scritto nel testo).
- [ ] Durante le attese (deposito, puntata, pagamento) la pagina dice cosa sta succedendo, senza ricaricare.
+2 -2
View File
@@ -4,7 +4,7 @@
## Project status (old stack)
All 10 stages of the original build order are code-complete and unit-tested — 1156 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 — 1157 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.
@@ -30,7 +30,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 1156 tests
python -m pytest # all 1157 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
```
+25 -1
View File
@@ -1,6 +1,30 @@
# Setup
> **Nota (migrazione a Django).** Questa guida descrive il vecchio stack FastAPI, non più nel `docker-compose.yml`. L'avvio del nuovo sito è in [sito-e-app.md](sito-e-app.md#6--avvio-in-locale).
## Avvio in locale del nuovo sito (Django)
Servono Docker con Compose e Python 3.12 (solo per i test e per generare la chiave). Nessun nodo né dominio: il sito parte su `https://localhost` con la catena **simulata** ([WEB-07](sito-e-app.md)).
```bash
mkdir -p data/db
cp .env.example .env
python3 -c "import secrets; print(secrets.token_urlsafe(64))" # incollare il risultato in DJANGO_SECRET_KEY nel file .env
docker compose up -d --build
```
1. Aprire `https://localhost`: il certificato è autofirmato, l'avviso del browser alla prima visita è atteso.
2. Servizi: `web` (applica le migrazioni), `worker` (apre, chiude ed estrae i round) e `caddy`. Se il worker non gira nessun round si muove: `docker compose logs worker`.
3. Registrarsi su `/registrati/`, caricare un deposito di prova in `/app/portafoglio/` (disponibile solo con la catena simulata) e puntare.
4. Account staff per la console `/ops/` e per `/admin/`:
```bash
docker compose exec web python manage.py createsuperuser
```
Un operatore non superutente riceve i permessi dall'admin: `view_console` per entrare in `/ops/` e uno per ciascun comando (`pause_after_round`, `suspend_new_bets`, `suspend_withdrawals`).
5. Verifica a mano su telefono e desktop: [checklist-verifica-sito.md](checklist-verifica-sito.md). Test automatici: `python -m pytest`.
6. Spegnere: `docker compose down` (i dati restano in `data/db`).
---
> **Nota (migrazione a Django).** Il resto di questa guida descrive il vecchio stack FastAPI, non più nel `docker-compose.yml`.
Passaggi da eseguire una tantum per preparare un'istanza di PLM Lottery, prima di
poterla avviare. Il server gira sempre in Docker; il venv serve solo a test, migrazioni da generare e script una tantum. Per come avviarla poi ogni volta, vedi
+2 -2
View File
@@ -53,9 +53,9 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
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
contenuto», focus sempre visibile, etichette su ogni campo, errori annunciati (`role="alert"`), nessuno script né stile
inline, pagine d'errore in italiano; la verifica su telefono e desktop con le schermate finali è l'A10 ·
inline, pagine d'errore in italiano; percorso completo coperto da un test (A10); la verifica a mano su telefono, desktop e tastiera è la [checklist](checklist-verifica-sito.md) ·
*Codice:* `apps/web/templates/web/base.html`, `apps/web/static/web/site.css` ·
*Test:* `tests/django/test_accounts.py::test_every_page_is_responsive_and_keyboard_friendly`, `test_every_input_has_its_label`, `test_pages_use_no_inline_scripts_or_styles`
*Test:* `tests/django/test_accounts.py::test_every_page_is_responsive_and_keyboard_friendly`, `test_every_input_has_its_label`, `test_pages_use_no_inline_scripts_or_styles`, `tests/django/test_journey.py::test_from_the_home_page_to_the_public_result`
- **[WEB-07]** Il sito si avvia e si naviga in locale su `http://localhost`
(stesso `docker-compose.yml` di sempre, `SITE_ADDRESS` non impostato) con
+1 -1
View File
@@ -33,7 +33,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore
- [x] **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.
- [x] **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.
- [x] **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.
- [x] **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
+85
View File
@@ -0,0 +1,85 @@
"""A10 — the whole path through the site, as a visitor and a player would walk it: home, sign up, deposit, bet, draw,
public result (WEB-05, WEB-06, WEB-10, WEB-12, WEB-13, WEB-22, WEB-26, WEB-27)."""
import re
from datetime import timedelta
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.test import Client
from django.utils import timezone
from apps.lottery import lifecycle, simulation
from apps.lottery.ledger import SimulatedLedger
from apps.lottery.models import Round
from apps.lottery.simulation import SimulatedChain
pytestmark = pytest.mark.django_db
PASSWORD = "correct-horse-battery"
def form_post(client, url, data, *, page=None):
"""Read the page first (it carries the CSRF cookie and the idempotency key), then send what a browser would."""
page_html = client.get(page or url).content.decode()
token = client.cookies["csrftoken"].value
extra = dict(re.findall(r'<input type="hidden" name="(round_id|request_id)" value="([^"]+)"', page_html))
return client.post(url, {**extra, **data, "csrfmiddlewaretoken": token})
def test_from_the_home_page_to_the_public_result(settings):
settings.SIMULATED_BLOCK_SECONDS, settings.SIMULATED_CONFIRM_SECONDS = 10, 2
client = Client(enforce_csrf_checks=True)
chain = SimulatedChain()
lifecycle.tick(chain=chain) # the worker opens the round
# a visitor sees an open round and is invited to take part
home = client.get("/").content.decode()
assert "Puntate aperte" in home and "Registrati" in home
# somebody else is already in, so the draw has two players
other = get_user_model().objects.create_user("avversario", password=PASSWORD)
round_ = Round.objects.get()
ledger = SimulatedLedger()
ledger.deposit(other, round_.bet_amount_sats)
ledger.confirm_bet(ledger.place_bet(other, round_.pk, request_id=uuid4()).obj)
# sign up: the player lands signed in on the play page
response = form_post(client, "/registrati/", {"username": "giulia", "password": PASSWORD, "password_confirm": PASSWORD})
assert response.status_code == 302 and response["Location"] == "/app/"
assert client.get("/app/").status_code == 200
# deposit on the simulated ledger: first «in conferma», then spendable once the worker settles it
response = form_post(client, "/app/portafoglio/deposito-prova/", {"amount": "10"}, page="/app/portafoglio/")
assert response.status_code == 302
assert "in conferma" in client.get("/app/portafoglio/").content.decode().lower()
now = timezone.now() + timedelta(seconds=5)
simulation.settle(now)
# bet: the confirmation page first, then the explicit POST
assert "Conferma" in client.get("/app/punta/").content.decode()
response = form_post(client, "/app/punta/", {})
assert response.status_code == 302
assert client.get("/app/stato/").json()["me"]["participation"]["status"] == "pending"
simulation.settle(now + timedelta(seconds=5))
assert client.get("/app/stato/").json()["me"]["participation"]["status"] == "confirmed"
# the worker closes the round, draws and pays
now += timedelta(seconds=round_.duration_seconds + 10)
for _ in range(400):
now += timedelta(seconds=5)
simulation.settle(now)
lifecycle.tick(now=now, chain=chain)
round_.refresh_from_db()
if round_.status == "closed":
break
assert round_.status == "closed" and round_.winner_id is not None
# the public result recomputes the winner and shows no account name
page = Client().get(f"/risultati/{round_.pk}/").content.decode()
assert "Vincitore" in page and 'data-ok="0"' not in page
assert "giulia" not in page and "avversario" not in page
assert Client().get("/risultati/").status_code == 200
# the player is told how it ended
me = client.get("/app/stato/").json()["me"]
assert me["last_result"] is not None