"""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, }