A9: operations console, three pause commands, admin and player reports (WEB-30..32, WEB-40..44, WEB-55, AUD-48)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
davideandClaude Sonnet 5.5 committed 2026-11-16 15:03:22 +01:00
1 parent 3d1e820564
commit eab141f467
24 files changed
+928 -11

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–A8 done). The suite has 1120 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–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).
**[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
```
1120 unit tests cover HD derivation, PSBT building, the Electrum client, bets,
1156 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
+54 -1
View File
@@ -1,6 +1,59 @@
"""Users in the admin (WEB-32). Staff can deactivate or promote an account but never delete one: a user's
ledger rows are PROTECTed (DAT-76), and a deactivation is an audited action. A user's game records are shown
read-only on the same page."""
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from apps.lottery import audit
from apps.lottery.models import Movement, Participation
from .models import User
admin.site.register(User, UserAdmin)
class ReadOnlyInline(admin.TabularInline):
extra = 0
can_delete = False
show_change_link = False
def has_add_permission(self, request, obj=None):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
class ParticipationInline(ReadOnlyInline):
model = Participation
fields = ("round", "status", "bet_amount_sats", "created_at")
readonly_fields = fields
ordering = ("-id",)
max_num = 0
verbose_name_plural = "Participations (read-only)"
class MovementInline(ReadOnlyInline):
model = Movement
fields = ("kind", "status", "amount_sats", "round", "created_at")
readonly_fields = fields
ordering = ("-id",)
max_num = 0
verbose_name_plural = "Movements (read-only)"
@admin.register(User)
class AccountAdmin(UserAdmin):
inlines = [ParticipationInline, MovementInline]
def has_delete_permission(self, request, obj=None):
return False
def save_model(self, request, obj, form, change):
super().save_model(request, obj, form, change)
if change and {"is_active", "is_staff", "is_superuser"} & set(form.changed_data):
audit.record("user_changed", actor=request.user, subject_type="user", subject_id=obj.pk,
payload={name: getattr(obj, name) for name in ("is_active", "is_staff", "is_superuser")
if name in form.changed_data})
+7
View File
@@ -68,3 +68,10 @@ class PasswordChangeForm(forms.Form):
cleaned["new_password"] != cleaned["new_password_confirm"]:
self.add_error("new_password_confirm", "Le due password non coincidono.")
return cleaned
class ReportForm(forms.Form):
"""WEB-55: a problem report from the profile."""
text = forms.CharField(label="Descrivi il problema", min_length=5, max_length=1000, strip=True,
widget=forms.Textarea(attrs={"rows": 4, "maxlength": 1000}))
@@ -18,6 +18,23 @@
<button class="button" type="submit">Aggiorna la password</button>
</form>
</section>
<section class="card narrow" aria-labelledby="segnalazioni">
<h2 id="segnalazioni">Segnala un problema</h2>
<form method="post" action="{% url 'accounts:report' %}" novalidate>
{% csrf_token %}
{% include "accounts/_form_errors.html" with form=report_form %}
{% for field in report_form %}{% include "accounts/_field.html" %}{% endfor %}
<button class="button" type="submit">Invia la segnalazione</button>
</form>
{% if reports %}
<h3>Le tue segnalazioni</h3>
<ul class="plain">
{% for report in reports %}
<li><strong>{{ report.get_status_display }}</strong> · {{ report.created_at|date:"j F Y H:i" }} UTC<br>{{ report.text|linebreaksbr }}</li>
{% endfor %}
</ul>
{% endif %}
</section>
<section class="card narrow">
<h2>Esci</h2>
<form method="post" action="{% url 'accounts:logout' %}">
+1
View File
@@ -36,6 +36,7 @@ LOGIN = Backoff("login", threshold=5, base_delay=2.0, max_delay=300.0, decay_sec
LOGIN_IP = Backoff("login_ip", threshold=20, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
CHANGE_PASSWORD = Backoff("chpwd", threshold=5, base_delay=2.0, max_delay=300.0, decay_seconds=900.0)
REGISTER = Quota("register", limit=5, window_seconds=3600.0)
REPORT = Quota("report", limit=10, window_seconds=3600.0) # WEB-55: per user
_KEY_MAX = 150
+1
View File
@@ -8,4 +8,5 @@ urlpatterns = [
path("registrati/", views.register_view, name="register"),
path("esci/", views.logout_view, name="logout"),
path("app/profilo/", views.profile_view, name="profile"),
path("app/profilo/segnalazioni/", views.report_view, name="report"),
]
+33 -3
View File
@@ -11,10 +11,11 @@ from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods, require_POST
from apps.lottery import audit
from apps.lottery.models import Report
from . import throttle
from .client_ip import client_ip
from .forms import LoginForm, PasswordChangeForm, RegisterForm
from .forms import LoginForm, PasswordChangeForm, RegisterForm, ReportForm
from .models import User
BACKEND = "apps.accounts.backends.CaseInsensitiveBackend"
@@ -107,6 +108,35 @@ def logout_view(request):
return redirect(settings.LOGOUT_REDIRECT_URL)
def _profile_context(request, *, form=None, report_form=None) -> dict:
"""Only the signed-in user's own data and reports (WEB-03)."""
return {
"form": form or PasswordChangeForm(request.user),
"report_form": report_form or ReportForm(),
"reports": Report.objects.filter(user=request.user).order_by("-created_at", "-id"),
}
@never_cache
@login_required
@require_POST
def report_view(request):
"""WEB-55: send a problem report. A rejected form does not use the quota; a sent one does."""
key = str(request.user.pk)
wait = throttle.retry_after(throttle.REPORT, key)
form = ReportForm(request.POST)
if wait > 0:
return _too_many(request, "accounts/profile.html", _profile_context(request, report_form=form), wait)
if not form.is_valid():
return render(request, "accounts/profile.html", _profile_context(request, report_form=form), status=400)
with transaction.atomic():
report = Report.objects.create(user=request.user, text=form.cleaned_data["text"])
audit.record("report_submitted", actor=request.user, subject_type="report", subject_id=report.pk)
throttle.record(throttle.REPORT, key)
messages.success(request, "Segnalazione inviata. Ne vedrai lo stato qui sotto.")
return redirect("accounts:profile")
@never_cache
@login_required
@require_http_methods(["GET", "POST"])
@@ -116,7 +146,7 @@ def profile_view(request):
key = str(request.user.pk)
wait = throttle.retry_after(throttle.CHANGE_PASSWORD, key)
if wait > 0:
return _too_many(request, "accounts/profile.html", {"form": form}, wait)
return _too_many(request, "accounts/profile.html", _profile_context(request, form=form), wait)
if form.is_valid():
if not request.user.check_password(form.cleaned_data["current_password"]):
# SEC-54: a stolen session must not be able to guess the password and lock the owner out.
@@ -133,4 +163,4 @@ def profile_view(request):
update_session_auth_hash(request, request.user)
messages.success(request, "Password aggiornata. Le altre sessioni sono state chiuse.")
return redirect("accounts:profile")
return render(request, "accounts/profile.html", {"form": form})
return render(request, "accounts/profile.html", _profile_context(request, form=form))
+77
View File
@@ -0,0 +1,77 @@
"""Admin for the lottery tables (WEB-32): closed rounds, transactions, movements and the audit are read-only;
reports are managed by changing their status, which is audited."""
from django.contrib import admin
from django.db import transaction
from . import audit
from .models import AuditEntry, ChainTransaction, Movement, Participation, Report, Round
class ReadOnlyAdmin(admin.ModelAdmin):
def has_add_permission(self, request):
return False
def has_change_permission(self, request, obj=None):
return False
def has_delete_permission(self, request, obj=None):
return False
@admin.register(Round)
class RoundAdmin(ReadOnlyAdmin):
list_display = ("id", "status", "opened_at", "closed_at", "pool_amount_sats")
list_filter = ("status",)
@admin.register(Participation)
class ParticipationAdmin(ReadOnlyAdmin):
list_display = ("id", "round", "user", "status", "bet_amount_sats")
list_filter = ("status",)
@admin.register(Movement)
class MovementAdmin(ReadOnlyAdmin):
list_display = ("id", "user", "kind", "status", "amount_sats", "created_at")
list_filter = ("kind", "status")
@admin.register(ChainTransaction)
class ChainTransactionAdmin(ReadOnlyAdmin):
list_display = ("id", "kind", "status", "current_txid", "created_at")
list_filter = ("kind", "status")
exclude = ("raw_hex",)
@admin.register(AuditEntry)
class AuditEntryAdmin(ReadOnlyAdmin):
list_display = ("created_at", "actor_label", "action", "outcome", "subject_type", "subject_id")
list_filter = ("action", "outcome")
search_fields = ("actor_label", "reason")
@admin.register(Report)
class ReportAdmin(admin.ModelAdmin):
list_display = ("id", "user", "status", "created_at")
list_filter = ("status",)
fields = ("user", "text", "created_at", "status", "status_changed_at")
readonly_fields = ("user", "text", "created_at", "status_changed_at")
def has_add_permission(self, request):
return False
def has_delete_permission(self, request, obj=None):
return False
def save_model(self, request, obj, form, change):
if not (change and "status" in form.changed_data):
return
from django.utils import timezone
before = form.initial.get("status")
with transaction.atomic():
obj.status_changed_at = timezone.now()
obj.save(update_fields=["status", "status_changed_at"])
audit.record("report_status_changed", actor=request.user, subject_type="report", subject_id=obj.pk,
payload={"from": before, "to": obj.status})
+170
View File
@@ -0,0 +1,170 @@
"""What the operations console shows and does (WEB-31, WEB-40..44, ADR-57).
The three pause switches are three distinct commands, each with its own permission. A command is
refused for anyone without that permission whatever the view did before (WEB-44), needs a reason
(WEB-43), and writes its audit row in the same transaction as the change (ADR-53). A refusal is
audited too, with outcome `denied`.
"""
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Any
from django.conf import settings
from django.core.exceptions import PermissionDenied, ValidationError
from django.db import transaction
from django.utils import timezone
from . import audit
from .lifecycle import get_active_round
from .models import AuditEntry, ChainTransaction, LotteryConfig, Movement, Participation, Round
from .rules import round_deadline
MIN_REASON = 5
MAX_REASON = 500
WORKER_STALE_AFTER = timedelta(seconds=30) # the worker ticks every 5 s: six missed ticks is a dead worker
LATE_AFTER = timedelta(minutes=10) # a pending operation older than this needs a look
@dataclass(frozen=True)
class Command:
key: str # the URL segment
field: str # the LotteryConfig switch
permission: str # codename in the `lottery` app
title_on: str
title_off: str
action_on: str # audit actions
action_off: str
continues: tuple[str, ...] # what keeps running while the switch is on (WEB-43)
before_resume: tuple[str, ...] # what to check before switching it off (WEB-43)
COMMANDS: dict[str, Command] = {
c.key: c
for c in (
Command(
"pausa-dopo-round", "pause_after_round", "pause_after_round",
"Pausa dopo il round in corso", "Riprendi i round",
"pause_after_round_enabled", "pause_after_round_disabled",
continues=("Il round attivo prosegue fino al pagamento del vincitore.",
"Le puntate di quel round restano aperte fino alla scadenza.",
"Il round successivo non si apre."),
before_resume=("Il worker è attivo.", "Nessuna operazione in ritardo."),
),
Command(
"sospendi-puntate", "new_bets_suspended", "suspend_new_bets",
"Sospendi nuove puntate", "Riprendi le puntate",
"new_bets_suspended", "new_bets_resumed",
continues=("Le puntate già inviate restano monitorate e si confermano o si rifiutano come prima.",
"L'estrazione e il pagamento del round in corso non si fermano."),
before_resume=("Il worker è attivo.", "Nessuna operazione in ritardo.",
"La causa dell'incidente è chiusa."),
),
Command(
"sospendi-prelievi", "withdrawals_suspended", "suspend_withdrawals",
"Sospendi i prelievi", "Riprendi i prelievi",
"withdrawals_suspended", "withdrawals_resumed",
continues=("Le puntate e i round non cambiano.",
"I prelievi già inviati restano monitorati."),
before_resume=("Il saldo del portafoglio è riconciliato.", "Nessuna operazione in ritardo."),
),
)
}
def is_on(command: Command, config: LotteryConfig | None = None) -> bool:
return bool(getattr(config or LotteryConfig.get(), command.field))
def title(command: Command, config: LotteryConfig | None = None) -> str:
return command.title_off if is_on(command, config) else command.title_on
def can_view(user) -> bool:
return user.is_authenticated and user.is_active and user.is_staff and user.has_perm("lottery.view_console")
def can_run(user, command: Command) -> bool:
return user.is_authenticated and user.is_active and user.is_staff and user.has_perm(f"lottery.{command.permission}")
def clean_reason(reason: str) -> str:
reason = " ".join((reason or "").split())
if len(reason) < MIN_REASON:
raise ValidationError(f"Indica il motivo (almeno {MIN_REASON} caratteri).")
if len(reason) > MAX_REASON:
raise ValidationError(f"Il motivo è troppo lungo (al massimo {MAX_REASON} caratteri).")
return reason
def run_command(user, command: Command, enable: bool, reason: str) -> bool:
"""Set the command's switch to `enable` (explicit, so a double submit cannot flip it back). Returns False
when it was already in the wanted state (nothing changes, nothing is audited). Raises PermissionDenied (audited) or ValidationError (no reason)."""
if not can_run(user, command):
audit.record(command.action_on if enable else command.action_off,
actor=user if user.is_authenticated else None,
actor_label=user.get_username() if user.is_authenticated else "anonymous",
outcome=AuditEntry.Outcome.DENIED, subject_type="config", subject_id=1,
payload={"command": command.key})
raise PermissionDenied(command.key)
reason = clean_reason(reason)
with transaction.atomic():
config = LotteryConfig.get()
if getattr(config, command.field) == enable:
return False
setattr(config, command.field, enable)
config.save(update_fields=[command.field, "updated_at"])
audit.record(command.action_on if enable else command.action_off, actor=user, reason=reason,
subject_type="config", subject_id=1, payload={"command": command.key})
return True
def worker_alive(config: LotteryConfig, now: datetime) -> bool:
return config.worker_seen_at is not None and now - config.worker_seen_at <= WORKER_STALE_AFTER
def beat(now: datetime | None = None) -> None:
"""Called by the worker at every tick (WEB-31)."""
LotteryConfig.get()
LotteryConfig.objects.filter(pk=1).update(worker_seen_at=now or timezone.now())
def late_operations(now: datetime) -> dict[str, int]:
"""Operations that should have moved on by now (WEB-31)."""
limit = now - LATE_AFTER
overdue = 0
active = get_active_round()
if active is not None and now > round_deadline(active) + LATE_AFTER:
overdue = 1
return {
"pending_bets": Participation.objects.filter(status=Participation.Status.PENDING, created_at__lt=limit).count(),
"pending_movements": Movement.objects.filter(status=Movement.Status.PENDING, created_at__lt=limit).count(),
"pending_transactions": ChainTransaction.objects.filter(
status__in=[ChainTransaction.Status.BUILDING, ChainTransaction.Status.PENDING], created_at__lt=limit).count(),
"overdue_rounds": overdue,
}
def console_state(now: datetime | None = None) -> dict[str, Any]:
now = now or timezone.now()
config = LotteryConfig.get()
active = get_active_round()
late = late_operations(now)
reasons: dict[str, AuditEntry | None] = {}
for command in COMMANDS.values():
reasons[command.key] = (
AuditEntry.objects.filter(action=command.action_on, outcome=AuditEntry.Outcome.OK).order_by("-id").first()
if is_on(command, config) else None
)
return {
"now": now,
"config": config,
"round": active,
"deadline": round_deadline(active) if active is not None else None,
"worker_alive": worker_alive(config, now),
"worker_seen_at": config.worker_seen_at,
"backend": settings.LEDGER_BACKEND,
"late": late,
"late_total": sum(late.values()),
"pause_reasons": reasons,
}
@@ -19,8 +19,9 @@ def tick() -> None:
"""One pass over everything the worker is responsible for."""
from django.conf import settings
from apps.lottery import lifecycle, simulation
from apps.lottery import console, lifecycle, simulation
console.beat() # WEB-31: proof of life, before the work that might fail
if settings.LEDGER_BACKEND == "simulated":
simulation.settle()
lifecycle.tick()
@@ -0,0 +1,41 @@
# Generated by Django 5.2.19 on 2026-11-16 13:55
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lottery', '0002_audit_append_only_triggers'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.AlterModelOptions(
name='lotteryconfig',
options={'permissions': [('view_console', 'Can open the operations console'), ('pause_after_round', 'Can pause the lottery after the round in progress'), ('suspend_new_bets', 'Can suspend new bets'), ('suspend_withdrawals', 'Can suspend withdrawals')]},
),
migrations.AddField(
model_name='lotteryconfig',
name='worker_seen_at',
field=models.DateTimeField(blank=True, null=True),
),
migrations.CreateModel(
name='Report',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('text', models.TextField(max_length=1000)),
('status', models.CharField(choices=[('open', 'Aperta'), ('read', 'Letta'), ('resolved', 'Risolta')], default='open', max_length=16)),
('created_at', models.DateTimeField(default=django.utils.timezone.now)),
('status_changed_at', models.DateTimeField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='reports', to=settings.AUTH_USER_MODEL)),
],
options={
'indexes': [models.Index(fields=['user', '-created_at'], name='lottery_rep_user_id_2851c0_idx'), models.Index(fields=['status'], name='lottery_rep_status_badbe2_idx')],
'constraints': [models.CheckConstraint(condition=models.Q(('status__in', ['open', 'read', 'resolved'])), name='lottery_report_status_valid')],
},
),
]
+37
View File
@@ -36,9 +36,19 @@ class LotteryConfig(models.Model):
new_bets_suspended = models.BooleanField(default=False)
withdrawals_suspended = models.BooleanField(default=False)
# WEB-31: written by the worker at every tick; the console reads it to tell a live worker from a dead one.
worker_seen_at = models.DateTimeField(null=True, blank=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
# WEB-30, WEB-44: one explicit permission per operational command, checked in the view and again in the service.
permissions = [
("view_console", "Can open the operations console"),
("pause_after_round", "Can pause the lottery after the round in progress"),
("suspend_new_bets", "Can suspend new bets"),
("suspend_withdrawals", "Can suspend withdrawals"),
]
constraints = [
models.CheckConstraint(condition=Q(id=1), name="lottery_config_single_row"),
models.CheckConstraint(condition=Q(bet_amount_sats__gt=0), name="lottery_config_bet_positive"),
@@ -383,3 +393,30 @@ class AuditEntry(models.Model):
def __str__(self) -> str:
return f"{self.created_at:%Y-%m-%d %H:%M} {self.actor_label} {self.action}"
class Report(models.Model):
"""A problem report written by a player from the profile (WEB-55). Staff reads it and changes its
status from the admin; each status change is in the audit."""
class Status(models.TextChoices):
OPEN = "open", "Aperta"
READ = "read", "Letta"
RESOLVED = "resolved", "Risolta"
MAX_LENGTH = 1000
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="reports")
text = models.TextField(max_length=MAX_LENGTH)
status = models.CharField(max_length=16, choices=Status.choices, default=Status.OPEN)
created_at = models.DateTimeField(default=timezone.now)
status_changed_at = models.DateTimeField(null=True, blank=True)
class Meta:
indexes = [models.Index(fields=["user", "-created_at"]), models.Index(fields=["status"])]
constraints = [
models.CheckConstraint(condition=Q(status__in=["open", "read", "resolved"]), name="lottery_report_status_valid"),
]
def __str__(self) -> str:
return f"Report {self.pk} ({self.status})"
+27
View File
@@ -0,0 +1,27 @@
{% extends "web/base.html" %}
{% block title %}{{ title }} · PLM Lottery{% endblock %}
{% block content %}
<h1>{{ title }}</h1>
<section class="card narrow">
<h2>Cosa continua</h2>
<ul>{% for line in cmd.continues %}<li>{{ line }}</li>{% endfor %}</ul>
{% if not enable %}
<h2>Verifiche prima della ripresa</h2>
<ul>{% for line in cmd.before_resume %}<li>{{ line }}</li>{% endfor %}</ul>
<p class="hint">
Stato ora: worker {% if worker_alive %}attivo{% else %}<strong>fermo</strong>{% endif %},
operazioni in ritardo: {{ late_total }}.
</p>
{% endif %}
<form method="post" novalidate>
{% csrf_token %}
<input type="hidden" name="enable" value="{% if enable %}1{% else %}0{% endif %}">
{% if error %}<p class="message error" role="alert">{{ error }}</p>{% endif %}
<label for="reason">Motivo (resta nell'audit)</label>
<textarea id="reason" name="reason" rows="3" maxlength="500" required>{{ reason_text }}</textarea>
<p><label><input type="checkbox" name="confirm" value="1"> Ho letto cosa comporta e confermo.</label></p>
<button class="button" type="submit">{{ title }}</button>
<a class="button secondary" href="{% url 'ops:dashboard' %}">Annulla</a>
</form>
</section>
{% endblock %}
+56
View File
@@ -0,0 +1,56 @@
{% extends "web/base.html" %}
{% block title %}Console operativa · PLM Lottery{% endblock %}
{% block content %}
<h1>Console operativa</h1>
<section class="card" aria-labelledby="stato">
<h2 id="stato">Stato</h2>
<dl class="facts">
<dt>Round in corso</dt>
<dd>{% if round %}n. {{ round.pk }} · {{ round.get_status_display }}{% else %}nessuno{% endif %}</dd>
<dt>Prossima scadenza</dt>
<dd>{% if round and round.status == "open" %}{{ deadline|date:"H:i:s" }} UTC{% else %}—{% endif %}</dd>
<dt>Worker</dt>
<dd>
{% if worker_alive %}attivo · ultimo battito {{ worker_seen_at|time:"H:i:s" }} UTC
{% elif worker_seen_at %}<strong>fermo</strong> · ultimo battito {{ worker_seen_at|date:"j F H:i:s" }} UTC
{% else %}<strong>mai avviato</strong>{% endif %}
</dd>
<dt>Catena</dt>
<dd>{% if backend == "simulated" %}simulata (fase A): nessun nodo Electrum da controllare{% else %}Electrum: controllo non ancora disponibile{% endif %}</dd>
<dt>Ultima riconciliazione</dt>
<dd>non ancora disponibile (arriva con la fase B)</dd>
<dt>Operazioni in ritardo</dt>
<dd>
{% if late_total %}
<strong>{{ late_total }}</strong>:
{{ late.pending_bets }} puntate in attesa, {{ late.pending_movements }} movimenti in attesa,
{{ late.pending_transactions }} transazioni in attesa{% if late.overdue_rounds %}, il round oltre la scadenza{% endif %}
{% else %}nessuna{% endif %}
</dd>
</dl>
</section>
<section class="card" aria-labelledby="comandi">
<h2 id="comandi">Pause</h2>
<ul class="plain">
{% for item in commands %}
<li>
<strong>{{ item.command.title_on }}</strong> — {% if item.on %}<strong>attiva</strong>{% else %}non attiva{% endif %}
{% if item.reason %}<br><span class="hint">Dal {{ item.reason.created_at|date:"j F H:i" }} UTC, {{ item.reason.actor_label }}: {{ item.reason.reason }}</span>{% endif %}
<br>
{% if item.allowed %}
<a class="button small{% if item.on %} secondary{% endif %}" href="{% url 'ops:command' item.command.key %}">{{ item.title }}…</a>
{% else %}
<span class="hint">Non hai il permesso per questo comando.</span>
{% endif %}
</li>
{% endfor %}
</ul>
</section>
<section class="card">
<h2>Altri strumenti</h2>
<p><a href="/admin/">Amministrazione: utenti, segnalazioni, audit</a></p>
</section>
{% endblock %}
+9
View File
@@ -0,0 +1,9 @@
from django.urls import path
from . import views
app_name = "ops"
urlpatterns = [
path("ops/", views.dashboard, name="dashboard"),
path("ops/<slug:key>/", views.command, name="command"),
]
+76
View File
@@ -0,0 +1,76 @@
"""The operations console (WEB-30..33, WEB-40..44, roadmap A9). Every view and every action checks the
specific permission; being logged in, or being staff, is not enough."""
from django.contrib import messages
from django.contrib.auth.views import redirect_to_login
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import Http404
from django.shortcuts import redirect, render
from django.views.decorators.cache import never_cache
from django.views.decorators.http import require_http_methods
from apps.lottery import console
from apps.lottery.models import LotteryConfig
def _gate(request, allowed: bool):
"""Anonymous visitors go to sign-in; anyone signed in without the permission gets 403."""
if not request.user.is_authenticated:
return redirect_to_login(request.get_full_path(), "/accedi/")
if not allowed:
raise PermissionDenied
return None
@never_cache
@require_http_methods(["GET"])
def dashboard(request):
if (denied := _gate(request, console.can_view(request.user))) is not None:
return denied
state = console.console_state()
commands = [
{"command": c, "on": console.is_on(c, state["config"]), "title": console.title(c, state["config"]),
"allowed": console.can_run(request.user, c), "reason": state["pause_reasons"][c.key]}
for c in console.COMMANDS.values()
]
return render(request, "ops/dashboard.html", {**state, "commands": commands})
@never_cache
@require_http_methods(["GET", "POST"])
def command(request, key: str):
cmd = console.COMMANDS.get(key)
if cmd is None:
raise Http404
if request.user.is_authenticated and not (console.can_view(request.user) and console.can_run(request.user, cmd)):
if request.method == "POST":
try:
console.run_command(request.user, cmd, True, "") # refuses, and records the refusal in the audit
except PermissionDenied:
pass
raise PermissionDenied
if (denied := _gate(request, True)) is not None:
return denied
config = LotteryConfig.get()
enable = not console.is_on(cmd, config)
state = console.console_state()
context = {"cmd": cmd, "enable": enable, "title": console.title(cmd, config), **state, "reason_text": ""}
if request.method == "POST":
# The page was rendered for one direction; a stale form must not flip the switch back.
wanted = request.POST.get("enable") == "1"
reason = request.POST.get("reason", "")
context["reason_text"] = reason
if request.POST.get("confirm") != "1":
context["error"] = "Conferma di aver letto cosa comporta."
else:
try:
changed = console.run_command(request.user, cmd, wanted, reason)
except ValidationError as error:
context["error"] = error.messages[0]
else:
if changed:
messages.success(request, f"Comando eseguito: {cmd.title_on if wanted else cmd.title_off}.")
else:
messages.info(request, "Il comando era già nello stato richiesto: nulla è cambiato.")
return redirect("ops:dashboard")
return render(request, "ops/command.html", context)
+1
View File
@@ -23,6 +23,7 @@
<a href="{% url 'web:app-home' %}"{% if current == 'web:app-home' or current == 'web:bet' %} aria-current="page"{% endif %}>Gioca</a>
<a href="{% url 'web:wallet' %}"{% if current == 'web:wallet' %} aria-current="page"{% endif %}>Portafoglio</a>
<a href="{% url 'web:movements' %}"{% if current == 'web:movements' %} aria-current="page"{% endif %}>Movimenti</a>
{% if user.is_staff and perms.lottery.view_console %}<a href="{% url 'ops:dashboard' %}">Console</a>{% endif %}
<a href="{% url 'accounts:profile' %}"{% if current == 'accounts:profile' %} aria-current="page"{% endif %}>Profilo</a>
{% endwith %}
<form class="inline" method="post" action="{% url 'accounts:logout' %}">
+1
View File
@@ -4,6 +4,7 @@ from django.urls import include, path
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("apps.accounts.urls")),
path("", include("apps.ops.urls")),
path("", include("apps.web.urls")),
]
+11
View File
@@ -698,3 +698,14 @@ nome tra parentesi quadre nel log è il modulo (`app.rounds.scheduler`, ecc.).
*Stato:* implementato (A2) ·
*Codice:* `apps/lottery/audit.py:record`, `apps/lottery/models.py:AuditEntry`, `apps/lottery/migrations/0002_audit_append_only_triggers.py` ·
*Test:* `tests/django/test_models.py::test_an_audit_row_cannot_be_changed_with_raw_sql_either`, `test_the_audit_is_written_in_the_same_transaction_as_the_change`
- **[AUD-48]** **Azioni della console, delle segnalazioni e degli utenti.** Ogni comando di `/ops/` scrive una riga con attore,
motivo (obbligatorio, 5–500 caratteri) e `payload {"command"}`: `pause_after_round_enabled`/`pause_after_round_disabled`,
`new_bets_suspended`/`new_bets_resumed`, `withdrawals_suspended`/`withdrawals_resumed` ([WEB-40](sito-e-app.md),
[WEB-41](sito-e-app.md), [WEB-42](sito-e-app.md)). Un comando negato (giocatore o staff senza il permesso) scrive la stessa
azione con esito `denied` e nessun cambiamento; un comando già nello stato richiesto non scrive nulla. Le segnalazioni scrivono
`report_submitted` (invio) e `report_status_changed` (`payload {"from", "to"}`, da `/admin/`); la modifica di `is_active`,
`is_staff` o `is_superuser` di un utente in `/admin/` scrive `user_changed`.
*Stato:* implementato (A9) ·
*Codice:* `apps/lottery/console.py:run_command`, `apps/lottery/admin.py:ReportAdmin.save_model`, `apps/accounts/admin.py:AccountAdmin.save_model`, `apps/accounts/views.py:report_view` ·
*Test:* `tests/django/test_console.py::test_each_command_switches_only_its_own_flag_and_is_audited`, `test_a_player_cannot_run_a_command_and_the_refusal_is_audited`, `test_changing_a_report_status_in_the_admin_is_audited`, `test_deactivating_a_user_in_the_admin_is_audited`
+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 — 1120 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 — 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.
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 1120 tests
python -m pytest # all 1156 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
```
+9 -1
View File
@@ -168,12 +168,15 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
- **[WEB-30]** Ogni operatore ha un account staff individuale; `/ops/` e
`/admin/` richiedono i permessi espliciti, verificati nelle viste e nelle azioni.
*Stato:* implementato (A9): quattro permessi `lottery.view_console`, `pause_after_round`, `suspend_new_bets`, `suspend_withdrawals`; un giocatore o uno staff senza permesso riceve 403, un anonimo è rimandato ad `/accedi/` · *Codice:* `apps/ops/views.py`, `apps/lottery/console.py:can_view`, `can_run` · *Test:* `tests/django/test_console.py::test_a_player_cannot_open_the_console`, `test_staff_without_the_permission_cannot_open_the_console`
- **[WEB-31]** `/ops/` mostra round in corso, prossima scadenza, salute di
Electrum e del worker, operazioni in ritardo, ultima riconciliazione e il
motivo di eventuali pause.
*Stato:* implementato (A9) per round, scadenza, worker (battito scritto a ogni tick, «fermo» oltre 30 s), operazioni in ritardo (in attesa da oltre 10 minuti) e motivo delle pause; Electrum e ultima riconciliazione arrivano con la fase B (la pagina lo dice) · *Codice:* `apps/lottery/console.py:console_state`, `beat`, `late_operations` · *Test:* `tests/django/test_console.py::test_the_worker_tick_leaves_a_heartbeat`, `test_a_silent_worker_is_reported_as_stopped`, `test_operations_pending_for_too_long_are_listed`, `test_the_pause_reason_is_shown_while_it_lasts`
- **[WEB-32]** Django Admin gestisce utenti e segnalazioni; round chiusi,
transazioni e audit sono in sola lettura. Le azioni operative passano dai
servizi della lotteria e registrano attore, data, azione, motivo ed esito.
*Stato:* implementato (A9): round, partecipazioni, movimenti, transazioni e audit senza aggiunta, modifica o cancellazione; l'utente non si cancella, la scheda mostra puntate e movimenti in sola lettura, e un cambio di `is_active`/`is_staff`/`is_superuser` è nell'audit ([AUD-48](audit-log.md)) · *Codice:* `apps/lottery/admin.py`, `apps/accounts/admin.py` · *Test:* `tests/django/test_console.py::test_game_records_are_read_only_in_the_admin`, `test_a_user_page_shows_game_records_and_cannot_delete_the_user`
- **[WEB-33]** Il recupero delle chiavi non è esposto dal pannello web: è una
procedura dedicata fuori dal web.
- **[WEB-34]** La MFA TOTP e il recupero dell'accesso sono requisiti di uscita
@@ -184,15 +187,20 @@ backend FastAPI (vedi [architettura.md](architettura.md)).
- **[WEB-40]** «Pausa dopo il round in corso»: il round attivo continua fino
al pagamento, il successivo resta sospeso.
*Stato:* implementato (A9) · *Codice:* `apps/lottery/console.py:COMMANDS`, `apps/lottery/lifecycle.py:open_new_round_if_needed` · *Test:* `tests/django/test_console.py::test_pausing_after_the_round_stops_the_next_one_from_opening`
- **[WEB-41]** «Sospendi nuove puntate»: comando distinto per gli incidenti;
nessuna nuova puntata, ma le operazioni già inviate restano monitorate.
*Stato:* implementato (A9): la home mostra «Manutenzione» e la puntata è rifiutata dal servizio · *Test:* `tests/django/test_console.py::test_suspending_bets_shows_maintenance_on_the_site_and_refuses_a_bet`
- **[WEB-42]** La sospensione dei prelievi è un comando separato dalle altre due.
*Stato:* implementato (A9) come interruttore separato con il proprio permesso; i prelievi esistono solo dalla fase B, quindi per ora ne cambia solo lo stato · *Test:* `tests/django/test_console.py::test_a_permission_for_one_command_does_not_open_the_others`
- **[WEB-43]** Pausa, ripresa e modifiche critiche richiedono conferma e
motivazione; la console mostra quali operazioni continuano e quali verifiche
servono prima della ripresa. Le pause automatiche si riesaminano dal servizio applicativo.
*Stato:* implementato (A9): la pagina del comando elenca cosa continua e, per la ripresa, le verifiche da fare con lo stato di worker e ritardi; servono motivo e conferma, e un invio ripetuto non rigira l'interruttore · *Test:* `tests/django/test_console.py::test_a_command_needs_a_reason_and_a_confirmation`, `test_the_command_page_says_what_continues_and_what_to_check_before_resuming`, `test_repeating_a_command_changes_nothing_and_adds_no_audit_row`
- **[WEB-44]** Ogni comando operativo è negato a un giocatore e a uno staff
senza il permesso specifico, si riflette sul sito con l'effetto previsto e
compare nell'audit.
*Stato:* implementato (A9): il permesso è controllato nella vista e di nuovo nel servizio, il rifiuto è nell'audit con esito `denied` · *Test:* `tests/django/test_console.py::test_a_player_cannot_run_a_command_and_the_refusal_is_audited`, `test_the_service_itself_refuses_without_the_permission`, `test_a_command_without_the_csrf_token_is_refused`
## 6 · Avvio in locale
@@ -252,4 +260,4 @@ FastAPI, che non è più nel compose.
- **[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/`).
*Stato:* implementato (A9): massimo 1000 caratteri, 10 invii all'ora per utente (un invio rifiutato dalla validazione non conta); il testo non è modificabile da `/admin/` · *Codice:* `apps/lottery/models.py:Report`, `apps/accounts/views.py:report_view`, `apps/lottery/admin.py:ReportAdmin` · *Test:* `tests/django/test_console.py::test_a_player_sends_a_report_and_sees_its_status`, `test_a_player_sees_only_their_own_reports`, `test_reports_are_limited_per_user`, `test_changing_a_report_status_in_the_admin_is_audited`
+1 -1
View File
@@ -32,7 +32,7 @@ Uscita: un giocatore completa il round dimostrativo in `localhost`, l'operatore
- [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.
- [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.
- [ ] **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.
- [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.
## Fase B — Integrazione del motore PLM
+293
View File
@@ -0,0 +1,293 @@
"""A9 — operations console, pauses, admin and reports: WEB-30, WEB-31, WEB-32, WEB-40, WEB-41, WEB-42, WEB-43,
WEB-44, WEB-55, ADR-57."""
from datetime import timedelta
from uuid import uuid4
import pytest
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Permission
from django.core.management import call_command
from django.test import Client
from django.utils import timezone
from apps.lottery import console, lifecycle
from apps.lottery.errors import LedgerError
from apps.lottery.ledger import get_ledger
from apps.lottery.models import AuditEntry, LotteryConfig, Movement, Report
User = get_user_model()
PASSWORD = "correct-horse-battery"
pytestmark = pytest.mark.django_db
ALL = ["view_console", "pause_after_round", "suspend_new_bets", "suspend_withdrawals"]
def player(name="mario"):
return User.objects.create_user(name, password=PASSWORD)
def staff(name="ops", perms=tuple(ALL)):
user = User.objects.create_user(name, password=PASSWORD, is_staff=True)
user.user_permissions.set(Permission.objects.filter(codename__in=perms, content_type__app_label="lottery"))
return user
def client_for(user):
client = Client()
client.force_login(user)
return client
def post(client, url, data):
return client.post(url, data)
def run(client, key, *, enable="1", reason="incident 42", confirm="1"):
return post(client, f"/ops/{key}/", {"enable": enable, "reason": reason, "confirm": confirm})
# --- who may enter (WEB-30) -----------------------------------------------------------------
def test_anonymous_visitors_are_sent_to_sign_in(client):
response = client.get("/ops/")
assert response.status_code == 302 and response["Location"].startswith("/accedi/")
def test_a_player_cannot_open_the_console(client):
assert client_for(player()).get("/ops/").status_code == 403
def test_staff_without_the_permission_cannot_open_the_console():
assert client_for(staff(perms=())).get("/ops/").status_code == 403
def test_staff_with_the_permission_sees_the_console():
html = client_for(staff()).get("/ops/").content.decode()
assert "Console operativa" in html and "Pausa dopo il round in corso" in html
def test_a_command_without_the_csrf_token_is_refused():
client = Client(enforce_csrf_checks=True)
client.force_login(staff())
response = client.post("/ops/sospendi-puntate/", {"enable": "1", "reason": "no token", "confirm": "1"})
assert response.status_code == 403 and not LotteryConfig.get().new_bets_suspended
# --- the three commands (WEB-40, WEB-41, WEB-42, WEB-44) ---------------------------------------
@pytest.mark.parametrize("key,field,on,off", [
("pausa-dopo-round", "pause_after_round", "pause_after_round_enabled", "pause_after_round_disabled"),
("sospendi-puntate", "new_bets_suspended", "new_bets_suspended", "new_bets_resumed"),
("sospendi-prelievi", "withdrawals_suspended", "withdrawals_suspended", "withdrawals_resumed"),
])
def test_each_command_switches_only_its_own_flag_and_is_audited(key, field, on, off):
user = staff()
client = client_for(user)
assert run(client, key, reason="planned maintenance").status_code == 302
config = LotteryConfig.get()
flags = {f: getattr(config, f) for f in ("pause_after_round", "new_bets_suspended", "withdrawals_suspended")}
assert flags == {f: f == field for f in flags}
entry = AuditEntry.objects.get(action=on)
assert (entry.actor, entry.reason, entry.outcome) == (user, "planned maintenance", "ok")
assert run(client, key, enable="0", reason="all clear").status_code == 302
assert not getattr(LotteryConfig.get(), field)
assert AuditEntry.objects.get(action=off).reason == "all clear"
@pytest.mark.parametrize("key", ["pausa-dopo-round", "sospendi-puntate", "sospendi-prelievi"])
def test_a_player_cannot_run_a_command_and_the_refusal_is_audited(key):
assert run(client_for(player()), key).status_code == 403
config = LotteryConfig.get()
assert not (config.pause_after_round or config.new_bets_suspended or config.withdrawals_suspended)
assert AuditEntry.objects.filter(outcome="denied", actor__username="mario").count() == 1
def test_a_permission_for_one_command_does_not_open_the_others():
client = client_for(staff(perms=("view_console", "suspend_new_bets")))
assert run(client, "sospendi-prelievi").status_code == 403
assert not LotteryConfig.get().withdrawals_suspended
assert run(client, "sospendi-puntate").status_code == 302
assert LotteryConfig.get().new_bets_suspended
def test_the_service_itself_refuses_without_the_permission():
"""The view is not the only gate: the service checks again (WEB-44)."""
with pytest.raises(Exception) as caught:
console.run_command(staff(perms=("view_console",)), console.COMMANDS["sospendi-puntate"], True, "because")
assert caught.type.__name__ == "PermissionDenied"
assert not LotteryConfig.get().new_bets_suspended
def test_a_command_needs_a_reason_and_a_confirmation():
client = client_for(staff())
assert "motivo" in run(client, "sospendi-puntate", reason=" ").content.decode()
assert "Conferma" in run(client, "sospendi-puntate", confirm="").content.decode()
assert not LotteryConfig.get().new_bets_suspended
assert not AuditEntry.objects.filter(action="new_bets_suspended").exists()
def test_repeating_a_command_changes_nothing_and_adds_no_audit_row():
client = client_for(staff())
run(client, "sospendi-puntate")
run(client, "sospendi-puntate") # a double submit
assert LotteryConfig.get().new_bets_suspended
assert AuditEntry.objects.filter(action="new_bets_suspended").count() == 1
def test_the_command_page_says_what_continues_and_what_to_check_before_resuming():
client = client_for(staff())
assert "Cosa continua" in client.get("/ops/sospendi-puntate/").content.decode()
run(client, "sospendi-puntate")
html = client.get("/ops/sospendi-puntate/").content.decode()
assert "Riprendi le puntate" in html and "Verifiche prima della ripresa" in html
# --- the site reflects the pause (WEB-44) -----------------------------------------------------
def test_suspending_bets_shows_maintenance_on_the_site_and_refuses_a_bet(client):
round_ = lifecycle.open_new_round_if_needed()
user = player()
ledger = get_ledger()
ledger.deposit(user, round_.bet_amount_sats * 2)
run(client_for(staff()), "sospendi-puntate")
state = client.get("/stato/").json()
assert state["state"] == "maintenance" and not state["can_participate"]
with pytest.raises(LedgerError) as refused:
ledger.place_bet(user, round_.pk, request_id=uuid4())
assert refused.value.code == "bets_suspended"
def test_pausing_after_the_round_stops_the_next_one_from_opening():
run(client_for(staff()), "pausa-dopo-round")
assert lifecycle.open_new_round_if_needed() is None
# --- what the console shows (WEB-31) -----------------------------------------------------------
def test_the_worker_tick_leaves_a_heartbeat():
assert not console.console_state()["worker_alive"]
call_command("run_worker", "--once")
assert console.console_state()["worker_alive"]
def test_a_silent_worker_is_reported_as_stopped():
console.beat(timezone.now() - timedelta(minutes=5))
html = client_for(staff()).get("/ops/").content.decode()
assert "fermo" in html
def test_operations_pending_for_too_long_are_listed():
user = player()
old = timezone.now() - console.LATE_AFTER - timedelta(minutes=1)
Movement.objects.create(user=user, kind="deposit", status="pending", amount_sats=5, created_at=old)
assert console.console_state()["late"]["pending_movements"] == 1
assert console.console_state()["late_total"] == 1
def test_the_pause_reason_is_shown_while_it_lasts():
client = client_for(staff())
run(client, "sospendi-puntate", reason="node unreachable")
assert "node unreachable" in client.get("/ops/").content.decode()
# --- reports (WEB-55) -------------------------------------------------------------------------
def test_a_player_sends_a_report_and_sees_its_status():
user = player()
client = client_for(user)
assert post(client, "/app/profilo/segnalazioni/", {"text": "The bet button is stuck"}).status_code == 302
report = Report.objects.get()
assert (report.user, report.status) == (user, "open")
assert AuditEntry.objects.filter(action="report_submitted", subject_id=str(report.pk)).exists()
html = client.get("/app/profilo/").content.decode()
assert "The bet button is stuck" in html and "Aperta" in html
def test_a_player_sees_only_their_own_reports():
Report.objects.create(user=player("luigi"), text="luigi's secret problem")
assert "luigi's secret problem" not in client_for(player()).get("/app/profilo/").content.decode()
def test_a_report_must_have_text_of_a_sane_length_and_a_refusal_does_not_use_the_quota():
client = client_for(player())
assert post(client, "/app/profilo/segnalazioni/", {"text": ""}).status_code == 400
assert post(client, "/app/profilo/segnalazioni/", {"text": "x" * 1001}).status_code == 400
assert not Report.objects.exists()
for number in range(10): # the ten refusals above would have used it up if they counted
assert post(client, "/app/profilo/segnalazioni/", {"text": f"problem number {number}"}).status_code == 302
def test_reports_are_limited_per_user():
client = client_for(player())
for number in range(10):
post(client, "/app/profilo/segnalazioni/", {"text": f"problem number {number}"})
response = post(client, "/app/profilo/segnalazioni/", {"text": "one problem too many"})
assert response.status_code == 429 and "Retry-After" in response
assert Report.objects.count() == 10
assert post(client_for(player("luigi")), "/app/profilo/segnalazioni/", {"text": "another player is fine"}).status_code == 302
def test_sending_a_report_needs_a_session(client):
assert client.post("/app/profilo/segnalazioni/", {"text": "anonymous"}).status_code in (302, 403)
assert not Report.objects.exists()
# --- admin (WEB-32) ---------------------------------------------------------------------------
def admin_user():
return User.objects.create_superuser("boss", password=PASSWORD)
def test_changing_a_report_status_in_the_admin_is_audited():
boss = admin_user()
report = Report.objects.create(user=player(), text="please look")
client = client_for(boss)
response = client.post(f"/admin/lottery/report/{report.pk}/change/", {"status": "resolved"})
assert response.status_code == 302
report.refresh_from_db()
assert report.status == "resolved" and report.status_changed_at is not None
entry = AuditEntry.objects.get(action="report_status_changed")
assert (entry.actor, entry.payload) == (boss, {"from": "open", "to": "resolved"})
def test_the_text_of_a_report_cannot_be_edited_in_the_admin():
report = Report.objects.create(user=player(), text="original")
client_for(admin_user()).post(f"/admin/lottery/report/{report.pk}/change/", {"status": "read", "text": "tampered"})
report.refresh_from_db()
assert (report.text, report.status) == ("original", "read")
@pytest.mark.parametrize("model", ["round", "movement", "chaintransaction", "auditentry", "participation"])
def test_game_records_are_read_only_in_the_admin(model):
client = client_for(admin_user())
assert client.get(f"/admin/lottery/{model}/").status_code == 200
assert client.get(f"/admin/lottery/{model}/add/").status_code == 403
def test_a_user_page_shows_game_records_and_cannot_delete_the_user():
user = player()
client = client_for(admin_user())
html = client.get(f"/admin/accounts/user/{user.pk}/change/").content.decode()
assert "Movements (read-only)" in html
assert client.post(f"/admin/accounts/user/{user.pk}/delete/", {"post": "yes"}).status_code == 403
def test_deactivating_a_user_in_the_admin_is_audited():
user = player()
client = client_for(admin_user())
data = {"username": user.username, "date_joined_0": "2026-01-01", "date_joined_1": "00:00:00", "is_staff": "",
"password": user.password, # is_active left out: unchecked
"participations-TOTAL_FORMS": "0", "participations-INITIAL_FORMS": "0",
"movements-TOTAL_FORMS": "0", "movements-INITIAL_FORMS": "0"}
client.post(f"/admin/accounts/user/{user.pk}/change/", data)
user.refresh_from_db()
assert not user.is_active
assert AuditEntry.objects.get(action="user_changed").payload == {"is_active": False}