"""What a visitor sees of the lottery right now (WEB-10): one of six states, the quota, the confirmed prize and the closing time. The same function feeds the page when it is rendered and the endpoint the page polls, so the two can never tell different stories (WEB-05).""" from datetime import datetime, timedelta, timezone as dt_timezone from typing import Any from django.db.models import Count, Sum from django.utils import timezone from .format import plm_text from .lifecycle import get_active_round from .models import LotteryConfig, Participation, Round from .rules import round_deadline, winner_share NONE, OPEN, CLOSING, DRAWING, PAYING, MAINTENANCE = "none", "open", "closing", "drawing", "paying", "maintenance" LABELS = { NONE: "Nessun round in corso", OPEN: "Puntate aperte", CLOSING: "In chiusura", DRAWING: "Estrazione in corso", PAYING: "Pagamento in attesa", MAINTENANCE: "Manutenzione", } def iso(moment: datetime) -> str: return moment.astimezone(dt_timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") def clock_text(moment: datetime) -> str: return moment.astimezone(dt_timezone.utc).strftime("%H:%M:%S") + " UTC" def countdown_text(total_seconds: float) -> str: """`mm:ss`, or `h:mm:ss` from one hour up — the same text `home.js` writes, so the page reads the same with and without JavaScript.""" seconds = max(0, int(total_seconds)) hours, minutes, secs = seconds // 3600, seconds % 3600 // 60, seconds % 60 return f"{hours}:{minutes:02d}:{secs:02d}" if hours else f"{minutes:02d}:{secs:02d}" def public_state(now: datetime | None = None) -> dict[str, Any]: now = now or timezone.now() config = LotteryConfig.get() round_ = get_active_round() data: dict[str, Any] = { "server_now": iso(now), "round_id": None, "closes_at": None, "closes_at_text": "", "seconds_left": None, "countdown_text": "", "bet_amount_sats": config.bet_amount_sats, "bet_amount_text": plm_text(config.bet_amount_sats), "jackpot_sats": 0, "jackpot_text": plm_text(0), "confirmed_players": 0, "pending_players": 0, "paused_after_round": config.pause_after_round, "next_round_at": None, "next_round_at_text": "", } if round_ is None: return _without_round(data, config, now) totals = Participation.objects.filter(round=round_, status=Participation.Status.CONFIRMED).aggregate( players=Count("id"), pool=Sum("bet_amount_sats")) confirmed_pool = totals["pool"] or 0 deadline = round_deadline(round_) data.update( round_id=round_.pk, bet_amount_sats=round_.bet_amount_sats, bet_amount_text=plm_text(round_.bet_amount_sats), # the round's own quota confirmed_players=totals["players"] or 0, pending_players=Participation.objects.filter(round=round_, status=Participation.Status.PENDING).count(), # "Confirmed prize": the winner's share of what is already confirmed — never more than will be paid (B-11, B-65). jackpot_sats=winner_share(confirmed_pool), jackpot_text=plm_text(winner_share(confirmed_pool)), ) if round_.status == Round.Status.OPEN and now < deadline: if config.new_bets_suspended: # ADR-57: «Sospendi nuove puntate» return _finish(data, MAINTENANCE, "Le nuove puntate sono sospese. Le puntate già inviate restano valide.") data.update(closes_at=iso(deadline), closes_at_text=clock_text(deadline), seconds_left=max(0, int((deadline - now).total_seconds())), countdown_text=countdown_text((deadline - now).total_seconds())) message = f"Quota {data['bet_amount_text']}. Il round chiude alle {data['closes_at_text']}." if config.pause_after_round: message += " Dopo questo round la lotteria si ferma per manutenzione." return _finish(data, OPEN, message) if round_.status in (Round.Status.OPEN, Round.Status.CLOSING): # past the deadline, even if the scheduler lags return _finish(data, CLOSING, "Le puntate sono chiuse: attendiamo la conferma di quelle già inviate.") if round_.status == Round.Status.DRAWING: return _finish(data, DRAWING, "Il vincitore sarà scelto con un blocco della catena che ancora non esisteva alla chiusura.") return _finish(data, PAYING, "Il vincitore è stato estratto: il pagamento è in attesa di conferma.") def _without_round(data: dict[str, Any], config: LotteryConfig, now: datetime) -> dict[str, Any]: if config.pause_after_round: return _finish(data, MAINTENANCE, "La lotteria è ferma per manutenzione. Il prossimo round non è ancora fissato.") last = Round.objects.filter(status=Round.Status.CLOSED).order_by("-id").first() if last is not None and last.closed_at is not None: opens = last.closed_at + timedelta(seconds=last.cooldown_seconds) if opens > now: data.update(next_round_at=iso(opens), next_round_at_text=clock_text(opens)) return _finish(data, NONE, f"Il prossimo round apre alle {data['next_round_at_text']}.") return _finish(data, NONE, "Il prossimo round sta per aprirsi.") def _finish(data: dict[str, Any], state: str, message: str) -> dict[str, Any]: data.update(state=state, label=LABELS[state], message=message, can_participate=state == OPEN) return data