Merge main into PR #291 and resolve scoreboard phase conflicts
This commit is contained in:
7
.claude/settings.json
Normal file
7
.claude/settings.json
Normal file
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,10 @@
|
||||
# Changelog
|
||||
|
||||
## [Unreleased]
|
||||
### Docs
|
||||
- Added `docs/ISSUE-279-I18N-MVP-CLOSEOUT.md` with the issue #279 i18n MVP close-out note, including migration impact, reusable release-note text, and a release-readiness checklist refreshed against `main@1bc4c27` after PR #282/#283 landed on 2026-03-13 UTC.
|
||||
- Clarified that the close-out note supersedes earlier PR snapshot assumptions and now treats PR #282 (`6ad5430`) and PR #283 (`1bc4c27`) as already merged on `main`.
|
||||
|
||||
## [0.1.0] - 2026-02-27
|
||||
### Added
|
||||
- Projekt scaffold for Weirsøe Party Protocol (Django 6.0.2)
|
||||
|
||||
119
CLAUDE.md
Normal file
119
CLAUDE.md
Normal file
@@ -0,0 +1,119 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
## Project Overview
|
||||
|
||||
**Weirsøe Party Protocol** is a Danish party game web platform (Jackbox-style) where games display on a primary screen and players participate via mobile. The MVP game is "Fup og Fakta" (a Fibbage-style lie-and-guess game).
|
||||
|
||||
- Backend: Django 6.0.2 + Django Channels (WebSockets) + Redis
|
||||
- Frontend: Angular 19 shell + shared TypeScript API client library
|
||||
- Database: MySQL (SQLite fallback for dev)
|
||||
- Deployment: Proxmox LXC containers (not Docker)
|
||||
|
||||
## Commands
|
||||
|
||||
### Backend (Django)
|
||||
```bash
|
||||
python manage.py runserver # Dev server
|
||||
python manage.py migrate # Apply migrations
|
||||
python manage.py test # Run all backend tests
|
||||
python manage.py test lobby # Run tests for a single app
|
||||
python manage.py shell # Django shell
|
||||
```
|
||||
|
||||
### Frontend — API client (`/frontend`)
|
||||
```bash
|
||||
cd frontend
|
||||
npm install
|
||||
npm test # Vitest unit tests
|
||||
npm run build # TypeScript compile check (--noEmit)
|
||||
```
|
||||
|
||||
### Frontend — Angular shell (`/frontend/angular`)
|
||||
```bash
|
||||
cd frontend/angular
|
||||
npm install
|
||||
npm start # Dev server (ng serve)
|
||||
npm run build # Production build
|
||||
npm run test # Vitest unit tests
|
||||
```
|
||||
|
||||
### i18n validation
|
||||
```bash
|
||||
python scripts/check_i18n_drift.py # Check for key drift between locales
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
### Backend apps
|
||||
|
||||
| App | Purpose |
|
||||
|-----|---------|
|
||||
| `partyhub/` | Main Django project — settings, root URLs, ASGI/WSGI, i18n bootstrap |
|
||||
| `lobby/` | Session & player management — create/join session, locale-aware error responses |
|
||||
| `fupogfakta/` | Game logic — all domain models, score calculation (server-authoritative) |
|
||||
| `realtime/` | WebSocket event layer (stub) |
|
||||
| `voice/` | Voice/TTS interface (stub, Phase 2) |
|
||||
| `core_admin/` | Health endpoint (`/healthz`), global admin |
|
||||
|
||||
**Key domain models** (all in `fupogfakta/models.py`): `GameSession`, `Player`, `Category`, `Question`, `RoundConfig`, `RoundQuestion`, `LieAnswer`, `Guess`, `ScoreEvent`.
|
||||
|
||||
Score calculation is server-side only. `ScoreEvent` provides an auditable trail of all point changes.
|
||||
|
||||
### Frontend layers
|
||||
|
||||
1. **Shared API client** (`frontend/src/`) — pure TypeScript, framework-agnostic. Defines all API types (`api/types.ts`) and HTTP client abstraction (`api/client.ts`).
|
||||
2. **Angular shell** (`frontend/angular/`) — Angular 19 standalone components (no NgModules), hash-based routing. `host-shell.component` for the presenter screen; `player-shell.component` for mobile players.
|
||||
|
||||
The Angular shell consumes the shared client via `frontend/src/api/angular-client.ts`.
|
||||
|
||||
### Real-time flow
|
||||
|
||||
`LOBBY → LIE → GUESS → REVEAL → FINISHED` — phase transitions broadcast a `PhaseViewModel` to all connected clients via WebSocket. Clients are read-only; only the server is authoritative for state.
|
||||
|
||||
### i18n
|
||||
|
||||
- **Single source of truth**: `shared/i18n/lobby.json` (keys in both `en` and `da`)
|
||||
- Loaded once at startup with LRU cache (`partyhub/i18n_bootstrap.py`)
|
||||
- Key naming: domain-first — `frontend.ui.host.*`, `frontend.ui.player.*`, `backend.errors.*`, `backend.error_codes.*`
|
||||
- Locale resolved from `Accept-Language` header; missing key returns key + logs warning; missing translation falls back to `en`
|
||||
|
||||
## Key Conventions
|
||||
|
||||
### Errors
|
||||
Backend error responses use stable machine-readable codes (`backend.error_codes.*`) with separately localized messages. Never couple error code strings to locale.
|
||||
|
||||
### Game constraints (MVP)
|
||||
- 3–12 players per session
|
||||
- Session codes: 6-char alphanumeric (no 0/O/1/I/L)
|
||||
- Anti-cheat: no duplicate lies, lies cannot match the correct answer, answer order randomized
|
||||
|
||||
### Git workflow
|
||||
- `main`: stable baseline
|
||||
- `feature/<name>`: development branches
|
||||
- `release/vX.Y.Z`: release preparation
|
||||
- Release: merge → create release branch → update `VERSION` + `CHANGELOG.md` → tag → push
|
||||
|
||||
### TypeScript
|
||||
Strict mode required. Target ES2022. API response interfaces in `frontend/src/api/types.ts` must match backend responses exactly.
|
||||
|
||||
### Database
|
||||
Use `ForeignKey` with explicit `on_delete` (`PROTECT`/`CASCADE`/`SET_NULL`). Add `db_index=True` on frequently queried fields. Migrations are auto-generated by Django and versioned in `migrations/`.
|
||||
|
||||
## Environment Variables
|
||||
|
||||
```
|
||||
DJANGO_SECRET_KEY, DJANGO_DEBUG, DJANGO_ALLOWED_HOSTS
|
||||
DB_ENGINE, DB_NAME, DB_USER, DB_PASSWORD, DB_HOST, DB_PORT
|
||||
CHANNEL_REDIS_HOST, CHANNEL_REDIS_PORT
|
||||
USE_SPA_UI (fallback: WPP_SPA_ENABLED)
|
||||
WPP_SPA_ASSET_BASE, WPP_SPA_ASSET_VERSION
|
||||
```
|
||||
|
||||
## Test Files of Note
|
||||
|
||||
- `lobby/tests.py` — comprehensive Django TestCase coverage for session/player/i18n/error flows
|
||||
- `frontend/angular/src/app/api-contract-smoke.spec.ts` — API contract smoke tests
|
||||
- `frontend/angular/src/app/lobby-i18n.spec.ts` — i18n parity checks
|
||||
- `frontend/tests/lobby-loader.parity.test.ts` — shared i18n loader parity
|
||||
71
PROMPT.md
Normal file
71
PROMPT.md
Normal file
@@ -0,0 +1,71 @@
|
||||
# Ralph Loop: Implement WebSocket push for Weirsøe Party Protocol
|
||||
|
||||
## Context
|
||||
- Project: /home/agw/projects/weirsoe-party-protocol
|
||||
- Backend: Django 6.0.2 + Django Channels + Redis
|
||||
- The full game REST flow is already implemented in lobby/views.py
|
||||
(create_session, join_session, start_round, show_question, submit_lie,
|
||||
mix_answers, submit_guess, calculate_scores, reveal_scoreboard, finish_game)
|
||||
- realtime/ app exists but is a stub (no consumers.py, no routing)
|
||||
- partyhub/settings.py has channels in INSTALLED_APPS but no CHANNEL_LAYERS or routing
|
||||
- PO hard requirement: WebSocket push is mandatory in MVP (no polling)
|
||||
|
||||
## What to build
|
||||
|
||||
### 1. realtime/consumers.py — GameConsumer
|
||||
- AsyncJsonWebsocketConsumer
|
||||
- Connects to group game_{session_code} on connect (session_code from URL)
|
||||
- Player auth: session_token query param validated against Player model
|
||||
- Host auth: query param role=host, no token required for MVP
|
||||
- On disconnect: clean leave from group
|
||||
- Handles incoming message type "ping" -> replies with {"type": "pong"}
|
||||
- Forwards broadcast group events to WebSocket client
|
||||
|
||||
### 2. partyhub/settings.py — CHANNEL_LAYERS
|
||||
Add CHANNEL_LAYERS using channels_redis.core.RedisChannelLayer.
|
||||
Read CHANNEL_REDIS_HOST (default 127.0.0.1) and CHANNEL_REDIS_PORT (default 6379) from env.
|
||||
|
||||
### 3. partyhub/asgi.py — ASGI routing
|
||||
Wire URLRouter so ws/game/<session_code>/ routes to GameConsumer.
|
||||
Keep existing HTTP routing intact.
|
||||
|
||||
### 4. realtime/routing.py
|
||||
Define websocket_urlpatterns list.
|
||||
|
||||
### 5. realtime/broadcast.py — broadcast helper
|
||||
- async def broadcast_phase_event(session_code, event_type, payload)
|
||||
Sends to group game_{session_code} via channel layer.
|
||||
- def sync_broadcast_phase_event(session_code, event_type, payload)
|
||||
Sync wrapper using async_to_sync for calling from sync REST views.
|
||||
|
||||
### 6. lobby/views.py — hook broadcasts into phase transitions
|
||||
After each phase transition, call sync_broadcast_phase_event:
|
||||
- start_round -> phase.lie_started (question prompt + time limit)
|
||||
- show_question -> phase.question_shown (question text)
|
||||
- mix_answers -> phase.guess_started (shuffled answers + time limit)
|
||||
- calculate_scores -> phase.scores_calculated (per-player score delta)
|
||||
- reveal_scoreboard -> phase.scoreboard (ranked player list)
|
||||
- finish_game -> phase.game_over (final rankings)
|
||||
|
||||
### 7. realtime/tests.py — basic tests
|
||||
- Connect/disconnect test using channels.testing.WebsocketCommunicator
|
||||
- Verify a broadcast reaches a connected client
|
||||
|
||||
## Constraints
|
||||
- Keep auth simple: session_token query param for players, unauthenticated host in MVP
|
||||
- Use async_to_sync wrapper for sync REST views calling async broadcast
|
||||
- Do not break existing REST tests (python manage.py test lobby must still pass)
|
||||
- After each file written, run: python manage.py check
|
||||
- Follow existing code style in lobby/views.py
|
||||
|
||||
## Completion criteria
|
||||
Output the exact text: WEBSOCKET COMPLETE
|
||||
|
||||
...when ALL of the following are true:
|
||||
- realtime/consumers.py exists and handles connect/disconnect/ping
|
||||
- realtime/broadcast.py exists with sync_broadcast_phase_event
|
||||
- partyhub/settings.py has CHANNEL_LAYERS configured
|
||||
- partyhub/asgi.py routes ws/game/<code>/ to GameConsumer
|
||||
- All 6 phase transitions in lobby/views.py call sync_broadcast_phase_event
|
||||
- python manage.py check passes with no errors
|
||||
- python manage.py test lobby passes (existing tests not broken)
|
||||
25
TODO.md
25
TODO.md
@@ -37,8 +37,8 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
||||
- [x] `core_admin` (global administration)
|
||||
- [x] `fupogfakta` (Spil 1)
|
||||
- [x] `lobby` (room/session/player join flow)
|
||||
- [x] `realtime` (channels events, game state broadcast)
|
||||
- [x] `voice` (fælles voice-acting interface)
|
||||
- [x] `realtime` (app-skelet oprettet — consumers/routing IKKE implementeret endnu)
|
||||
- [x] `voice` (fælles voice-acting interface — stub)
|
||||
- [x] Miljøfiler (`.env.test`, `.env.prod` skabeloner)
|
||||
- [x] Konfig for MySQL test/prod
|
||||
|
||||
@@ -53,14 +53,15 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
||||
- [x] `ScoreEvent` (auditérbar pointslog)
|
||||
|
||||
### Fase 3 — Spilflow `Fup og Fakta`
|
||||
- [x] Lobby: host opretter session, spillere joiner via kode
|
||||
- [x] Runde starter med kategori
|
||||
- [x] Spørgsmål vises -> alle skriver løgn inden X sek
|
||||
- [x] System blander korrekt svar + løgne
|
||||
- [x] Guessfase: alle gætter inden Z sek
|
||||
- [x] Pointudregning (konfigurerbar pr. runde)
|
||||
- [x] Scoreboard + næste spørgsmål/runde
|
||||
- [x] Slutresultat
|
||||
- [x] Lobby: host opretter session, spillere joiner via kode (REST)
|
||||
- [x] Runde starter med kategori (REST)
|
||||
- [x] Spørgsmål vises -> alle skriver løgn inden X sek (REST)
|
||||
- [x] System blander korrekt svar + løgne (persisted i JSONField, anti-cheat dedup)
|
||||
- [x] Guessfase: alle gætter inden Z sek (REST)
|
||||
- [x] Pointudregning (konfigurerbar pr. runde, ScoreEvent audit trail)
|
||||
- [x] Scoreboard + næste spørgsmål/runde (REST)
|
||||
- [x] Slutresultat (REST)
|
||||
- [x] **WebSocket push af phase-events til host + spillere** (GameConsumer + broadcast.py, InMemoryChannelLayer i tests)
|
||||
|
||||
### Fase 4 — Voice-acting (platformkrav)
|
||||
- [ ] Definér TTS provider-interface
|
||||
@@ -103,10 +104,10 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
||||
- [ ] Migrations + static + health checks
|
||||
|
||||
### Backlog — Need-to-have / Nice-to-have
|
||||
- [ ] (Need-to-have) Persistér mixed svarrækkefølge pr. round question, så alle spillere ser samme rækkefølge ved reconnect/refresh
|
||||
- [x] (Need-to-have) Persistér mixed svarrækkefølge pr. round question — DONE (JSONField + migration 0003 + test)
|
||||
- [x] (Need-to-have) Tilføj spiller-auth/session-token for submit_lie (pt. baseret på player_id i payload)
|
||||
- [ ] (Nice-to-have) Endpoint til status/progress i løgnfasen (antal indsendt ud af total)
|
||||
- [ ] (Need-to-have) [Fejltype: CI/lint F401] [Fil/område: core_admin/*, fupogfakta/tests.py+views.py, lobby/admin.py+models.py, realtime/*, voice/*] [Branch/PR: feature/f3-lobby-create-join, feature/fase0-mvp-fup-og-fakta, feature/lobby-mvp (ingen åbne PRs fundet)] Fjern ubrugte scaffold-imports (eller kør ruff check --fix) så quality gate kan blive grøn før merge.
|
||||
- [ ] (Need-to-have) Fjern ubrugte scaffold-imports i core_admin/*, realtime/*, voice/*, fupogfakta/views.py (kør `ruff check --fix`) så CI quality gate er grøn
|
||||
- [x] (Need-to-have) [Issue #251] Release-often lane: SPA MVP opdelt i 3 merge-klare micro-PR batches (plan + acceptance criteria dokumenteret i `docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md`).
|
||||
- [ ] (Need-to-have) Rate limiting på join/submit endpoints
|
||||
- [ ] (Need-to-have) Session-kode brute-force beskyttelse
|
||||
|
||||
27
docs/ISSUE-252-REACT-FALLBACK-TRIGGERS-ARTIFACT.md
Normal file
27
docs/ISSUE-252-REACT-FALLBACK-TRIGGERS-ARTIFACT.md
Normal file
@@ -0,0 +1,27 @@
|
||||
# ISSUE-252 Artifact — React fallback trigger criteria (delivery-blocking only)
|
||||
|
||||
Issue: **#252**
|
||||
|
||||
## Leveret ændring
|
||||
Dokumentationen i `docs/spa-cutover-flag.md` er opdateret med en dedikeret sektion:
|
||||
- **React fallback trigger-kriterier (kun delivery-blocking)**
|
||||
- klare **tilladelses-kriterier** (alle skal være opfyldt)
|
||||
- tydelige **scope-limits**
|
||||
- eksplicitte **ikke-tilladte** anvendelser
|
||||
|
||||
## Acceptance mapping
|
||||
1. **Clear trigger criteria**
|
||||
- Definerer præcist hvornår fallback er tilladt:
|
||||
- aktiv delivery-blocking fejl i Angular SPA
|
||||
- ingen sikker Angular-fix inden release-vinduet
|
||||
- rollback alene er utilstrækkelig for leveringsbehovet
|
||||
- beslutning + evidens logges eksplicit (inkl. issue/incident-reference)
|
||||
2. **Scope limits**
|
||||
- Begrænset til delivery-blocking host/player-paths.
|
||||
- Ingen feature-bundling eller ikke-kritiske ændringer.
|
||||
- Midlertidig anvendelse kun i aktiv incident/release-vindue.
|
||||
3. **When fallback is allowed**
|
||||
- Kun når alle trigger-kriterier er opfyldt og dokumenteret.
|
||||
|
||||
## Resultat
|
||||
Issue #252 er dokumenteret med operationelle guardrails, så React fallback kun bruges i kontrollerede, leveringsblokerende situationer.
|
||||
36
docs/ISSUE-278-SMOKE-E2E-GATE-ARTIFACT.md
Normal file
36
docs/ISSUE-278-SMOKE-E2E-GATE-ARTIFACT.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Issue #278 Artifact — smoke/e2e gate for da+en locale flow and primary-only audio
|
||||
|
||||
## Scope
|
||||
Acceptance for `[READY][#175][P4]`:
|
||||
1. Verify one MVP host+player smoke run in `en`.
|
||||
2. Verify one MVP host+player smoke run in `da`.
|
||||
3. Verify audio routing remains `primary-device only` so phone/player clients never take playback ownership.
|
||||
|
||||
Dette er en gate-/evidensleverance. Ingen ny produktfunktion ud over test/verifikation.
|
||||
|
||||
## Implemented smoke gate
|
||||
Angular smoke spec: `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts`
|
||||
|
||||
The gate now runs two explicit locale scenarios:
|
||||
- `en`: host refresh/start-round copy + player submit-guess copy
|
||||
- `da`: samme flow med dansk copy
|
||||
|
||||
Audio-policy delen af samme smoke-spec verificerer:
|
||||
- host/primary playback path er uændret før player mount
|
||||
- player mount installerer no-audio guard på secondary device
|
||||
- guard fjernes igen ved unmount, så primary path fortsat er eneste aktive output
|
||||
|
||||
## Recommended verification command
|
||||
Køres fra `frontend/angular`:
|
||||
|
||||
```bash
|
||||
npm test -- --run src/app/i18n-mvp-flow-smoke.spec.ts src/app/lobby-i18n.spec.ts src/app/features/player/player-shell.component.spec.ts
|
||||
```
|
||||
|
||||
## Why this is the gate
|
||||
- `i18n-mvp-flow-smoke.spec.ts` giver en lille, samlet smoke/e2e-lignende verifikation af host+player i begge locale-kontekster.
|
||||
- `lobby-i18n.spec.ts` holder shared locale propagation + contract fallback grøn.
|
||||
- `player-shell.component.spec.ts` dækker den dybere regressionflade for audio-guard på secondary device.
|
||||
|
||||
## Conclusion
|
||||
Gate’en verificerer nu eksplicit begge locale-runs (`da` + `en`) og bekræfter primary-only audio routing i MVP-flowet.
|
||||
168
docs/ISSUE-279-I18N-MVP-CLOSEOUT.md
Normal file
168
docs/ISSUE-279-I18N-MVP-CLOSEOUT.md
Normal file
@@ -0,0 +1,168 @@
|
||||
# ISSUE-279 — i18n MVP close-out note
|
||||
|
||||
Issue: **#279** (`[READY][#175][P5] MVP close-out note: migration/changelog + release-readiness checklist for i18n`)
|
||||
|
||||
## Scope
|
||||
|
||||
Dette dokument lukker MVP-sporet for issue #175 med tre konkrete ting:
|
||||
|
||||
1. en migrationsnote for release/deploy,
|
||||
2. changelog-indhold der kan genbruges i næste release-note,
|
||||
3. en release-readiness checkliste for i18n, forankret i et verificeret snapshot af `main` ved reviewtidspunktet.
|
||||
|
||||
Repo-state ved review-opdatering:
|
||||
- `main` peger nu på merge commit `1bc4c27` (PR #283), og inkluderer også PR #282 via merge commit `6ad5430`.
|
||||
- Denne note er opdateret mod repo-tilstanden verificeret 2026-03-13 UTC, ikke en løbende garanti for senere `main`-ændringer.
|
||||
- Denne revision afløser de tidligere snapshot-antagelser fra PR-historikken, hvor #282/#283 endnu ikke var landet.
|
||||
- Der er ingen åbne release-afklaringer tilbage for PR #282/#283; begge er allerede landet på `main`.
|
||||
|
||||
## Current i18n MVP state on `main`
|
||||
|
||||
Følgende er allerede til stede på `main`:
|
||||
|
||||
- **Shared contract** i `shared/i18n/lobby.json`
|
||||
- default locale: `en`
|
||||
- supported locales: `en`, `da`
|
||||
- fælles frontend/backend keyspace + fallback-regler
|
||||
- **Django bootstrap** via `partyhub/i18n_bootstrap.py` og `partyhub/settings.py`
|
||||
- `LocaleMiddleware` aktiv
|
||||
- `LANGUAGE_CODE` + `LANGUAGES` bootstrappes fra shared catalog
|
||||
- **Backend locale/error flow** via `lobby/i18n.py`
|
||||
- normalisering af locale-tags
|
||||
- locale-aware fejlpayload med `error_code`, `error`, `locale`
|
||||
- fallback til `en` når locale eller oversættelse mangler
|
||||
- **Angular MVP wiring** via
|
||||
- `frontend/shared/i18n/lobby-loader.ts`
|
||||
- `frontend/angular/src/app/lobby-i18n.ts`
|
||||
- host/player shells med locale switch og shared copy-opslag
|
||||
- **Drift/parity guardrails**
|
||||
- `shared/i18n/key-manifest.json`
|
||||
- `scripts/check_i18n_drift.py`
|
||||
- frontend parity/contract tests
|
||||
- **Existing documentation/artifacts**
|
||||
- `docs/I18N_ARCHITECTURE.md`
|
||||
- `docs/ISSUE-175-I18N-SHARED-CONTRACT-ARTIFACT.md`
|
||||
- `docs/ISSUE-225-BACKEND-I18N-BASELINE-ARTIFACT.md`
|
||||
- `docs/ISSUE-257-SHARED-I18N-KEYSPACE-FRONTEND-LOADER-ARTIFACT.md`
|
||||
- `docs/ISSUE-207-I18N-AUDIO-SMOKE-ARTIFACT.md`
|
||||
- `docs/i18n-drift-check.md`
|
||||
|
||||
## Migration note for release
|
||||
|
||||
### Schema impact
|
||||
|
||||
**Der er ingen nye Django-migrations i selve i18n-MVP-sporet på `main`.**
|
||||
|
||||
Den i18n-relaterede leverance ligger i shared catalog, locale-bootstrap, error-payload-kontrakt, Angular wiring og test/documentation. Den kræver derfor ikke en særskilt i18n-database-migration for at gå i release.
|
||||
|
||||
### Release/deploy expectation
|
||||
|
||||
Selv om issue #279 ikke introducerer schemaændringer, skal release-flow stadig følge repoets generelle migreringsgate:
|
||||
|
||||
```bash
|
||||
python manage.py makemigrations --check --dry-run
|
||||
python manage.py migrate --check --noinput
|
||||
```
|
||||
|
||||
Hvorfor: release-policyen kræver, at vi undgår code/schema drift, og staging-smoke-suiten forventer eksplicit migration consistency check.
|
||||
|
||||
### Praktisk migrationskonklusion
|
||||
|
||||
Til release-notes/deploy-runbook kan i18n-sporet beskrives sådan her:
|
||||
|
||||
- **Migration impact:** none for i18n MVP itself
|
||||
- **Deploy requirement:** run standard Django migration consistency checks anyway
|
||||
- **Rollback note:** rollback er primært kode-/asset-baseret (shared catalog, frontend bundles, backend locale resolver), ikke schema-baseret
|
||||
|
||||
## Suggested changelog content
|
||||
|
||||
Følgende tekst kan bruges direkte i næste unreleased/release-sektion:
|
||||
|
||||
```markdown
|
||||
### i18n
|
||||
- Shared da/en lobby i18n contract is now wired across Django and Angular MVP flows via `shared/i18n/lobby.json`.
|
||||
- Backend error payloads expose stable locale-aware fields (`error_code`, `error`, `locale`) with fallback to English for unsupported locales.
|
||||
- Angular host/player shells now consume shared i18n copy, persist preferred locale, and keep audio-policy messaging aligned with the shared catalog.
|
||||
- Added repo guardrails for i18n drift/parity through the shared key manifest, drift checker, and focused frontend/backend contract tests.
|
||||
- Release migration impact for the i18n MVP is **none** beyond the standard Django migration consistency checks.
|
||||
```
|
||||
|
||||
Kort version til annoterede release-notes:
|
||||
|
||||
```markdown
|
||||
## i18n MVP close-out
|
||||
- Shared da/en contract is active across backend + Angular MVP shell.
|
||||
- Locale fallback remains `en` for unsupported requests and missing translations.
|
||||
- No i18n-specific schema migration is required; keep standard `migrate --check --noinput` in release verification.
|
||||
```
|
||||
|
||||
## Release-readiness checklist for i18n
|
||||
|
||||
Status er vurderet mod verificeret snapshot `main@1bc4c27` (reviewet 2026-03-13 UTC, inkl. PR #282/#283).
|
||||
|
||||
### 1) Shared contract and locale behavior
|
||||
|
||||
- [x] Shared catalog findes i `shared/i18n/lobby.json`.
|
||||
- [x] Default/supported locales er dokumenteret og implementeret som `en` + `da`.
|
||||
- [x] Backend bruger shared contract til locale-aware fejlbeskeder.
|
||||
- [x] Frontend/Angular bruger shared loader + shared keyspace.
|
||||
- [x] Fallback-regel til `en` er dokumenteret og testet.
|
||||
|
||||
### 2) Verification artifacts and local checks
|
||||
|
||||
- [x] Arkitektur-note findes: `docs/I18N_ARCHITECTURE.md`.
|
||||
- [x] Baseline artifact for issue #175 findes.
|
||||
- [x] Backend artifact for issue #225 findes.
|
||||
- [x] Frontend/shared loader artifact for issue #257 findes.
|
||||
- [x] Drift-check dokumentation findes i `docs/i18n-drift-check.md`.
|
||||
- [x] Parity artifact fra issue #277 er på `main` via PR #282 (merge commit `6ad5430`).
|
||||
|
||||
### 3) Code readiness on current branch topology
|
||||
|
||||
- [x] Angular MVP host/player i18n flow er på `main` (PR #281).
|
||||
- [x] Shared locale/bootstrap wiring er på `main`.
|
||||
- [x] Django i18n hardening fra issue #275 er på `main` via PR #283 (merge commit `1bc4c27`).
|
||||
- [x] PR #283 er ikke længere en separat release-afklaring; hardeningen er allerede indarbejdet på `main`.
|
||||
|
||||
### 4) Release gate before shipping i18n as “done”
|
||||
|
||||
- [x] PR #282 er allerede merged, så parity-artifact-status er afklaret på `main`.
|
||||
- [x] PR #283 er allerede merged, så backend hardening-status er afklaret på `main`.
|
||||
- [ ] Kør drift-check fra repo root:
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
```
|
||||
- [ ] Kør backend i18n regressions:
|
||||
```bash
|
||||
. .venv/bin/activate && python manage.py test \
|
||||
partyhub.tests_i18n_bootstrap \
|
||||
lobby.tests.I18nResolverTests
|
||||
```
|
||||
- [ ] Kør frontend shared-contract/parity checks:
|
||||
```bash
|
||||
cd frontend && npm test -- --run \
|
||||
tests/lobby-loader.parity.test.ts \
|
||||
tests/lobby-i18n.contract.test.ts
|
||||
```
|
||||
- [ ] Kør Angular MVP locale smoke:
|
||||
```bash
|
||||
cd frontend/angular && npm test -- --run \
|
||||
src/app/lobby-i18n.spec.ts \
|
||||
src/app/i18n-mvp-flow-smoke.spec.ts \
|
||||
src/app/features/host/host-shell.component.spec.ts \
|
||||
src/app/features/player/player-shell.component.spec.ts
|
||||
```
|
||||
- [ ] Bekræft standard migration consistency gate:
|
||||
```bash
|
||||
. .venv/bin/activate && python manage.py makemigrations --check --dry-run
|
||||
. .venv/bin/activate && python manage.py migrate --check --noinput
|
||||
```
|
||||
- [ ] Følg `docs/RELEASE_POLICY.md`: staging deploy, `/healthz`, smoke-resultat og changelog-reference før tag.
|
||||
|
||||
## Close-out conclusion
|
||||
|
||||
**Konklusion:** i18n-MVP'en er implementeret på `main`, og issue #279 leverer den manglende release-/migration-closeout dokumentation uden nye kodeændringer i app-logikken.
|
||||
|
||||
PR #282 (parity artifact) og PR #283 (Django i18n hardening) er nu begge merged på `main`, så close-out-noten, changelog-teksten og release-readiness-checklisten kan behandles som indbyrdes konsistente for det verificerede snapshot.
|
||||
|
||||
Det betyder, at de resterende release-gates for i18n nu er de almindelige verificeringstrin (drift-check, backend/frontend-smoke, migrations-konsistens, staging deploy og changelog-reference) — ikke længere afklaring af om #282/#283 skal lande.
|
||||
272
docs/plans/2026-03-09-fupogfakta-game-engine-design.md
Normal file
272
docs/plans/2026-03-09-fupogfakta-game-engine-design.md
Normal file
@@ -0,0 +1,272 @@
|
||||
# Design: Fup og Fakta — Game Engine & Platform Architecture
|
||||
|
||||
**Date:** 2026-03-09
|
||||
**Status:** Approved
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
Build a working Fup og Fakta game (Fibbage-style) on top of a **pluggable game platform**. The platform handles sessions, players, WebSocket push, and Celery-driven timers. Each game is a self-contained **cartridge** that implements a shared driver interface and owns its own models, config, and phase logic.
|
||||
|
||||
---
|
||||
|
||||
## Platform Architecture
|
||||
|
||||
```
|
||||
partyhub/ Django project — settings, Celery app, ASGI
|
||||
lobby/ Platform layer — sessions, players, GameRun, timer dispatch
|
||||
realtime/ WebSocket consumers (already built)
|
||||
fupogfakta/ Game cartridge #1
|
||||
future_game/ Game cartridge #N (same interface)
|
||||
```
|
||||
|
||||
### Platform provides (`lobby/`)
|
||||
|
||||
#### Models
|
||||
|
||||
**`GameSession`** (exists, minor additions)
|
||||
- `game_type` (CharField) — e.g. `"fupogfakta"`
|
||||
- `host` (FK → User)
|
||||
- `code` (6-char session code)
|
||||
- `status` (LOBBY / ACTIVE / FINISHED)
|
||||
- `config_id` / `config_snapshot` — see Config section
|
||||
|
||||
**`GameRun`** (new — ephemeral, deleted on game exit)
|
||||
- `session` (OneToOne → GameSession)
|
||||
- `current_state` (CharField — game-defined state string)
|
||||
- `phase_deadline` (DateTimeField, nullable)
|
||||
- `is_paused` (BooleanField, default False)
|
||||
- `paused_remaining_seconds` (FloatField, nullable)
|
||||
- `celery_task_id` (CharField, nullable)
|
||||
- `state_data` (JSONField) — game-specific snapshot for current phase
|
||||
|
||||
**`Player`** (exists)
|
||||
- `session`, `nickname`, `score`, `session_token`, `is_connected`
|
||||
|
||||
#### GameDriver interface
|
||||
|
||||
Each cartridge implements:
|
||||
|
||||
```python
|
||||
class GameDriver:
|
||||
game_type: str # e.g. "fupogfakta"
|
||||
|
||||
def on_game_start(session, run, config) -> PhaseResult
|
||||
def on_timer_expired(session, run, config) -> PhaseResult
|
||||
def on_pause(session, run) -> None
|
||||
def on_resume(session, run) -> None
|
||||
def on_exit(session, run) -> None # must clean up all game data
|
||||
def get_ws_payload(state, state_data) -> dict
|
||||
```
|
||||
|
||||
`PhaseResult` = `(next_state: str, duration_seconds: int | None, broadcast_payload: dict)`
|
||||
|
||||
#### Celery task
|
||||
|
||||
```python
|
||||
@app.task
|
||||
def handle_timer_expired(run_id: int, expected_state: str):
|
||||
# If run no longer exists or state has changed → stale task, ignore
|
||||
# Call driver.on_timer_expired(session, run, config)
|
||||
# Apply PhaseResult: update run, broadcast via channel layer, schedule next task
|
||||
```
|
||||
|
||||
`expected_state` prevents stale tasks from firing after pause/resume or manual state changes.
|
||||
|
||||
#### REST endpoints (platform-level)
|
||||
|
||||
- `POST /sessions/{code}/play` — start or resume
|
||||
- `POST /sessions/{code}/pause` — pause current phase timer
|
||||
- `POST /sessions/{code}/exit` — end game, delete GameRun + all game data
|
||||
|
||||
---
|
||||
|
||||
## Configuration System
|
||||
|
||||
### Base config model (`partyhub/`)
|
||||
|
||||
```python
|
||||
class BaseGameConfig(models.Model):
|
||||
class Meta:
|
||||
abstract = True
|
||||
|
||||
name = models.CharField(max_length=100) # "Quick game", "Full evening"
|
||||
user = models.ForeignKey(User, null=True, ...) # null = system default
|
||||
is_default = models.BooleanField(default=False)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
```
|
||||
|
||||
### Game-specific config (`fupogfakta/`)
|
||||
|
||||
```python
|
||||
class FupOgFaktaConfig(BaseGameConfig):
|
||||
num_rounds = PositiveIntegerField(default=3)
|
||||
questions_per_round = PositiveIntegerField(default=3)
|
||||
min_players = PositiveIntegerField(default=2)
|
||||
max_players = PositiveIntegerField(default=8)
|
||||
lie_seconds = PositiveIntegerField(default=45)
|
||||
guess_seconds = PositiveIntegerField(default=30)
|
||||
reveal_seconds_per_lie = PositiveIntegerField(default=8)
|
||||
scoreboard_recap_seconds = PositiveIntegerField(default=10)
|
||||
# Escalating scoring per round (stored as arrays or separate fields)
|
||||
points_correct = JSONField(default=[1500, 3000, 4500])
|
||||
points_bluff = JSONField(default=[500, 1000, 1500])
|
||||
# Reaction bonus (static, feeds post-game awards only)
|
||||
reaction_bonus = IntegerField(default=5)
|
||||
```
|
||||
|
||||
### Default resolution at session start
|
||||
|
||||
1. User has `is_default=True` row for this game type → use that
|
||||
2. System default (`user=null, is_default=True`) — set in Django admin
|
||||
3. Model field `default=` values (hardcoded)
|
||||
|
||||
User can have **multiple named presets** (one-to-many). When starting a session they choose which to use (or it auto-selects their default). The chosen config's values are **snapshotted into `GameRun.state_data`** at game start — immutable for the life of the session.
|
||||
|
||||
---
|
||||
|
||||
## Fup og Fakta — Game States
|
||||
|
||||
```
|
||||
LOBBY
|
||||
│ (host presses Play)
|
||||
▼
|
||||
LIE_PHASE timer: lie_seconds
|
||||
│ (all submitted OR timer expires)
|
||||
▼
|
||||
GUESS_PHASE timer: guess_seconds
|
||||
│ (timer expires — no mercy)
|
||||
▼
|
||||
REVEAL_LIE_{n} timer: reveal_seconds_per_lie (one per lie with ≥1 guess)
|
||||
│ → score liar incrementally as each is shown
|
||||
▼
|
||||
REVEAL_TRUTH timer: reveal_seconds_per_lie
|
||||
│ → score correct guessers
|
||||
▼
|
||||
SCOREBOARD_RECAP timer: scoreboard_recap_seconds
|
||||
│
|
||||
├─ more questions in round → back to LIE_PHASE (next question)
|
||||
├─ round done, more rounds → back to LIE_PHASE (next round, next category)
|
||||
└─ all rounds done → POST_GAME_AWARDS
|
||||
timer: configurable
|
||||
→ FINISHED (GameRun deleted, GameSession status = FINISHED)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Fup og Fakta — Phase Details
|
||||
|
||||
### LIE_PHASE
|
||||
- Question shown to all clients via WebSocket (`phase.lie_started` event)
|
||||
- Players submit lie via `POST /fupogfakta/{code}/lie`
|
||||
- **If lie matches correct answer (case-insensitive):** return `error_code: lie_matches_correct_answer` — player prompted again, does not consume their submission
|
||||
- Anonymous to other players during this phase
|
||||
- `state_data` tracks: question id, round number, how many have submitted (for progress display on host screen)
|
||||
- Timer expires → transition to GUESS_PHASE regardless of how many submitted
|
||||
|
||||
### GUESS_PHASE
|
||||
- Answers mixed (lies + truth, deduped) broadcast to all clients (`phase.guess_started`)
|
||||
- Players guess via `POST /fupogfakta/{code}/guess`
|
||||
- **After selecting:** player can react to other lies with 👍 😂 ❤️ etc. until timer expires. Cannot change guess.
|
||||
- Reactions stored in `LieReaction` model (player, lie, reaction_type)
|
||||
- Timer expires → transition to first REVEAL_LIE (or REVEAL_TRUTH if no lies had guesses)
|
||||
|
||||
### REVEAL_LIE_{n}
|
||||
- One Celery task per lie to reveal (only lies with ≥1 guesser)
|
||||
- Broadcast: which lie, who wrote it, who guessed it (`phase.reveal_lie`)
|
||||
- Score awarded to liar: `points_bluff[round_index] × guesser_count`
|
||||
- Score broadcast immediately (`phase.score_delta`)
|
||||
- Skipped lies (0 guesses): not shown at all
|
||||
|
||||
### REVEAL_TRUTH
|
||||
- Broadcast: correct answer, who guessed correctly (`phase.reveal_truth`)
|
||||
- Score awarded: `points_correct[round_index]` per correct guesser
|
||||
- Also show reaction totals on each lie during this phase
|
||||
|
||||
### SCOREBOARD_RECAP
|
||||
- Full leaderboard broadcast (`phase.scoreboard`)
|
||||
- Auto-advances to next question, next round, or post-game
|
||||
|
||||
### POST_GAME_AWARDS
|
||||
- Computed from `LieReaction` aggregate:
|
||||
- "Most Hilarious Liar" — most 😂 reactions total
|
||||
- "Most Beloved Lie" — most ❤️ reactions on a single lie
|
||||
- etc. (extensible)
|
||||
- Broadcast as `phase.awards`
|
||||
- Then FINISHED → GameRun deleted, all session game data wiped
|
||||
|
||||
---
|
||||
|
||||
## Fup og Fakta — Models
|
||||
|
||||
**Existing (keep):** `Category`, `Question`, `RoundQuestion`, `LieAnswer`, `Guess`
|
||||
|
||||
**Remove:** `ScoreEvent` (no audit trail needed — game state is ephemeral)
|
||||
|
||||
**New:**
|
||||
```python
|
||||
class LieReaction(models.Model):
|
||||
lie = ForeignKey(LieAnswer, on_delete=CASCADE)
|
||||
player = ForeignKey(Player, on_delete=CASCADE)
|
||||
reaction = CharField(max_length=20) # "laugh", "heart", "fire", etc.
|
||||
created_at = auto_now_add
|
||||
class Meta:
|
||||
unique_together = [("lie", "player", "reaction")]
|
||||
```
|
||||
|
||||
**Modify `RoundQuestion`:**
|
||||
- Add `reveal_order` (PositiveIntegerField, nullable) — set when GUESS_PHASE ends, determines reveal sequence
|
||||
|
||||
---
|
||||
|
||||
## Pause / Resume
|
||||
|
||||
- **Pause:** compute `remaining = phase_deadline - now`, store in `paused_remaining_seconds`, set `is_paused=True`, revoke Celery task by `celery_task_id`
|
||||
- **Resume:** set `phase_deadline = now + paused_remaining_seconds`, schedule new Celery task, clear pause fields
|
||||
- Stale task guard: every Celery task checks `expected_state == run.current_state` before firing
|
||||
|
||||
---
|
||||
|
||||
## Host Controls (Session Owner Only)
|
||||
|
||||
| Action | Effect |
|
||||
|--------|--------|
|
||||
| Play | Starts game from LOBBY, or resumes from paused |
|
||||
| Pause | Freezes current phase timer, broadcasts `phase.paused` |
|
||||
| Exit | Ends game immediately, deletes GameRun + all game data |
|
||||
|
||||
Cannot skip. Cannot manually advance phases.
|
||||
|
||||
---
|
||||
|
||||
## WebSocket Event Reference
|
||||
|
||||
| Event | Triggered by | Payload |
|
||||
|-------|-------------|---------|
|
||||
| `phase.lie_started` | LIE_PHASE start | question prompt, deadline, round info |
|
||||
| `phase.lie_progress` | Each lie submitted | n_submitted / n_players (no names) |
|
||||
| `phase.guess_started` | GUESS_PHASE start | mixed answers, deadline |
|
||||
| `phase.reveal_lie` | REVEAL_LIE_{n} | lie text, author, guessers, score delta |
|
||||
| `phase.reveal_truth` | REVEAL_TRUTH | correct answer, correct guessers, score delta |
|
||||
| `phase.scoreboard` | SCOREBOARD_RECAP | full leaderboard |
|
||||
| `phase.awards` | POST_GAME_AWARDS | award winners |
|
||||
| `phase.paused` | Pause | remaining_seconds |
|
||||
| `phase.resumed` | Resume | new deadline |
|
||||
| `phase.game_over` | FINISHED | final leaderboard |
|
||||
|
||||
---
|
||||
|
||||
## Data Lifecycle
|
||||
|
||||
All game session data (`GameRun`, `RoundQuestion`, `LieAnswer`, `Guess`, `LieReaction`, `Player`) is **deleted when host exits or game reaches FINISHED**. `GameSession` row is kept (with status=FINISHED) for the session code uniqueness constraint. `Category` and `Question` content is permanent.
|
||||
|
||||
---
|
||||
|
||||
## Not In Scope (This Implementation)
|
||||
|
||||
- TTS / read-aloud (Fase 4, deferred)
|
||||
- Reconnect recovery after server restart (game is gone if server dies)
|
||||
- Spectator/viewer mode (post-MVP)
|
||||
- Rate limiting on endpoints (backlog)
|
||||
- Bulk question import (Fase 5)
|
||||
2180
docs/plans/2026-03-09-fupogfakta-implementation-plan.md
Normal file
2180
docs/plans/2026-03-09-fupogfakta-implementation-plan.md
Normal file
File diff suppressed because it is too large
Load Diff
@@ -59,6 +59,31 @@ Trin-for-trin:
|
||||
|
||||
Target: rollback + sanity-verifikation inden for 10 minutter.
|
||||
|
||||
## React fallback trigger-kriterier (kun delivery-blocking)
|
||||
Formål: React fallback må kun bruges som kortvarig leverings-sikring, når release ellers er blokeret.
|
||||
|
||||
### Hvornår fallback er tilladt
|
||||
Alle punkter skal være opfyldt:
|
||||
1. **Delivery-blocking fejl i Angular SPA**
|
||||
- Host/player kerneflow kan ikke leveres i release-vinduet (fx login/join/start/round/scoreboard stopper).
|
||||
2. **Ingen hurtig Angular-fix inden for release-vinduet**
|
||||
- Teamet har vurderet at patch + verificering ikke kan nås sikkert i tide.
|
||||
3. **Rollback alene løser ikke leveringsbehovet**
|
||||
- `USE_SPA_UI=false` (legacy) er enten utilstrækkelig for den konkrete leverance eller allerede verificeret som ikke tilstrækkelig.
|
||||
4. **Beslutning er eksplicit logget**
|
||||
- Trigger, impact, UTC-tid, ansvarlig, issue/incident-reference og plan for tilbagevenden til Angular er dokumenteret i release/smoke artifact.
|
||||
|
||||
### Scope-limits for fallback
|
||||
- Fallback omfatter kun **delivery-blocking host/player-paths**.
|
||||
- Ingen nye features, UX-forbedringer eller ikke-kritiske ændringer må bundtes ind i fallback.
|
||||
- Fallback er **midlertidig** og gælder kun for aktiv incident/release-vindue.
|
||||
- Når blocker er fjernet, skal miljøet tilbage på standard cutover-spor (Angular + `USE_SPA_UI` styring).
|
||||
|
||||
### Ikke tilladt
|
||||
- Proaktiv fallback "for en sikkerheds skyld" uden aktiv blocker.
|
||||
- Brug af fallback til at omgå normale kvalitetsgates eller testkrav.
|
||||
- Langvarig drift i fallback-mode uden dokumenteret blocker og opfølgningsplan.
|
||||
|
||||
## Verifikation
|
||||
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
|
||||
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||
|
||||
@@ -262,5 +262,26 @@ describe('HostShellComponent gameplay wiring', () => {
|
||||
await component.refreshSession();
|
||||
|
||||
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
|
||||
expect(component.canStartRound).toBe(false);
|
||||
expect(component.canShowQuestion).toBe(false);
|
||||
expect(component.canMixAnswers).toBe(false);
|
||||
expect(component.canCalculateScores).toBe(true);
|
||||
});
|
||||
|
||||
it('uses phase_view_model to keep host action surface phase-specific', async () => {
|
||||
const component = new HostShellComponent();
|
||||
|
||||
expect(component.canStartRound).toBe(true);
|
||||
expect(component.canShowQuestion).toBe(false);
|
||||
|
||||
component.session = sessionDetailPayload('lie') as any;
|
||||
expect(component.canStartRound).toBe(false);
|
||||
expect(component.canShowQuestion).toBe(true);
|
||||
expect(component.canMixAnswers).toBe(true);
|
||||
|
||||
component.session = sessionDetailPayload('reveal') as any;
|
||||
expect(component.canRevealScoreboard).toBe(true);
|
||||
expect(component.canStartNextRound).toBe(false);
|
||||
expect(component.canFinishGame).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,6 +11,17 @@ interface SessionDetail {
|
||||
session: { code: string; status: string; current_round: number };
|
||||
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||
players: Array<{ id: number; nickname: string; score: number }>;
|
||||
phase_view_model?: {
|
||||
host?: {
|
||||
can_start_round?: boolean;
|
||||
can_show_question?: boolean;
|
||||
can_mix_answers?: boolean;
|
||||
can_calculate_scores?: boolean;
|
||||
can_reveal_scoreboard?: boolean;
|
||||
can_start_next_round?: boolean;
|
||||
can_finish_game?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
type LeaderboardEntry = ScoreboardResponse['leaderboard'][number];
|
||||
@@ -25,18 +36,15 @@ type LeaderboardResponse = FinishGameResponse;
|
||||
|
||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label>
|
||||
<label *ngIf="canStartRound">{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||
<button (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button>
|
||||
<button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button>
|
||||
<button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button>
|
||||
<button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button>
|
||||
<button (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.load_scoreboard') }}</button>
|
||||
<button (click)="startNextRound()" [disabled]="loading">{{ copy('host.start_next_round') }}</button>
|
||||
<button (click)="finishGame()" [disabled]="loading">{{ copy('host.finish_game') }}</button>
|
||||
<button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.retry_scoreboard') }}</button>
|
||||
<button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy('host.retry_next_round') }}</button>
|
||||
<button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">{{ copy('host.retry_finish') }}</button>
|
||||
<button *ngIf="canStartRound" (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button>
|
||||
<button *ngIf="canShowQuestion" (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button>
|
||||
<button *ngIf="canMixAnswers" (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button>
|
||||
<button *ngIf="canCalculateScores" (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button>
|
||||
<button *ngIf="canRevealScoreboard || scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy(scoreboardError ? 'host.retry_scoreboard' : 'host.load_scoreboard') }}</button>
|
||||
<button *ngIf="canStartNextRound || nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy(nextRoundError ? 'host.retry_next_round' : 'host.start_next_round') }}</button>
|
||||
<button *ngIf="canFinishGame || finishError" (click)="finishGame()" [disabled]="loading">{{ copy(finishError ? 'host.retry_finish' : 'host.finish_game') }}</button>
|
||||
</div>
|
||||
|
||||
<p *ngIf="session" class="hint">{{ copy('host.audio_locale_hint') }}: {{ locale }}</p>
|
||||
@@ -114,6 +122,34 @@ export class HostShellComponent implements OnInit, OnDestroy {
|
||||
this.unsubscribeLocale = null;
|
||||
}
|
||||
|
||||
get canStartRound(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_start_round ?? !this.session);
|
||||
}
|
||||
|
||||
get canShowQuestion(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_show_question);
|
||||
}
|
||||
|
||||
get canMixAnswers(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_mix_answers);
|
||||
}
|
||||
|
||||
get canCalculateScores(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_calculate_scores);
|
||||
}
|
||||
|
||||
get canRevealScoreboard(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_reveal_scoreboard);
|
||||
}
|
||||
|
||||
get canStartNextRound(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_start_next_round);
|
||||
}
|
||||
|
||||
get canFinishGame(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.host?.can_finish_game);
|
||||
}
|
||||
|
||||
copy(key: string): string {
|
||||
return t(key, this.locale);
|
||||
}
|
||||
|
||||
@@ -518,4 +518,28 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
expect(component.clientHasNoAudioOutput).toBe(false);
|
||||
});
|
||||
|
||||
it('keeps phone client controls phase-specific and low-complexity', () => {
|
||||
const component = new PlayerShellComponent();
|
||||
|
||||
expect(component.showJoinControls).toBe(true);
|
||||
expect(component.showLieControls).toBe(false);
|
||||
expect(component.showGuessControls).toBe(false);
|
||||
expect(component.showFinalLeaderboard).toBe(false);
|
||||
|
||||
component.session = sessionDetailPayload('lie') as any;
|
||||
component.playerId = 9;
|
||||
component.sessionToken = 'tok';
|
||||
expect(component.showJoinControls).toBe(false);
|
||||
expect(component.showLieControls).toBe(true);
|
||||
expect(component.showGuessControls).toBe(false);
|
||||
|
||||
component.session = sessionDetailPayload('guess', { answers: ['A', 'B'] }) as any;
|
||||
expect(component.showLieControls).toBe(false);
|
||||
expect(component.showGuessControls).toBe(true);
|
||||
|
||||
component.session = sessionDetailPayload('finished', { players: [{ id: 1, nickname: 'Luna', score: 8 }] }) as any;
|
||||
expect(component.showGuessControls).toBe(false);
|
||||
expect(component.showFinalLeaderboard).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -11,6 +11,14 @@ interface SessionDetail {
|
||||
session: { code: string; status: string; current_round: number };
|
||||
round_question: { id: number; prompt: string; answers: Array<{ text: string }> } | null;
|
||||
players: Array<{ id: number; nickname: string; score: number }>;
|
||||
phase_view_model?: {
|
||||
player?: {
|
||||
can_join?: boolean;
|
||||
can_submit_lie?: boolean;
|
||||
can_submit_guess?: boolean;
|
||||
can_view_final_result?: boolean;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
||||
@@ -49,9 +57,9 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
|
||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
|
||||
<label *ngIf="showJoinControls">{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||
<button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
|
||||
<button *ngIf="showJoinControls" (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
|
||||
</div>
|
||||
|
||||
<p *ngIf="connectionState === 'reconnecting'" class="error">
|
||||
@@ -71,26 +79,30 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
|
||||
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
|
||||
|
||||
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
|
||||
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button>
|
||||
<ng-container *ngIf="showLieControls">
|
||||
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading" /></label>
|
||||
<button (click)="submitLie()" [disabled]="loading">{{ copy('player.submit_lie') }}</button>
|
||||
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
|
||||
</ng-container>
|
||||
|
||||
<ng-container *ngIf="showGuessControls">
|
||||
<div class="answers" *ngIf="session.round_question?.answers?.length">
|
||||
<button
|
||||
type="button"
|
||||
*ngFor="let answer of session.round_question?.answers"
|
||||
(click)="selectedGuess = answer.text"
|
||||
[class.active]="selectedGuess === answer.text"
|
||||
[disabled]="loading || session.session.status !== 'guess'"
|
||||
[disabled]="loading"
|
||||
>
|
||||
{{ answer.text }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button>
|
||||
<button (click)="submitGuess()" [disabled]="loading || !selectedGuess">{{ copy('player.submit_guess') }}</button>
|
||||
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
|
||||
</ng-container>
|
||||
|
||||
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
|
||||
<div *ngIf="showFinalLeaderboard && finalLeaderboard.length">
|
||||
<h3>{{ copy('player.final_leaderboard') }}</h3>
|
||||
<ol>
|
||||
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||
@@ -300,6 +312,25 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
get showJoinControls(): boolean {
|
||||
if (!this.session) {
|
||||
return true;
|
||||
}
|
||||
return Boolean(this.session?.phase_view_model?.player?.can_join && !this.playerId && !this.sessionToken);
|
||||
}
|
||||
|
||||
get showLieControls(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.player?.can_submit_lie);
|
||||
}
|
||||
|
||||
get showGuessControls(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.player?.can_submit_guess);
|
||||
}
|
||||
|
||||
get showFinalLeaderboard(): boolean {
|
||||
return Boolean(this.session?.phase_view_model?.player?.can_view_final_result);
|
||||
}
|
||||
|
||||
get loadingMessage(): string {
|
||||
switch (this.loadingTransition) {
|
||||
case 'join':
|
||||
|
||||
@@ -4,42 +4,56 @@ import { HostShellComponent } from './features/host/host-shell.component';
|
||||
import { PlayerShellComponent } from './features/player/player-shell.component';
|
||||
import { setPreferredLocale } from './lobby-i18n';
|
||||
|
||||
function stubShellGlobals(initialLocale: string) {
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue(initialLocale), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: `${initialLocale}-US`, onLine: true });
|
||||
}
|
||||
|
||||
describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('resolves host/player copy in en and da from shared catalog', () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
it.each([
|
||||
{
|
||||
locale: 'en',
|
||||
hostRefresh: 'Refresh',
|
||||
hostStartRound: 'Start round',
|
||||
playerSubmitGuess: 'Submit guess',
|
||||
},
|
||||
{
|
||||
locale: 'da',
|
||||
hostRefresh: 'Opdatér',
|
||||
hostStartRound: 'Start runde',
|
||||
playerSubmitGuess: 'Send gæt',
|
||||
},
|
||||
])('resolves one host/player locale run for $locale', ({ locale, hostRefresh, hostStartRound, playerSubmitGuess }) => {
|
||||
stubShellGlobals(locale);
|
||||
|
||||
const host = new HostShellComponent();
|
||||
const player = new PlayerShellComponent();
|
||||
host.ngOnInit();
|
||||
player.ngOnInit();
|
||||
setPreferredLocale(locale);
|
||||
|
||||
expect(host.copy('game.host.start_round')).toBe('Start round');
|
||||
expect(player.copy('game.player.submit_guess')).toBe('Submit guess');
|
||||
|
||||
setPreferredLocale('da');
|
||||
|
||||
expect(host.copy('game.host.start_round')).toBe('Start runde');
|
||||
expect(player.copy('game.player.submit_guess')).toBe('Send gæt');
|
||||
expect(host.copy('common.refresh')).toBe(hostRefresh);
|
||||
expect(host.copy('game.host.start_round')).toBe(hostStartRound);
|
||||
expect(player.copy('game.player.submit_guess')).toBe(playerSubmitGuess);
|
||||
|
||||
player.ngOnDestroy();
|
||||
host.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('keeps audio routing policy primary-only (client has no audio output)', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
it('keeps audio routing primary-only by guarding player playback without muting the host path', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('primary host playback'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
@@ -57,7 +71,7 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
const host = new HostShellComponent();
|
||||
host.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('primary host playback');
|
||||
|
||||
const player = new PlayerShellComponent();
|
||||
player.ngOnInit();
|
||||
@@ -66,7 +80,7 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
|
||||
player.ngOnDestroy();
|
||||
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('primary host playback');
|
||||
|
||||
host.ngOnDestroy();
|
||||
});
|
||||
|
||||
@@ -24,6 +24,15 @@ def lobby_i18n_error_messages() -> dict:
|
||||
return shared_i18n_catalog().get("backend", {}).get("errors", {})
|
||||
|
||||
|
||||
def resolve_error_key(code: str) -> str:
|
||||
resolved = lobby_i18n_errors().get(code)
|
||||
if isinstance(resolved, str) and resolved:
|
||||
return resolved
|
||||
|
||||
LOGGER.warning("i18n error code missing in shared catalog", extra={"code": code})
|
||||
return code
|
||||
|
||||
|
||||
def _quality_value(language_candidate: str) -> float | None:
|
||||
for parameter in language_candidate.split(";")[1:]:
|
||||
key, separator, value = parameter.partition("=")
|
||||
@@ -78,12 +87,13 @@ def resolve_error_message(*, key: str, locale: str) -> str:
|
||||
return key
|
||||
|
||||
|
||||
def api_error(request: HttpRequest, *, key: str, status: int) -> JsonResponse:
|
||||
def api_error(request: HttpRequest, *, code: str, status: int) -> JsonResponse:
|
||||
locale = resolve_locale(request)
|
||||
key = resolve_error_key(code)
|
||||
return JsonResponse(
|
||||
{
|
||||
"error": resolve_error_message(key=key, locale=locale),
|
||||
"error_code": key,
|
||||
"error_code": code,
|
||||
"locale": locale,
|
||||
},
|
||||
status=status,
|
||||
|
||||
@@ -55,8 +55,12 @@
|
||||
<p id="hostCriticalPlayers">Spillere: afventer</p>
|
||||
<p id="hostCriticalRound">Aktiv round question: afventer</p>
|
||||
</section>
|
||||
<pre id="out">Klar.</pre>
|
||||
<pre id="out">Ready.</pre>
|
||||
{{ lobby_i18n|json_script:"wppHostI18n" }}
|
||||
<script>
|
||||
var WPP_HOST_LOCALE="{{ shell_locale|default:'en'|escapejs }}";
|
||||
var WPP_HOST_I18N=JSON.parse(document.getElementById("wppHostI18n").textContent||"{}");
|
||||
function hostCopy(path,fallback){var node=WPP_HOST_I18N;var parts=(path||"").split(".");for(var i=0;i<parts.length;i++){if(!node||typeof node!=="object"){return fallback||path;}node=node[parts[i]];}if(node&&typeof node==="object"){if(node[WPP_HOST_LOCALE]){return node[WPP_HOST_LOCALE];}if(node.en){return node.en;}}return typeof node==="string"?node:(fallback||path);}
|
||||
var currentSessionStatus="";
|
||||
var autoRefreshEnabled=false;
|
||||
var autoRefreshTimer=null;
|
||||
@@ -85,7 +89,7 @@ function code(){return document.getElementById("code").value.trim().toUpperCase(
|
||||
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
||||
function saveHostContext(){try{localStorage.setItem("wppHostContext",JSON.stringify({code:code(),round_question_id:rq(),session_status:currentSessionStatus||"",auto_refresh:autoRefreshEnabled}));}catch(_e){}}
|
||||
function restoreHostContext(){try{var raw=localStorage.getItem("wppHostContext");if(!raw){return false;}var ctx=JSON.parse(raw);if(ctx.code){document.getElementById("code").value=(ctx.code||"").toUpperCase();}if(ctx.round_question_id){document.getElementById("roundQuestionId").value=ctx.round_question_id;}if(ctx.session_status){currentSessionStatus=ctx.session_status;}autoRefreshEnabled=!!ctx.auto_refresh;updateAutoRefreshUi();return !!ctx.code;}catch(_e){return false;}}
|
||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Afsluttet";}return"Ukendt";}
|
||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Lie";}if(status==="guess"){return"Guess";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Finished";}return"Unknown";}
|
||||
function hostShellRouteFromPath(){var marker="/lobby/ui/host";var path=(window.location.pathname||"").toLowerCase();var idx=path.indexOf(marker);if(idx===-1){return"";}var remainder=path.slice(idx+marker.length).replace(/^\/+|\/+$/g,"");if(!remainder){return"";}var route=remainder.split("/")[0];return HOST_SHELL_ROUTES[route]?route:"";}
|
||||
function expectedHostShellRoute(){return HOST_SHELL_ROUTES[currentSessionStatus]||"";}
|
||||
function syncHostShellRoute(){var currentRoute=hostShellRouteFromPath();var expectedRoute=expectedHostShellRoute();if(!currentRoute||!expectedRoute){hostShellRouteHint="";return;}if(currentRoute===expectedRoute){hostShellRouteHint="";return;}var nextPath="/lobby/ui/host/"+expectedRoute;window.history.replaceState(null,"",nextPath);hostShellRouteHint="Deep-link route guard: omdirigeret fra /"+currentRoute+" til /"+expectedRoute+" for fase "+phaseLabel(currentSessionStatus)+".";}
|
||||
@@ -93,11 +97,11 @@ function updateAutoRefreshUi(){var btn=document.getElementById("autoRefreshToggl
|
||||
function stopAutoRefresh(reason){autoRefreshEnabled=false;if(autoRefreshTimer){clearInterval(autoRefreshTimer);autoRefreshTimer=null;}if(reason){var hint=document.getElementById("autoRefreshHint");if(hint){hint.textContent=reason;}}updateAutoRefreshUi();saveHostContext();}
|
||||
function startAutoRefresh(){if(!code()){updateAutoRefreshUi();return;}autoRefreshEnabled=true;if(autoRefreshTimer){clearInterval(autoRefreshTimer);}autoRefreshTimer=setInterval(function(){if(!code()||sessionDetailInFlight){return;}if(currentSessionStatus==="finished"){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");return;}sessionDetail();},10000);updateAutoRefreshUi();saveHostContext();}
|
||||
function toggleAutoRefresh(){if(hostActionInFlight||sessionDetailInFlight||!code()){updateAutoRefreshUi();return;}if(autoRefreshEnabled){stopAutoRefresh();return;}startAutoRefresh();}
|
||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString("da-DK",{hour12:false});}
|
||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString(WPP_HOST_LOCALE,{hour12:false});}
|
||||
function markSessionRefresh(status){if(status>=200&&status<300){lastRefreshAtLabel=formatTimeLabel(new Date());lastRefreshFailed=false;}else{lastRefreshFailed=true;}updateLastRefreshStatus();}
|
||||
function updateLastRefreshStatus(){var el=document.getElementById("lastRefreshStatus");if(!el){return;}if(!lastRefreshAtLabel){el.textContent=lastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(lastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+lastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+lastRefreshAtLabel+".";}
|
||||
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(key.indexOf("phase")!==-1){return"Ugyldig fase for handlingen. Opdatér session-status og prøv igen.";}if(key.indexOf("token")!==-1||key.indexOf("auth")!==-1){return"Session-token er ugyldig eller udløbet. Rejoin sessionen og prøv igen.";}if(key.indexOf("round")!==-1||key.indexOf("question")!==-1||key.indexOf("state")!==-1){return"Runde-kontekst matcher ikke længere. Opdatér session-status før næste handling.";}if(key.indexOf("session")!==-1){return"Sessionkoden er ugyldig eller sessionen findes ikke længere.";}return"Handling fejlede. Opdatér session-status og prøv igen.";}
|
||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(WPP_HOST_I18N&&WPP_HOST_I18N.backend&&WPP_HOST_I18N.backend.errors&&WPP_HOST_I18N.backend.errors[key]){return hostCopy("backend.errors."+key,"Action failed. Refresh state and retry.");}if(key.indexOf("session")!==-1){return hostCopy("backend.errors.session_not_found_or_closed","Session code is invalid, or session no longer exists.");}return hostCopy("backend.errors.generic_action_failed_retry","Action failed. Refresh state and retry.");}
|
||||
function updateErrorHint(status,data){var el=document.getElementById("hostErrorHint");if(!el){return;}if(status>=200&&status<300){el.textContent="Ingen fejl.";return;}var errKey=normalizeApiError(data);el.textContent="Fejl: "+mapUiErrorMessage(errKey)+" ("+(errKey||("http_"+status))+")";}
|
||||
function updateCreateSessionState(){var btn=document.getElementById("createSessionBtn");var hint=document.getElementById("createSessionHint");if(btn){btn.disabled=hostActionInFlight||sessionDetailInFlight;}if(!hint){return;}if(hostActionInFlight){hint.textContent="Opret session er låst mens en host-handling kører.";return;}if(sessionDetailInFlight){hint.textContent="Opret session er låst mens session-opdatering kører.";return;}hint.textContent="Opret session er klar.";}function updateSessionDetailState(){var btn=document.getElementById("sessionDetailBtn");var hint=document.getElementById("sessionDetailHint");var codeInput=document.getElementById("code");if(btn){btn.disabled=sessionDetailInFlight||hostActionInFlight||!code();}if(codeInput){codeInput.readOnly=sessionDetailInFlight||hostActionInFlight;}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Opdaterer session-status…";return;}if(hostActionInFlight){hint.textContent="Session-opdatering er låst mens en host-handling kører.";return;}if(!code()){hint.textContent="Angiv sessionkode for at opdatere session-status.";updateHostShellErrorBoundary();return;}hint.textContent="Session-opdatering klar.";updateHostShellErrorBoundary();}
|
||||
|
||||
|
||||
@@ -69,8 +69,12 @@
|
||||
<p id="playerCriticalRound">Round question: afventer</p>
|
||||
<p id="playerCriticalJoin">Join-status: afventer</p>
|
||||
</section>
|
||||
<pre id="out">Klar.</pre>
|
||||
<pre id="out">Ready.</pre>
|
||||
{{ lobby_i18n|json_script:"wppPlayerI18n" }}
|
||||
<script>
|
||||
var WPP_PLAYER_LOCALE="{{ shell_locale|default:'en'|escapejs }}";
|
||||
var WPP_PLAYER_I18N=JSON.parse(document.getElementById("wppPlayerI18n").textContent||"{}");
|
||||
function playerCopy(path,fallback){var node=WPP_PLAYER_I18N;var parts=(path||"").split(".");for(var i=0;i<parts.length;i++){if(!node||typeof node!=="object"){return fallback||path;}node=node[parts[i]];}if(node&&typeof node==="object"){if(node[WPP_PLAYER_LOCALE]){return node[WPP_PLAYER_LOCALE];}if(node.en){return node.en;}}return typeof node==="string"?node:(fallback||path);}
|
||||
var availableAnswers=[];
|
||||
var guessSubmitted=false;
|
||||
var lieSubmitted=false;
|
||||
@@ -105,7 +109,7 @@ function clearPlayerShellFatalError(){playerShellFatalError=false;playerShellRec
|
||||
function recoverPlayerShell(mode){if(playerShellRecoverInFlight){return Promise.resolve({error:"recover_in_flight"});}playerShellRecoverInFlight=true;updatePlayerShellErrorBoundary();if(mode==="reload"){window.location.reload();return Promise.resolve({ok:true});}if(!code()){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();return Promise.resolve({error:"missing_session_code"});}return sessionDetail().then(function(result){clearPlayerShellFatalError();return result;}).catch(function(err){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();throw err;});}
|
||||
function pid(){return document.getElementById("playerId").value.trim();}
|
||||
function rq(){return document.getElementById("roundQuestionId").value.trim();}
|
||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Afsluttet";}return"Ukendt";}
|
||||
function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Lie";}if(status==="guess"){return"Guess";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Finished";}return"Unknown";}
|
||||
function updatePhaseStatus(){var el=document.getElementById("phaseStatus");if(!el){return;}if(!currentSessionStatus){el.textContent="Fase: ukendt (opdatér session-status).";return;}el.textContent="Fase: "+phaseLabel(currentSessionStatus)+" ("+currentSessionStatus+")";}
|
||||
function savePlayerContext(){try{localStorage.setItem(PLAYER_CONTEXT_KEY,JSON.stringify({code:code(),nickname:document.getElementById("nickname").value.trim(),player_id:pid(),session_token:document.getElementById("sessionToken").value.trim(),round_question_id:rq(),auto_refresh:playerAutoRefreshEnabled}));}catch(_e){}}
|
||||
function loadPlayerContext(){try{var raw=localStorage.getItem(PLAYER_CONTEXT_KEY);if(!raw){return null;}return JSON.parse(raw);}catch(_e){return null;}}
|
||||
@@ -118,8 +122,8 @@ function resetRoundContextForManualChange(){document.getElementById("roundQuesti
|
||||
function updateContextLockState(){var locked=isPlayerContextLocked()||joinInFlight;var codeField=document.getElementById("code");var nicknameField=document.getElementById("nickname");var playerIdField=document.getElementById("playerId");var tokenField=document.getElementById("sessionToken");if(codeField){codeField.readOnly=locked;}if(nicknameField){nicknameField.readOnly=locked;}if(playerIdField){playerIdField.readOnly=locked;}if(tokenField){tokenField.readOnly=true;}var hint=document.getElementById("contextLockHint");if(!hint){return;}if(joinInFlight){hint.textContent="Låser kontekst…";return;}if(locked){hint.textContent="Spillerkontekst er låst efter join.";return;}hint.textContent="Kontekst er ikke låst endnu.";}
|
||||
function canAttemptJoin(){return !!(code()&&document.getElementById("nickname").value.trim());}
|
||||
function normalizeApiError(data){if(!data||typeof data!=="object"){return"";}return (data.error_code||data.error||"").toString();}
|
||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(key.indexOf("phase")!==-1){return"Ugyldig fase for handlingen. Opdatér session-status og prøv igen.";}if(key.indexOf("token")!==-1||key.indexOf("auth")!==-1){return"Session-token er ugyldig eller udløbet. Rejoin sessionen og prøv igen.";}if(key.indexOf("round")!==-1||key.indexOf("question")!==-1||key.indexOf("state")!==-1){return"Runde-kontekst matcher ikke længere. Opdatér session-status før næste handling.";}if(key.indexOf("session")!==-1){return"Sessionkoden er ugyldig eller sessionen findes ikke længere.";}return"Handling fejlede. Opdatér session-status og prøv igen.";}
|
||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString("da-DK",{hour12:false});}
|
||||
function mapUiErrorMessage(errorKey){if(!errorKey){return"";}var key=errorKey.toLowerCase();if(WPP_PLAYER_I18N&&WPP_PLAYER_I18N.backend&&WPP_PLAYER_I18N.backend.errors&&WPP_PLAYER_I18N.backend.errors[key]){return playerCopy("backend.errors."+key,"Action failed. Refresh state and retry.");}if(key.indexOf("session")!==-1){return playerCopy("backend.errors.session_not_found_or_closed","Session code is invalid, or session no longer exists.");}return playerCopy("backend.errors.generic_action_failed_retry","Action failed. Refresh state and retry.");}
|
||||
function formatTimeLabel(dateObj){return dateObj.toLocaleTimeString(WPP_PLAYER_LOCALE,{hour12:false});}
|
||||
function markPlayerSessionRefresh(status){if(status>=200&&status<300){playerLastRefreshAtLabel=formatTimeLabel(new Date());playerLastRefreshFailed=false;}else{playerLastRefreshFailed=true;}updatePlayerLastRefreshStatus();}
|
||||
function updatePlayerLastRefreshStatus(){var el=document.getElementById("playerLastRefreshStatus");if(!el){return;}if(!playerLastRefreshAtLabel){el.textContent=playerLastRefreshFailed?"Session-data kan være forældet (ingen succesfuld opdatering endnu).":"Session-data ikke opdateret endnu.";return;}if(playerLastRefreshFailed){el.textContent="Session-data kan være forældet (seneste succes: "+playerLastRefreshAtLabel+").";return;}el.textContent="Sidst opdateret: "+playerLastRefreshAtLabel+".";}
|
||||
function updatePlayerAutoRefreshUi(){var btn=document.getElementById("playerAutoRefreshToggleBtn");var hint=document.getElementById("playerAutoRefreshHint");if(btn){btn.textContent="Auto-refresh: "+(playerAutoRefreshEnabled?"ON":"OFF");btn.disabled=sessionDetailInFlight||joinInFlight||!code();}if(!hint){return;}if(sessionDetailInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv session-opdatering.";return;}if(joinInFlight){hint.textContent="Auto-refresh-lås: afvent aktiv join.";return;}if(!code()){hint.textContent="Auto-refresh kræver sessionkode.";return;}if(!playerAutoRefreshEnabled){hint.textContent="Auto-refresh er slået fra.";return;}if(currentSessionStatus==="finished"){hint.textContent="Auto-refresh stoppet: spillet er afsluttet.";return;}hint.textContent="Auto-refresh aktiv (10s) for spillerstatus.";}
|
||||
|
||||
104
lobby/tests.py
104
lobby/tests.py
@@ -375,6 +375,8 @@ class LieSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "lie_submission_closed")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Lie submission window has closed")
|
||||
|
||||
def test_submit_lie_rejects_duplicate_submission(self):
|
||||
@@ -396,6 +398,8 @@ class LieSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(response.json()["error_code"], "lie_already_submitted")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Lie already submitted for this player")
|
||||
|
||||
def test_submit_lie_requires_session_token(self):
|
||||
@@ -416,6 +420,8 @@ class LieSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "session_token_required")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "session_token is required")
|
||||
|
||||
def test_submit_lie_rejects_invalid_session_token(self):
|
||||
@@ -436,8 +442,33 @@ class LieSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "invalid_player_session_token")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Invalid player session token")
|
||||
|
||||
def test_submit_lie_uses_danish_locale_payload_from_accept_language(self):
|
||||
round_question = RoundQuestion.objects.create(
|
||||
session=self.session,
|
||||
round_number=1,
|
||||
question=self.question,
|
||||
correct_answer=self.question.correct_answer,
|
||||
)
|
||||
|
||||
response = self.client.post(
|
||||
reverse(
|
||||
"lobby:submit_lie",
|
||||
kwargs={"code": self.session.code, "round_question_id": round_question.id},
|
||||
),
|
||||
data={"player_id": self.player.id, "session_token": "invalid-token", "text": "Sydney"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da-DK,da;q=0.9,en;q=0.1",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "invalid_player_session_token")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Ugyldigt spiller-session-token")
|
||||
|
||||
class MixAnswersTests(TestCase):
|
||||
def setUp(self):
|
||||
self.host = User.objects.create_user(username="host", password="secret123")
|
||||
@@ -597,6 +628,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "guess_submission_invalid_phase")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Guess submission is only allowed in guess phase")
|
||||
|
||||
def test_submit_guess_rejects_unknown_answer(self):
|
||||
@@ -610,6 +643,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "selected_answer_invalid")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Selected answer is not part of this round")
|
||||
|
||||
def test_submit_guess_rejects_duplicate_submission(self):
|
||||
@@ -625,6 +660,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 409)
|
||||
self.assertEqual(response.json()["error_code"], "guess_already_submitted")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Guess already submitted for this player")
|
||||
|
||||
def test_submit_guess_rejects_after_deadline(self):
|
||||
@@ -641,6 +678,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "guess_submission_closed")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Guess submission window has closed")
|
||||
|
||||
|
||||
@@ -656,6 +695,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "session_token_required")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "session_token is required")
|
||||
|
||||
def test_submit_guess_rejects_invalid_session_token(self):
|
||||
@@ -669,6 +710,8 @@ class GuessSubmissionTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "invalid_player_session_token")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Invalid player session token")
|
||||
|
||||
|
||||
@@ -750,6 +793,8 @@ class ScoreCalculationTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_calculate_scores")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can calculate scores")
|
||||
|
||||
def test_calculate_scores_rejects_duplicate_calculation(self):
|
||||
@@ -771,6 +816,8 @@ class ScoreCalculationTests(TestCase):
|
||||
|
||||
self.assertEqual(first.status_code, 200)
|
||||
self.assertEqual(second.status_code, 409)
|
||||
self.assertEqual(second.json()["error_code"], "scores_already_calculated")
|
||||
self.assertEqual(second.json()["locale"], "en")
|
||||
self.assertEqual(second.json()["error"], "Scores already calculated for this round question")
|
||||
|
||||
|
||||
@@ -824,11 +871,9 @@ class RevealRoundFlowTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json(), {
|
||||
"error": "Only host can view scoreboard",
|
||||
"error_code": "host_only_view_scoreboard",
|
||||
"locale": "en",
|
||||
})
|
||||
self.assertEqual(response.json()["error_code"], "host_only_view_scoreboard")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can view scoreboard")
|
||||
|
||||
def test_reveal_scoreboard_is_idempotent_in_scoreboard_phase(self):
|
||||
self.session.status = GameSession.Status.SCOREBOARD
|
||||
@@ -875,11 +920,9 @@ class RevealRoundFlowTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json(), {
|
||||
"error": "Kun værten kan afslutte spillet",
|
||||
"error_code": "host_only_finish_game",
|
||||
"locale": "da",
|
||||
})
|
||||
self.assertEqual(response.json()["error_code"], "host_only_finish_game")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Kun værten kan afslutte spillet")
|
||||
|
||||
def test_finish_game_rejects_wrong_phase(self):
|
||||
self.client.login(username="host_reveal", password="secret123")
|
||||
@@ -895,11 +938,9 @@ class RevealRoundFlowTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json(), {
|
||||
"error": "Game can only be finished from scoreboard phase",
|
||||
"error_code": "finish_game_invalid_phase",
|
||||
"locale": "en",
|
||||
})
|
||||
self.assertEqual(response.json()["error_code"], "finish_game_invalid_phase")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Game can only be finished from scoreboard phase")
|
||||
|
||||
@patch("lobby.views.sync_broadcast_phase_event")
|
||||
def test_host_can_start_next_round_from_scoreboard(self, _mock_sync_broadcast_phase_event):
|
||||
@@ -980,11 +1021,25 @@ class RevealRoundFlowTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json(), {
|
||||
"error": "Næste runde kan kun starte fra scoreboard-fasen",
|
||||
"error_code": "next_round_invalid_phase",
|
||||
"locale": "da",
|
||||
})
|
||||
self.assertEqual(response.json()["error_code"], "next_round_invalid_phase")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Næste runde kan kun starte fra scoreboard-fasen")
|
||||
|
||||
def test_reveal_scoreboard_unsupported_locale_falls_back_to_en_deterministically(self):
|
||||
self.client.login(username="other_reveal", password="secret123")
|
||||
|
||||
response = self.client.get(
|
||||
reverse(
|
||||
"lobby:reveal_scoreboard",
|
||||
kwargs={"code": self.session.code},
|
||||
),
|
||||
HTTP_ACCEPT_LANGUAGE="fr-FR,fr;q=0.9",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_view_scoreboard")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can view scoreboard")
|
||||
|
||||
class UiScreenTests(TestCase):
|
||||
def setUp(self):
|
||||
@@ -1472,6 +1527,15 @@ class I18nResolverTests(TestCase):
|
||||
self.assertEqual(result, "missing_key")
|
||||
self.assertTrue(any("i18n key missing in shared catalog" in entry for entry in logs.output))
|
||||
|
||||
def test_missing_backend_error_code_is_logged_with_context(self):
|
||||
from lobby.i18n import resolve_error_key
|
||||
|
||||
with self.assertLogs("lobby.i18n", level="WARNING") as logs:
|
||||
result = resolve_error_key("missing_code")
|
||||
|
||||
self.assertEqual(result, "missing_code")
|
||||
self.assertTrue(any("i18n error code missing in shared catalog" in entry for entry in logs.output))
|
||||
|
||||
def test_missing_locale_translation_falls_back_to_default_locale(self):
|
||||
with patch(
|
||||
"lobby.i18n.lobby_i18n_error_messages",
|
||||
|
||||
@@ -40,6 +40,7 @@ def host_screen(request, spa_path=None):
|
||||
{
|
||||
"categories": categories,
|
||||
"lobby_i18n": lobby_i18n_catalog(),
|
||||
"shell_locale": resolve_locale(request),
|
||||
},
|
||||
)
|
||||
|
||||
@@ -48,4 +49,8 @@ def player_screen(request):
|
||||
if use_spa_ui():
|
||||
return _render_spa_shell(request, "/player", "player")
|
||||
|
||||
return render(request, "lobby/player_screen.html", {"lobby_i18n": lobby_i18n_catalog()})
|
||||
return render(
|
||||
request,
|
||||
"lobby/player_screen.html",
|
||||
{"lobby_i18n": lobby_i18n_catalog(), "shell_locale": resolve_locale(request)},
|
||||
)
|
||||
|
||||
237
lobby/views.py
237
lobby/views.py
@@ -21,7 +21,9 @@ from fupogfakta.models import (
|
||||
)
|
||||
from realtime.broadcast import sync_broadcast_phase_event
|
||||
|
||||
from .i18n import api_error, lobby_i18n_errors
|
||||
from realtime.broadcast import sync_broadcast_phase_event
|
||||
|
||||
from .i18n import api_error
|
||||
|
||||
SESSION_CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"
|
||||
SESSION_CODE_LENGTH = 6
|
||||
@@ -33,7 +35,7 @@ JOINABLE_STATUSES = {
|
||||
GameSession.Status.REVEAL,
|
||||
GameSession.Status.SCOREBOARD,
|
||||
}
|
||||
ERROR_CODES = lobby_i18n_errors()
|
||||
|
||||
|
||||
|
||||
def _json_body(request: HttpRequest) -> dict:
|
||||
@@ -132,14 +134,14 @@ def join_session(request: HttpRequest) -> JsonResponse:
|
||||
if not code:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_code_required", "session_code_required"),
|
||||
code="session_code_required",
|
||||
status=400,
|
||||
)
|
||||
|
||||
if len(nickname) < 2 or len(nickname) > 40:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("nickname_invalid", "nickname_invalid"),
|
||||
code="nickname_invalid",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -148,21 +150,21 @@ def join_session(request: HttpRequest) -> JsonResponse:
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
code="session_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.status not in JOINABLE_STATUSES:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_joinable", "session_not_joinable"),
|
||||
code="session_not_joinable",
|
||||
status=400,
|
||||
)
|
||||
|
||||
if Player.objects.filter(session=session, nickname__iexact=nickname).exists():
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("nickname_taken", "nickname_taken"),
|
||||
code="nickname_taken",
|
||||
status=409,
|
||||
)
|
||||
|
||||
@@ -194,7 +196,7 @@ def session_detail(request: HttpRequest, code: str) -> JsonResponse:
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
code="session_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
@@ -255,7 +257,7 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
if not category_slug:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("category_slug_required", "category_slug_required"),
|
||||
code="category_slug_required",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -266,21 +268,21 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
code="session_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_start_round", "host_only_start_round"),
|
||||
code="host_only_start_round",
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LOBBY:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
code="round_start_invalid_phase",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -289,14 +291,14 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
except Category.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("category_not_found", "category_not_found"),
|
||||
code="category_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
if not Question.objects.filter(category=category, is_active=True).exists():
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("category_has_no_questions", "category_has_no_questions"),
|
||||
code="category_has_no_questions",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -305,7 +307,7 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
if session.status != GameSession.Status.LOBBY:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
code="round_start_invalid_phase",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -317,13 +319,23 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
if not created:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_already_configured", "round_already_configured"),
|
||||
code="round_already_configured",
|
||||
status=409,
|
||||
)
|
||||
|
||||
session.status = GameSession.Status.LIE
|
||||
session.save(update_fields=["status"])
|
||||
|
||||
sync_broadcast_phase_event(
|
||||
session.code,
|
||||
"phase.lie_started",
|
||||
{
|
||||
"round_number": session.current_round,
|
||||
"category": {"slug": round_config.category.slug, "name": round_config.category.name},
|
||||
"lie_seconds": round_config.lie_seconds,
|
||||
},
|
||||
)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"session": {
|
||||
@@ -353,21 +365,21 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
code="session_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_show_question", "host_only_show_question"),
|
||||
code="host_only_show_question",
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LIE:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("show_question_invalid_phase", "show_question_invalid_phase"),
|
||||
code="show_question_invalid_phase",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -376,14 +388,14 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
except RoundConfig.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_config_missing", "round_config_missing"),
|
||||
code="round_config_missing",
|
||||
status=400,
|
||||
)
|
||||
|
||||
if RoundQuestion.objects.filter(session=session, round_number=session.current_round).exists():
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("question_already_shown", "question_already_shown"),
|
||||
code="question_already_shown",
|
||||
status=409,
|
||||
)
|
||||
|
||||
@@ -396,7 +408,7 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
if not available_questions.exists():
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("no_available_questions", "no_available_questions"),
|
||||
code="no_available_questions",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -410,6 +422,18 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
|
||||
lie_deadline_at = round_question.shown_at + timedelta(seconds=round_config.lie_seconds)
|
||||
|
||||
sync_broadcast_phase_event(
|
||||
session.code,
|
||||
"phase.question_shown",
|
||||
{
|
||||
"round_question_id": round_question.id,
|
||||
"prompt": question.prompt,
|
||||
"shown_at": round_question.shown_at.isoformat(),
|
||||
"lie_deadline_at": lie_deadline_at.isoformat(),
|
||||
"lie_seconds": round_config.lie_seconds,
|
||||
},
|
||||
)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"round_question": {
|
||||
@@ -437,29 +461,29 @@ def submit_lie(request: HttpRequest, code: str, round_question_id: int) -> JsonR
|
||||
lie_text = str(payload.get("text", "")).strip()
|
||||
|
||||
if not player_id:
|
||||
return JsonResponse({"error": "player_id is required"}, status=400)
|
||||
return api_error(request, code="player_id_required", status=400)
|
||||
|
||||
if not session_token:
|
||||
return JsonResponse({"error": "session_token is required"}, status=400)
|
||||
return api_error(request, code="session_token_required", status=400)
|
||||
|
||||
if not lie_text or len(lie_text) > 255:
|
||||
return JsonResponse({"error": "text must be between 1 and 255 characters"}, status=400)
|
||||
return api_error(request, code="lie_text_invalid", status=400)
|
||||
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.status != GameSession.Status.LIE:
|
||||
return JsonResponse({"error": "Lie submission is only allowed in lie phase"}, status=400)
|
||||
return api_error(request, code="lie_submission_invalid_phase", status=400)
|
||||
|
||||
try:
|
||||
player = Player.objects.get(pk=player_id, session=session)
|
||||
except Player.DoesNotExist:
|
||||
return JsonResponse({"error": "Player not found in session"}, status=404)
|
||||
return api_error(request, code="player_not_found_in_session", status=404)
|
||||
|
||||
if player.session_token != session_token:
|
||||
return JsonResponse({"error": "Invalid player session token"}, status=403)
|
||||
return api_error(request, code="invalid_player_session_token", status=403)
|
||||
|
||||
try:
|
||||
round_question = RoundQuestion.objects.get(
|
||||
@@ -468,21 +492,21 @@ def submit_lie(request: HttpRequest, code: str, round_question_id: int) -> JsonR
|
||||
round_number=session.current_round,
|
||||
)
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return JsonResponse({"error": "Round question not found"}, status=404)
|
||||
return api_error(request, code="round_question_not_found", status=404)
|
||||
|
||||
try:
|
||||
round_config = RoundConfig.objects.get(session=session, number=round_question.round_number)
|
||||
except RoundConfig.DoesNotExist:
|
||||
return JsonResponse({"error": "Round config missing"}, status=400)
|
||||
return api_error(request, code="round_config_missing", status=400)
|
||||
|
||||
lie_deadline_at = round_question.shown_at + timedelta(seconds=round_config.lie_seconds)
|
||||
if timezone.now() > lie_deadline_at:
|
||||
return JsonResponse({"error": "Lie submission window has closed"}, status=400)
|
||||
return api_error(request, code="lie_submission_closed", status=400)
|
||||
|
||||
try:
|
||||
lie = LieAnswer.objects.create(round_question=round_question, player=player, text=lie_text)
|
||||
except IntegrityError:
|
||||
return JsonResponse({"error": "Lie already submitted for this player"}, status=409)
|
||||
return api_error(request, code="lie_already_submitted", status=409)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
@@ -510,21 +534,21 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
code="session_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_mix_answers", "host_only_mix_answers"),
|
||||
code="host_only_mix_answers",
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
code="mix_answers_invalid_phase",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -537,7 +561,7 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_question_not_found", "round_question_not_found"),
|
||||
code="round_question_not_found",
|
||||
status=404,
|
||||
)
|
||||
|
||||
@@ -546,7 +570,7 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
if locked_session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
code="mix_answers_invalid_phase",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -566,7 +590,7 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
if len(deduped_answers) < 2:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("not_enough_answers_to_mix", "not_enough_answers_to_mix"),
|
||||
code="not_enough_answers_to_mix",
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -578,6 +602,22 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
locked_session.status = GameSession.Status.GUESS
|
||||
locked_session.save(update_fields=["status"])
|
||||
|
||||
try:
|
||||
_guess_config = RoundConfig.objects.get(session=session, number=session.current_round)
|
||||
_guess_seconds = _guess_config.guess_seconds
|
||||
except RoundConfig.DoesNotExist:
|
||||
_guess_seconds = None
|
||||
|
||||
sync_broadcast_phase_event(
|
||||
session.code,
|
||||
"phase.guess_started",
|
||||
{
|
||||
"round_question_id": round_question.id,
|
||||
"answers": [{"text": t} for t in deduped_answers],
|
||||
"guess_seconds": _guess_seconds,
|
||||
},
|
||||
)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"session": {
|
||||
@@ -604,29 +644,29 @@ def submit_guess(request: HttpRequest, code: str, round_question_id: int) -> Jso
|
||||
selected_text = str(payload.get("selected_text", "")).strip()
|
||||
|
||||
if not player_id:
|
||||
return JsonResponse({"error": "player_id is required"}, status=400)
|
||||
return api_error(request, code="player_id_required", status=400)
|
||||
|
||||
if not session_token:
|
||||
return JsonResponse({"error": "session_token is required"}, status=400)
|
||||
return api_error(request, code="session_token_required", status=400)
|
||||
|
||||
if not selected_text or len(selected_text) > 255:
|
||||
return JsonResponse({"error": "selected_text must be between 1 and 255 characters"}, status=400)
|
||||
return api_error(request, code="selected_text_invalid", status=400)
|
||||
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.status != GameSession.Status.GUESS:
|
||||
return JsonResponse({"error": "Guess submission is only allowed in guess phase"}, status=400)
|
||||
return api_error(request, code="guess_submission_invalid_phase", status=400)
|
||||
|
||||
try:
|
||||
player = Player.objects.get(pk=player_id, session=session)
|
||||
except Player.DoesNotExist:
|
||||
return JsonResponse({"error": "Player not found in session"}, status=404)
|
||||
return api_error(request, code="player_not_found_in_session", status=404)
|
||||
|
||||
if player.session_token != session_token:
|
||||
return JsonResponse({"error": "Invalid player session token"}, status=403)
|
||||
return api_error(request, code="invalid_player_session_token", status=403)
|
||||
|
||||
try:
|
||||
round_question = RoundQuestion.objects.get(
|
||||
@@ -635,18 +675,18 @@ def submit_guess(request: HttpRequest, code: str, round_question_id: int) -> Jso
|
||||
round_number=session.current_round,
|
||||
)
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return JsonResponse({"error": "Round question not found"}, status=404)
|
||||
return api_error(request, code="round_question_not_found", status=404)
|
||||
|
||||
try:
|
||||
round_config = RoundConfig.objects.get(session=session, number=round_question.round_number)
|
||||
except RoundConfig.DoesNotExist:
|
||||
return JsonResponse({"error": "Round config missing"}, status=400)
|
||||
return api_error(request, code="round_config_missing", status=400)
|
||||
|
||||
guess_deadline_at = round_question.shown_at + timedelta(
|
||||
seconds=round_config.lie_seconds + round_config.guess_seconds
|
||||
)
|
||||
if timezone.now() > guess_deadline_at:
|
||||
return JsonResponse({"error": "Guess submission window has closed"}, status=400)
|
||||
return api_error(request, code="guess_submission_closed", status=400)
|
||||
|
||||
allowed_answers = {
|
||||
round_question.correct_answer.strip().casefold(),
|
||||
@@ -659,7 +699,7 @@ def submit_guess(request: HttpRequest, code: str, round_question_id: int) -> Jso
|
||||
|
||||
selected_normalized = selected_text.casefold()
|
||||
if selected_normalized not in allowed_answers:
|
||||
return JsonResponse({"error": "Selected answer is not part of this round"}, status=400)
|
||||
return api_error(request, code="selected_answer_invalid", status=400)
|
||||
|
||||
correct_normalized = round_question.correct_answer.strip().casefold()
|
||||
fooled_player_id = None
|
||||
@@ -677,7 +717,7 @@ def submit_guess(request: HttpRequest, code: str, round_question_id: int) -> Jso
|
||||
fooled_player_id=fooled_player_id,
|
||||
)
|
||||
except IntegrityError:
|
||||
return JsonResponse({"error": "Guess already submitted for this player"}, status=409)
|
||||
return api_error(request, code="guess_already_submitted", status=409)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
@@ -708,33 +748,22 @@ def reveal_scoreboard(request: HttpRequest, code: str) -> JsonResponse:
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_view_scoreboard", "host_only_view_scoreboard"),
|
||||
status=403,
|
||||
)
|
||||
return api_error(request, code="host_only_view_scoreboard", status=403)
|
||||
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status not in {GameSession.Status.REVEAL, GameSession.Status.SCOREBOARD}:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("scoreboard_invalid_phase", "scoreboard_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
return api_error(request, code="scoreboard_invalid_phase", status=400)
|
||||
|
||||
promoted_to_scoreboard = locked_session.status == GameSession.Status.REVEAL
|
||||
if promoted_to_scoreboard:
|
||||
locked_session.status = GameSession.Status.SCOREBOARD
|
||||
locked_session.save(update_fields=["status"])
|
||||
|
||||
|
||||
leaderboard = list(
|
||||
Player.objects.filter(session=session)
|
||||
.order_by("-score", "nickname")
|
||||
@@ -748,6 +777,7 @@ def reveal_scoreboard(request: HttpRequest, code: str) -> JsonResponse:
|
||||
{"leaderboard": list(leaderboard), "current_round": locked_session.current_round},
|
||||
)
|
||||
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"session": {
|
||||
@@ -768,27 +798,16 @@ def start_next_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_start_next_round", "host_only_start_next_round"),
|
||||
status=403,
|
||||
)
|
||||
return api_error(request, code="host_only_start_next_round", status=403)
|
||||
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status != GameSession.Status.SCOREBOARD:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("next_round_invalid_phase", "next_round_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
return api_error(request, code="next_round_invalid_phase", status=400)
|
||||
|
||||
|
||||
locked_session.current_round += 1
|
||||
locked_session.status = GameSession.Status.LOBBY
|
||||
@@ -812,27 +831,16 @@ def finish_game(request: HttpRequest, code: str) -> JsonResponse:
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_finish_game", "host_only_finish_game"),
|
||||
status=403,
|
||||
)
|
||||
return api_error(request, code="host_only_finish_game", status=403)
|
||||
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status != GameSession.Status.SCOREBOARD:
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("finish_game_invalid_phase", "finish_game_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
return api_error(request, code="finish_game_invalid_phase", status=400)
|
||||
|
||||
|
||||
locked_session.status = GameSession.Status.FINISHED
|
||||
locked_session.save(update_fields=["status"])
|
||||
@@ -845,6 +853,12 @@ def finish_game(request: HttpRequest, code: str) -> JsonResponse:
|
||||
|
||||
winner = leaderboard[0] if leaderboard else None
|
||||
|
||||
sync_broadcast_phase_event(
|
||||
session.code,
|
||||
"phase.game_over",
|
||||
{"winner": winner, "leaderboard": list(leaderboard)},
|
||||
)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"session": {
|
||||
@@ -866,20 +880,20 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(request, code="session_not_found", status=404)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can calculate scores"}, status=403)
|
||||
return api_error(request, code="host_only_calculate_scores", status=403)
|
||||
|
||||
already_calculated = ScoreEvent.objects.filter(
|
||||
session=session,
|
||||
meta__round_question_id=round_question_id,
|
||||
).exists()
|
||||
if already_calculated:
|
||||
return JsonResponse({"error": "Scores already calculated for this round question"}, status=409)
|
||||
return api_error(request, code="scores_already_calculated", status=409)
|
||||
|
||||
if session.status != GameSession.Status.GUESS:
|
||||
return JsonResponse({"error": "Scores can only be calculated in guess phase"}, status=400)
|
||||
return api_error(request, code="calculate_scores_invalid_phase", status=400)
|
||||
|
||||
try:
|
||||
round_question = RoundQuestion.objects.get(
|
||||
@@ -888,16 +902,16 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
round_number=session.current_round,
|
||||
)
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return JsonResponse({"error": "Round question not found"}, status=404)
|
||||
return api_error(request, code="round_question_not_found", status=404)
|
||||
|
||||
try:
|
||||
round_config = RoundConfig.objects.get(session=session, number=round_question.round_number)
|
||||
except RoundConfig.DoesNotExist:
|
||||
return JsonResponse({"error": "Round config missing"}, status=400)
|
||||
return api_error(request, code="round_config_missing", status=400)
|
||||
|
||||
guesses = list(round_question.guesses.select_related("player"))
|
||||
if not guesses:
|
||||
return JsonResponse({"error": "No guesses submitted for this round question"}, status=400)
|
||||
return api_error(request, code="no_guesses_submitted", status=400)
|
||||
|
||||
bluff_counts = {}
|
||||
for guess in guesses:
|
||||
@@ -907,7 +921,7 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status != GameSession.Status.GUESS:
|
||||
return JsonResponse({"error": "Scores can only be calculated in guess phase"}, status=400)
|
||||
return api_error(request, code="calculate_scores_invalid_phase", status=400)
|
||||
|
||||
score_events = []
|
||||
|
||||
@@ -951,6 +965,21 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
.values("id", "nickname", "score")
|
||||
)
|
||||
|
||||
score_deltas = [
|
||||
{"player_id": ev.player_id, "delta": ev.delta, "reason": ev.reason}
|
||||
for ev in score_events
|
||||
]
|
||||
|
||||
sync_broadcast_phase_event(
|
||||
session.code,
|
||||
"phase.scores_calculated",
|
||||
{
|
||||
"round_question_id": round_question.id,
|
||||
"score_deltas": score_deltas,
|
||||
"leaderboard": list(leaderboard),
|
||||
},
|
||||
)
|
||||
|
||||
return JsonResponse(
|
||||
{
|
||||
"session": {
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import os
|
||||
from channels.routing import ProtocolTypeRouter
|
||||
|
||||
from channels.routing import ProtocolTypeRouter, URLRouter
|
||||
from django.core.asgi import get_asgi_application
|
||||
|
||||
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'partyhub.settings')
|
||||
|
||||
django_asgi_app = get_asgi_application()
|
||||
|
||||
from realtime.routing import websocket_urlpatterns # noqa: E402 — must come after env setup
|
||||
|
||||
application = ProtocolTypeRouter({
|
||||
'http': django_asgi_app,
|
||||
'websocket': URLRouter(websocket_urlpatterns),
|
||||
})
|
||||
|
||||
@@ -116,8 +116,13 @@ WPP_SPA_ASSET_VERSION = env('WPP_SPA_ASSET_VERSION', 'dev')
|
||||
|
||||
CHANNEL_REDIS_HOST = env('CHANNEL_REDIS_HOST', '127.0.0.1')
|
||||
CHANNEL_REDIS_PORT = int(env('CHANNEL_REDIS_PORT', '6379'))
|
||||
|
||||
import sys # noqa: E402
|
||||
_testing = 'test' in sys.argv
|
||||
CHANNEL_LAYERS = {
|
||||
'default': {
|
||||
'BACKEND': 'channels.layers.InMemoryChannelLayer',
|
||||
} if _testing else {
|
||||
'BACKEND': 'channels_redis.core.RedisChannelLayer',
|
||||
'CONFIG': {'hosts': [(CHANNEL_REDIS_HOST, CHANNEL_REDIS_PORT)]},
|
||||
}
|
||||
|
||||
@@ -1,26 +1,26 @@
|
||||
from asgiref.sync import async_to_sync
|
||||
from channels.exceptions import InvalidChannelLayerError
|
||||
from channels.layers import get_channel_layer
|
||||
from redis.exceptions import ConnectionError as RedisConnectionError
|
||||
|
||||
try:
|
||||
from redis.exceptions import ConnectionError as RedisConnectionError
|
||||
except Exception: # pragma: no cover - optional dependency in local/test runtimes
|
||||
RedisConnectionError = RuntimeError
|
||||
|
||||
|
||||
async def broadcast_phase_event(session_code: str, event_type: str, payload: dict) -> None:
|
||||
"""Send a phase event to all WebSocket clients connected to a game session."""
|
||||
try:
|
||||
channel_layer = get_channel_layer()
|
||||
except InvalidChannelLayerError:
|
||||
return
|
||||
|
||||
if channel_layer is None:
|
||||
return
|
||||
|
||||
group_name = f"game_{session_code.upper()}"
|
||||
try:
|
||||
await channel_layer.group_send(
|
||||
group_name,
|
||||
{
|
||||
"type": "phase_event",
|
||||
"payload": {"type": event_type, **payload},
|
||||
"type": "phase.event",
|
||||
"event_type": event_type,
|
||||
"payload": payload,
|
||||
},
|
||||
)
|
||||
except (InvalidChannelLayerError, RedisConnectionError):
|
||||
|
||||
61
realtime/consumers.py
Normal file
61
realtime/consumers.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import json
|
||||
from urllib.parse import parse_qs
|
||||
|
||||
from channels.generic.websocket import AsyncJsonWebsocketConsumer
|
||||
|
||||
from fupogfakta.models import Player
|
||||
|
||||
|
||||
class GameConsumer(AsyncJsonWebsocketConsumer):
|
||||
"""
|
||||
WebSocket consumer for a game session.
|
||||
|
||||
URL: ws/game/<session_code>/
|
||||
|
||||
Query params:
|
||||
- session_token: player session token (players only)
|
||||
- role=host: skip token check for host in MVP
|
||||
"""
|
||||
|
||||
async def connect(self):
|
||||
self.session_code = self.scope["url_route"]["kwargs"]["session_code"].upper()
|
||||
self.group_name = f"game_{self.session_code}"
|
||||
|
||||
query_string = self.scope.get("query_string", b"").decode()
|
||||
params = parse_qs(query_string)
|
||||
|
||||
role = params.get("role", [None])[0]
|
||||
session_token = params.get("session_token", [None])[0]
|
||||
|
||||
if role != "host":
|
||||
if not session_token:
|
||||
await self.close(code=4001)
|
||||
return
|
||||
|
||||
try:
|
||||
self.player = await Player.objects.aget(
|
||||
session_token=session_token,
|
||||
session__code=self.session_code,
|
||||
)
|
||||
except Player.DoesNotExist:
|
||||
await self.close(code=4003)
|
||||
return
|
||||
else:
|
||||
self.player = None
|
||||
|
||||
await self.channel_layer.group_add(self.group_name, self.channel_name)
|
||||
await self.accept()
|
||||
|
||||
async def disconnect(self, close_code):
|
||||
if hasattr(self, "group_name"):
|
||||
await self.channel_layer.group_discard(self.group_name, self.channel_name)
|
||||
|
||||
async def receive_json(self, content, **kwargs):
|
||||
if content.get("type") == "ping":
|
||||
await self.send_json({"type": "pong"})
|
||||
|
||||
# --- Group message handlers ---
|
||||
|
||||
async def phase_event(self, event):
|
||||
"""Forward any phase_event broadcast to the WebSocket client."""
|
||||
await self.send_json(event["payload"])
|
||||
7
realtime/routing.py
Normal file
7
realtime/routing.py
Normal file
@@ -0,0 +1,7 @@
|
||||
from django.urls import re_path
|
||||
|
||||
from . import consumers
|
||||
|
||||
websocket_urlpatterns = [
|
||||
re_path(r"^ws/game/(?P<session_code>[A-Z0-9]{4,8})/$", consumers.GameConsumer.as_asgi()),
|
||||
]
|
||||
@@ -1,10 +1,21 @@
|
||||
import unittest
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from channels.exceptions import InvalidChannelLayerError
|
||||
from django.test import SimpleTestCase
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.test import SimpleTestCase, TestCase
|
||||
|
||||
try:
|
||||
from channels.testing import WebsocketCommunicator
|
||||
except Exception: # pragma: no cover - optional test dependency
|
||||
WebsocketCommunicator = None
|
||||
|
||||
from fupogfakta.models import GameSession, Player
|
||||
from partyhub.asgi import application
|
||||
from realtime.broadcast import broadcast_phase_event, sync_broadcast_phase_event
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
|
||||
class BroadcastPhaseEventTests(SimpleTestCase):
|
||||
@patch("realtime.broadcast.get_channel_layer", return_value=None)
|
||||
@@ -25,3 +36,67 @@ class BroadcastPhaseEventTests(SimpleTestCase):
|
||||
sync_broadcast_phase_event("ABCD", "phase.scoreboard", {"phase": "scoreboard"})
|
||||
|
||||
sender.assert_called_once_with("ABCD", "phase.scoreboard", {"phase": "scoreboard"})
|
||||
|
||||
|
||||
@unittest.skipIf(WebsocketCommunicator is None, "channels.testing dependencies unavailable")
|
||||
class GameConsumerConnectTest(TestCase):
|
||||
def setUp(self):
|
||||
self.user = User.objects.create_user(username="host", password="pw")
|
||||
self.session = GameSession.objects.create(host=self.user, code="AABBCC")
|
||||
self.player = Player.objects.create(session=self.session, nickname="Tester")
|
||||
|
||||
async def test_player_connect_and_ping(self):
|
||||
token = self.player.session_token
|
||||
communicator = WebsocketCommunicator(
|
||||
application,
|
||||
f"/ws/game/AABBCC/?session_token={token}",
|
||||
)
|
||||
connected, _ = await communicator.connect()
|
||||
self.assertTrue(connected)
|
||||
|
||||
await communicator.send_json_to({"type": "ping"})
|
||||
response = await communicator.receive_json_from()
|
||||
self.assertEqual(response["type"], "pong")
|
||||
|
||||
await communicator.disconnect()
|
||||
|
||||
async def test_connect_without_token_rejected(self):
|
||||
communicator = WebsocketCommunicator(application, "/ws/game/AABBCC/")
|
||||
connected, code = await communicator.connect()
|
||||
self.assertFalse(connected)
|
||||
self.assertEqual(code, 4001)
|
||||
|
||||
async def test_connect_invalid_token_rejected(self):
|
||||
communicator = WebsocketCommunicator(
|
||||
application,
|
||||
"/ws/game/AABBCC/?session_token=invalid-token",
|
||||
)
|
||||
connected, code = await communicator.connect()
|
||||
self.assertFalse(connected)
|
||||
self.assertEqual(code, 4003)
|
||||
|
||||
async def test_host_connect_without_token(self):
|
||||
communicator = WebsocketCommunicator(
|
||||
application,
|
||||
"/ws/game/AABBCC/?role=host",
|
||||
)
|
||||
connected, _ = await communicator.connect()
|
||||
self.assertTrue(connected)
|
||||
await communicator.disconnect()
|
||||
|
||||
async def test_broadcast_reaches_connected_client(self):
|
||||
token = self.player.session_token
|
||||
communicator = WebsocketCommunicator(
|
||||
application,
|
||||
f"/ws/game/AABBCC/?session_token={token}",
|
||||
)
|
||||
connected, _ = await communicator.connect()
|
||||
self.assertTrue(connected)
|
||||
|
||||
await broadcast_phase_event("AABBCC", "phase.test_event", {"hello": "world"})
|
||||
|
||||
message = await communicator.receive_json_from(timeout=2)
|
||||
self.assertEqual(message["type"], "phase.test_event")
|
||||
self.assertEqual(message["hello"], "world")
|
||||
|
||||
await communicator.disconnect()
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
Django==6.0.2
|
||||
channels>=4.1,<5
|
||||
channels-redis>=4.2,<5
|
||||
daphne>=4.1,<5
|
||||
mysqlclient>=2.2,<3
|
||||
python-dotenv>=1.0,<2
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"locales": ["en", "da"],
|
||||
"locales": [
|
||||
"en",
|
||||
"da"
|
||||
],
|
||||
"frontend_error_keys": [
|
||||
"join_failed",
|
||||
"nickname_invalid",
|
||||
@@ -11,50 +14,96 @@
|
||||
"unknown"
|
||||
],
|
||||
"backend_error_codes": [
|
||||
"calculate_scores_invalid_phase",
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"finish_game_invalid_phase",
|
||||
"guess_already_submitted",
|
||||
"guess_submission_closed",
|
||||
"guess_submission_invalid_phase",
|
||||
"host_only_calculate_scores",
|
||||
"host_only_finish_game",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_next_round",
|
||||
"host_only_start_round",
|
||||
"host_only_view_scoreboard",
|
||||
"invalid_player_session_token",
|
||||
"lie_already_submitted",
|
||||
"lie_submission_closed",
|
||||
"lie_submission_invalid_phase",
|
||||
"lie_text_invalid",
|
||||
"mix_answers_invalid_phase",
|
||||
"next_round_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"no_guesses_submitted",
|
||||
"not_enough_answers_to_mix",
|
||||
"player_id_required",
|
||||
"player_not_found_in_session",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"scoreboard_invalid_phase",
|
||||
"scores_already_calculated",
|
||||
"selected_answer_invalid",
|
||||
"selected_text_invalid",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"session_token_required",
|
||||
"show_question_invalid_phase"
|
||||
],
|
||||
"allowed_contract_only_backend_codes": [
|
||||
"host_only_action"
|
||||
],
|
||||
"backend_error_keys": [
|
||||
"calculate_scores_invalid_phase",
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"finish_game_invalid_phase",
|
||||
"guess_already_submitted",
|
||||
"guess_submission_closed",
|
||||
"guess_submission_invalid_phase",
|
||||
"host_only_calculate_scores",
|
||||
"host_only_finish_game",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_next_round",
|
||||
"host_only_start_round",
|
||||
"host_only_view_scoreboard",
|
||||
"invalid_player_session_token",
|
||||
"lie_already_submitted",
|
||||
"lie_submission_closed",
|
||||
"lie_submission_invalid_phase",
|
||||
"lie_text_invalid",
|
||||
"mix_answers_invalid_phase",
|
||||
"next_round_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"no_guesses_submitted",
|
||||
"not_enough_answers_to_mix",
|
||||
"player_id_required",
|
||||
"player_not_found_in_session",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"scoreboard_invalid_phase",
|
||||
"scores_already_calculated",
|
||||
"selected_answer_invalid",
|
||||
"selected_text_invalid",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"session_token_required",
|
||||
"show_question_invalid_phase"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -39,18 +39,6 @@
|
||||
"unknown": {
|
||||
"en": "Action failed. Refresh status and try again.",
|
||||
"da": "Handlingen fejlede. Opdater status og prøv igen."
|
||||
},
|
||||
"scoreboard_failed": {
|
||||
"en": "Could not load scoreboard. Refresh the session and try again.",
|
||||
"da": "Kunne ikke indlæse scoreboardet. Opdater sessionen og prøv igen."
|
||||
},
|
||||
"next_round_failed": {
|
||||
"en": "Could not start next round. Refresh the session and try again.",
|
||||
"da": "Kunne ikke starte næste runde. Opdater sessionen og prøv igen."
|
||||
},
|
||||
"finish_game_failed": {
|
||||
"en": "Could not finish game. Refresh the session and try again.",
|
||||
"da": "Kunne ikke afslutte spillet. Opdater sessionen og prøv igen."
|
||||
}
|
||||
},
|
||||
"ui": {
|
||||
@@ -309,12 +297,29 @@
|
||||
"host_only_start_round": "host_only_start_round",
|
||||
"host_only_show_question": "host_only_show_question",
|
||||
"host_only_mix_answers": "host_only_mix_answers",
|
||||
"player_id_required": "player_id_required",
|
||||
"session_token_required": "session_token_required",
|
||||
"lie_text_invalid": "lie_text_invalid",
|
||||
"player_not_found_in_session": "player_not_found_in_session",
|
||||
"invalid_player_session_token": "invalid_player_session_token",
|
||||
"lie_submission_closed": "lie_submission_closed",
|
||||
"lie_already_submitted": "lie_already_submitted",
|
||||
"host_only_view_scoreboard": "host_only_view_scoreboard",
|
||||
"scoreboard_invalid_phase": "scoreboard_invalid_phase",
|
||||
"host_only_start_next_round": "host_only_start_next_round",
|
||||
"next_round_invalid_phase": "next_round_invalid_phase",
|
||||
"host_only_finish_game": "host_only_finish_game",
|
||||
"finish_game_invalid_phase": "finish_game_invalid_phase"
|
||||
"finish_game_invalid_phase": "finish_game_invalid_phase",
|
||||
"host_only_calculate_scores": "host_only_calculate_scores",
|
||||
"scores_already_calculated": "scores_already_calculated",
|
||||
"calculate_scores_invalid_phase": "calculate_scores_invalid_phase",
|
||||
"no_guesses_submitted": "no_guesses_submitted",
|
||||
"guess_submission_closed": "guess_submission_closed",
|
||||
"selected_answer_invalid": "selected_answer_invalid",
|
||||
"guess_already_submitted": "guess_already_submitted",
|
||||
"lie_submission_invalid_phase": "lie_submission_invalid_phase",
|
||||
"selected_text_invalid": "selected_text_invalid",
|
||||
"guess_submission_invalid_phase": "guess_submission_invalid_phase"
|
||||
},
|
||||
"errors": {
|
||||
"session_code_required": {
|
||||
@@ -397,9 +402,37 @@
|
||||
"en": "Only host can mix answers",
|
||||
"da": "Kun værten kan blande svar"
|
||||
},
|
||||
"player_id_required": {
|
||||
"en": "player_id is required",
|
||||
"da": "player_id er påkrævet"
|
||||
},
|
||||
"session_token_required": {
|
||||
"en": "session_token is required",
|
||||
"da": "session_token er påkrævet"
|
||||
},
|
||||
"lie_text_invalid": {
|
||||
"en": "text must be between 1 and 255 characters",
|
||||
"da": "text skal være mellem 1 og 255 tegn"
|
||||
},
|
||||
"player_not_found_in_session": {
|
||||
"en": "Player not found in session",
|
||||
"da": "Spiller blev ikke fundet i sessionen"
|
||||
},
|
||||
"invalid_player_session_token": {
|
||||
"en": "Invalid player session token",
|
||||
"da": "Ugyldigt spiller-session-token"
|
||||
},
|
||||
"lie_submission_closed": {
|
||||
"en": "Lie submission window has closed",
|
||||
"da": "Vinduet for løgn-indsendelse er lukket"
|
||||
},
|
||||
"lie_already_submitted": {
|
||||
"en": "Lie already submitted for this player",
|
||||
"da": "Løgnen er allerede indsendt for denne spiller"
|
||||
},
|
||||
"host_only_view_scoreboard": {
|
||||
"en": "Only host can view scoreboard",
|
||||
"da": "Kun værten kan se scoreboardet"
|
||||
"da": "Kun værten kan se scoreboard"
|
||||
},
|
||||
"scoreboard_invalid_phase": {
|
||||
"en": "Scoreboard is only available in reveal/scoreboard phase",
|
||||
@@ -420,6 +453,46 @@
|
||||
"finish_game_invalid_phase": {
|
||||
"en": "Game can only be finished from scoreboard phase",
|
||||
"da": "Spillet kan kun afsluttes fra scoreboard-fasen"
|
||||
},
|
||||
"host_only_calculate_scores": {
|
||||
"en": "Only host can calculate scores",
|
||||
"da": "Kun værten kan udregne score"
|
||||
},
|
||||
"scores_already_calculated": {
|
||||
"en": "Scores already calculated for this round question",
|
||||
"da": "Score er allerede udregnet for dette rundespørgsmål"
|
||||
},
|
||||
"calculate_scores_invalid_phase": {
|
||||
"en": "Scores can only be calculated in guess phase",
|
||||
"da": "Score kan kun udregnes i gættefasen"
|
||||
},
|
||||
"no_guesses_submitted": {
|
||||
"en": "No guesses submitted for this round question",
|
||||
"da": "Ingen gæt er indsendt for dette rundespørgsmål"
|
||||
},
|
||||
"guess_submission_closed": {
|
||||
"en": "Guess submission window has closed",
|
||||
"da": "Vinduet for gæt-indsendelse er lukket"
|
||||
},
|
||||
"selected_answer_invalid": {
|
||||
"en": "Selected answer is not part of this round",
|
||||
"da": "Det valgte svar er ikke en del af denne runde"
|
||||
},
|
||||
"guess_already_submitted": {
|
||||
"en": "Guess already submitted for this player",
|
||||
"da": "Gættet er allerede indsendt for denne spiller"
|
||||
},
|
||||
"lie_submission_invalid_phase": {
|
||||
"en": "Lie submission is only allowed in lie phase",
|
||||
"da": "Løgn kan kun indsendes i løgnefasen"
|
||||
},
|
||||
"selected_text_invalid": {
|
||||
"en": "selected_text must be between 1 and 255 characters",
|
||||
"da": "selected_text skal være mellem 1 og 255 tegn"
|
||||
},
|
||||
"guess_submission_invalid_phase": {
|
||||
"en": "Guess submission is only allowed in guess phase",
|
||||
"da": "Gæt kan kun indsendes i gættefasen"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -459,12 +532,29 @@
|
||||
"mix_answers_invalid_phase": "start_round_failed",
|
||||
"round_question_not_found": "start_round_failed",
|
||||
"not_enough_answers_to_mix": "start_round_failed",
|
||||
"host_only_view_scoreboard": "scoreboard_failed",
|
||||
"scoreboard_invalid_phase": "scoreboard_failed",
|
||||
"host_only_start_next_round": "next_round_failed",
|
||||
"next_round_invalid_phase": "next_round_failed",
|
||||
"host_only_finish_game": "finish_game_failed",
|
||||
"finish_game_invalid_phase": "finish_game_failed"
|
||||
"player_id_required": "unknown",
|
||||
"session_token_required": "unknown",
|
||||
"lie_text_invalid": "unknown",
|
||||
"lie_submission_invalid_phase": "unknown",
|
||||
"player_not_found_in_session": "unknown",
|
||||
"invalid_player_session_token": "unknown",
|
||||
"lie_submission_closed": "unknown",
|
||||
"lie_already_submitted": "unknown",
|
||||
"selected_text_invalid": "unknown",
|
||||
"guess_submission_invalid_phase": "unknown",
|
||||
"guess_submission_closed": "unknown",
|
||||
"selected_answer_invalid": "unknown",
|
||||
"guess_already_submitted": "unknown",
|
||||
"host_only_view_scoreboard": "unknown",
|
||||
"scoreboard_invalid_phase": "unknown",
|
||||
"host_only_start_next_round": "unknown",
|
||||
"next_round_invalid_phase": "unknown",
|
||||
"host_only_finish_game": "unknown",
|
||||
"finish_game_invalid_phase": "unknown",
|
||||
"host_only_calculate_scores": "unknown",
|
||||
"scores_already_calculated": "unknown",
|
||||
"calculate_scores_invalid_phase": "unknown",
|
||||
"no_guesses_submitted": "unknown"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user