diff --git a/CLAUDE.md b/CLAUDE.md index 00ca301..19cf331 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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. diff --git a/README.md b/README.md index a98b0d5..13e46de 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/docs/README.md b/docs/README.md index 8ea20d1..13b6303 100644 --- a/docs/README.md +++ b/docs/README.md @@ -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 diff --git a/docs/checklist-verifica-sito.md b/docs/checklist-verifica-sito.md new file mode 100644 index 0000000..3845a9d --- /dev/null +++ b/docs/checklist-verifica-sito.md @@ -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//`: 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. diff --git a/docs/legacy-fastapi-notes.md b/docs/legacy-fastapi-notes.md index ee449d5..6cfa502 100644 --- a/docs/legacy-fastapi-notes.md +++ b/docs/legacy-fastapi-notes.md @@ -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 ``` diff --git a/docs/setup.md b/docs/setup.md index 1cb196a..daf20d1 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -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 diff --git a/docs/sito-e-app.md b/docs/sito-e-app.md index 41dc638..6094102 100644 --- a/docs/sito-e-app.md +++ b/docs/sito-e-app.md @@ -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 diff --git a/roadmap.md b/roadmap.md index 76cfc2a..5e66aa8 100644 --- a/roadmap.md +++ b/roadmap.md @@ -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//` 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 diff --git a/tests/django/test_journey.py b/tests/django/test_journey.py new file mode 100644 index 0000000..dee6fed --- /dev/null +++ b/tests/django/test_journey.py @@ -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'