Files
plm-lottery/apps/web/player_views.py
T
davideandClaude Sonnet 5.5 42e5e33371 A7: player area - play, wallet, movements (WEB-03, WEB-05, WEB-20..27)
Gioca: the round, the player's funds and their bet; the bet is two steps
(a confirmation screen that sends nothing, then an explicit confirm) with a
fresh idempotency key per screen, and the server re-checks everything.
Portafoglio: spendable apart from in-confirmation, deposit address with a QR
of the player's own address, copy button, simulated test deposits.
Movimenti: the player's own ledger, paged, stacked as cards on a phone.
GET /app/stato/ feeds the page and its polling. Every view takes the user from
the session only. Checked end to end in a real browser (Playwright): status
moves from pending to confirmed without a reload, a double click is one bet.
Mutation checks: cross-account leak, non-idempotent POST and unrestricted
test-deposit amounts are all caught.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-16 14:41:27 +01:00

177 lines
7.8 KiB
Python

"""The player area (WEB-20 .. WEB-27, roadmap A7). Every view needs a session and reads or changes only the
signed-in player's own data (WEB-03): no view takes a user id from the request."""
import io
from uuid import UUID, uuid4
import qrcode
import qrcode.image.svg
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.http import Http404, HttpResponse, JsonResponse
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_POST
from apps.lottery.addresses import participant_address
from apps.lottery.balances import balance_of
from apps.lottery.errors import LedgerError
from apps.lottery.format import plm_text
from apps.lottery.ledger import get_ledger
from apps.lottery.messages import ledger_error_text
from apps.lottery.models import SATS_PER_PLM, Movement
from apps.lottery.player import full_state, player_state
from apps.lottery.status import public_state
# The test deposits a player can ask for on the simulated ledger (WEB-26): fixed, so a tampered form gets nothing else.
SIMULATED_DEPOSITS_PLM = (10, 50, 100)
KIND_LABELS = {"deposit": "Deposito", "bet": "Puntata", "win": "Vincita", "refund": "Rimborso", "withdrawal": "Prelievo"}
STATUS_LABELS = {"pending": "In conferma", "confirmed": "Confermato", "failed": "Non riuscito"}
MOVEMENTS_PER_PAGE = 25
def _uuid(value: str | None) -> UUID | None:
try:
return UUID(value or "")
except ValueError:
return None
# --- play --------------------------------------------------------------------------------------
@never_cache
@login_required
def play(request):
"""«Gioca»: the round, the player's funds and their bet in it (WEB-20)."""
state = full_state(request.user)
return render(request, "web/app_home.html", {"s": state, "me": state["me"], "poll_url": "/app/stato/"})
@never_cache
@login_required
def player_state_json(request):
"""The same, as JSON, for the page to poll (WEB-05, WEB-27): the player's own data only."""
return JsonResponse(full_state(request.user))
@never_cache
@login_required
def bet(request):
"""The bet in two steps (WEB-22): GET shows round and amount and asks for an explicit confirmation; POST sends
it. The server decides — round, deadline, quota, limits and funds are all checked again in the ledger — and
the request carries its own idempotency key, so a double send is one bet (WEB-23)."""
public = public_state()
if request.method == "POST":
round_id = request.POST.get("round_id", "")
request_id = _uuid(request.POST.get("request_id"))
if not round_id.isdigit() or request_id is None:
messages.error(request, ledger_error_text("missing_request_id", {}))
return redirect("web:app-home")
try:
result = get_ledger().place_bet(request.user, int(round_id), request_id=request_id)
except LedgerError as error:
messages.error(request, ledger_error_text(error.code, error.params))
return redirect("web:app-home")
if result.replayed:
messages.info(request, "Questa puntata era già stata registrata: non è stata addebitata due volte.")
else:
messages.success(request, "Puntata inviata: è in attesa di conferma.")
return redirect("web:app-home")
me = player_state(request.user, public=public)
if not me["can_bet"]:
if me["participation"] is not None:
text = ledger_error_text("already_betting", {})
else:
text = me["bet_blocker"] or ledger_error_text("round_closing", {})
messages.error(request, text)
return redirect("web:app-home")
return render(request, "web/bet_confirm.html", {"s": public, "me": me, "request_id": uuid4()})
# --- wallet ------------------------------------------------------------------------------------
def _network_label() -> str:
return {"regtest": "PLM regtest (rete di prova)", "mainnet": "PLM mainnet"}[settings.PLM_NETWORK]
@never_cache
@login_required
def wallet(request):
"""«Portafoglio»: spendable funds apart from funds in confirmation, and where to deposit (WEB-21)."""
balance = balance_of(request.user)
pending = Movement.objects.filter(user=request.user, kind="deposit", status="pending").order_by("-created_at")
context = {
"spendable_text": plm_text(balance.spendable_sats), "incoming_text": plm_text(balance.incoming_sats),
"pending_deposits": [{"amount_text": plm_text(m.amount_sats), "since": m.created_at} for m in pending],
"address": participant_address(request.user), "network_label": _network_label(),
"simulated": settings.LEDGER_BACKEND == "simulated",
"simulated_amounts": [{"plm": n, "text": plm_text(n * SATS_PER_PLM)} for n in SIMULATED_DEPOSITS_PLM],
"request_id": uuid4(),
}
return render(request, "web/wallet.html", context)
@never_cache
@login_required
def wallet_qr(request):
"""The QR of the player's own deposit address — never an address taken from the request (WEB-03, WEB-21)."""
image = qrcode.make(participant_address(request.user), image_factory=qrcode.image.svg.SvgPathImage, box_size=10)
buffer = io.BytesIO()
image.save(buffer)
return HttpResponse(buffer.getvalue(), content_type="image/svg+xml")
@never_cache
@login_required
@require_POST
def simulated_deposit(request):
"""Test funds for the simulated ledger (WEB-26): they arrive «in conferma» and the worker confirms them a few
seconds later, so the whole path can be seen. Not available when the ledger is real."""
if settings.LEDGER_BACKEND != "simulated":
raise Http404
request_id = _uuid(request.POST.get("request_id"))
amount = request.POST.get("amount", "")
if request_id is None or not amount.isdigit() or int(amount) not in SIMULATED_DEPOSITS_PLM:
messages.error(request, "La richiesta di deposito non è valida.")
return redirect("web:wallet")
try:
result = get_ledger().deposit(request.user, int(amount) * SATS_PER_PLM, request_id=request_id, confirmed=False)
except LedgerError as error:
messages.error(request, ledger_error_text(error.code, error.params))
return redirect("web:wallet")
if result.replayed:
messages.info(request, "Questo deposito era già stato registrato.")
else:
messages.success(request, f"Deposito di prova di {plm_text(int(amount) * SATS_PER_PLM)} in conferma.")
return redirect("web:wallet")
# --- history -----------------------------------------------------------------------------------
@never_cache
@login_required
def movements(request):
"""«Movimenti»: deposits, bets, wins and withdrawals of this player, newest first (WEB-25)."""
queryset = (Movement.objects.filter(user=request.user).select_related("chain_transaction")
.order_by("-created_at", "-id"))
page = Paginator(queryset, MOVEMENTS_PER_PAGE).get_page(request.GET.get("pagina"))
rows = []
for movement in page:
txid = movement.chain_transaction.current_txid if movement.chain_transaction_id else None
rows.append({
"when": movement.created_at, "kind": KIND_LABELS[movement.kind], "status": STATUS_LABELS[movement.status],
"status_code": movement.status, "amount_text": ("+" if movement.amount_sats > 0 else "") + plm_text(movement.amount_sats),
"credit": movement.amount_sats > 0, "round_id": movement.round_id,
"txid": txid, "txid_short": f"{txid[:10]}…{txid[-6:]}" if txid else "",
"txid_url": settings.EXPLORER_TX_URL.replace("{txid}", txid) if txid and settings.EXPLORER_TX_URL else "",
"simulated": bool(txid) and settings.LEDGER_BACKEND == "simulated",
})
return render(request, "web/movements.html", {"rows": rows, "page": page})