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:
1 parent
3d1e820564
commit
eab141f467
24 files changed
+928
-11
No files matched your search
@@ -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})
|
||||
@@ -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')],
|
||||
},
|
||||
),
|
||||
]
|
||||
@@ -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})"
|
||||
Reference in new issue
Block a user