Compare commits
84 Commits
dev/issue-
...
dev/issue-
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c524d7d2d | |||
| f0ebc25da7 | |||
| b968ea4430 | |||
| 5a580964c4 | |||
| e0aba3fdf6 | |||
| c0c3ecd90c | |||
| b8a9fbf6d1 | |||
| 9594a8fcb0 | |||
| e4841afbaa | |||
| ee2a202f34 | |||
| f73b99b637 | |||
| 6d99741305 | |||
| cf58ba8067 | |||
| f7ed3d9407 | |||
| 951e24b57d | |||
| 63fce7760a | |||
| 8899bf547c | |||
| 0dad635311 | |||
| 7c7a6b6a08 | |||
| f87e0b60cf | |||
| aa2d636e90 | |||
| 9219648231 | |||
| 377fb712e1 | |||
| bb90295d26 | |||
| f9e1999e74 | |||
| 0c515ed2b7 | |||
| 0bb15f749b | |||
| 361f78b1c8 | |||
| 4d46611910 | |||
| ed72f9a824 | |||
| 3474d68c57 | |||
| 0bc4e6f066 | |||
| b18b05cc70 | |||
| ed57efb1b3 | |||
| 1faadbea4d | |||
| dc6af7547c | |||
| 1f98f01283 | |||
| a278934960 | |||
| c1391e8dc5 | |||
| 8d3df1f850 | |||
| 6838cc0efc | |||
| 9deae85a56 | |||
| 4b2b21fe57 | |||
| 5538a91800 | |||
| 79b694c590 | |||
| 87c1a0ee6c | |||
| c34a52e83e | |||
| edf9460ceb | |||
| a0a1424e90 | |||
| 60e58f6214 | |||
| a658ef5f80 | |||
| 258025ac4e | |||
| f28a390f95 | |||
| a1bb1ccbed | |||
| ee025e8deb | |||
| b977016ef4 | |||
| 1b899a30a2 | |||
| 187b26e561 | |||
| 0b4ddaf43f | |||
| 7a3d649e11 | |||
| f50f6a08ae | |||
| 000a486db1 | |||
| 845e94b726 | |||
| 5fe8f92ee4 | |||
| e2f184d1bc | |||
| ab41798220 | |||
| c7ff3d96de | |||
| 3398aead7f | |||
| 97945ede92 | |||
| 3655bad847 | |||
| fdef33f44a | |||
| bc78f79f78 | |||
| 784622058a | |||
| 257732e2ab | |||
| 64fe273691 | |||
| cd6fb06343 | |||
| 508d462bb6 | |||
| e435a41660 | |||
| b9bfe55f93 | |||
| 8e21ca8e5e | |||
| ddf8e874e2 | |||
| 21a25a063c | |||
| 4e300e4631 | |||
| 5fe9939057 |
1
TODO.md
1
TODO.md
@@ -107,6 +107,7 @@ Byg **Weirsøe Party Protocol**: en dansk party-webapp platform ala Jackbox, hvo
|
||||
- [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.
|
||||
- [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
|
||||
- [ ] (Need-to-have) Audit-log for host-handlinger (start/stop/skip)
|
||||
|
||||
@@ -9,7 +9,7 @@ Issue #175 requires one shared i18n contract for MVP host/player flows across fr
|
||||
- supported: `en`, `da`
|
||||
- default/fallback: `en`
|
||||
|
||||
Both Angular (`frontend/angular/src/app/lobby-i18n.ts`) and Django (`lobby/i18n.py`) read from this catalog.
|
||||
Django (`lobby/i18n.py`) reads directly from the catalog. Frontend runtimes are Angular-first and use a shared loader (`frontend/shared/i18n/lobby-loader.ts`) so Angular shell and SPA fallback consume the same keyspace + locale normalization.
|
||||
|
||||
## Key naming convention
|
||||
- Domain-first namespaces:
|
||||
@@ -46,3 +46,4 @@ Both Angular (`frontend/angular/src/app/lobby-i18n.ts`) and Django (`lobby/i18n.
|
||||
- `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts`
|
||||
- `frontend/angular/src/app/features/host/host-shell.component.spec.ts`
|
||||
- `frontend/angular/src/app/features/player/player-shell.component.spec.ts`
|
||||
- `frontend/tests/lobby-loader.parity.test.ts` (minimal da/en key parity guard for shared keyspace)
|
||||
|
||||
20
docs/ISSUE-223-PLAYER-AUDIO-GUARD-ARTIFACT.md
Normal file
20
docs/ISSUE-223-PLAYER-AUDIO-GUARD-ARTIFACT.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Issue #223 — Telefon-klient audio guard (artifact)
|
||||
|
||||
## Scope leveret
|
||||
- Telefon-/player-klient installerer en eksplicit audio guard ved mount (`installSecondaryDeviceAudioGuard`).
|
||||
- Guard overskriver `HTMLMediaElement.prototype.play` til en no-op på secondary device (client policy: `client_has_no_audio_output=true`).
|
||||
- Guard fjernes igen ved unmount (`ngOnDestroy`) så øvrige flows/enheder ikke påvirkes.
|
||||
- Ingen audio-controls er eksponeret i player-shell UI.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **Telefon-klient trigger ikke audio playback i kerneflow**
|
||||
- Verificeret af test: `player-shell.component.spec.ts` (`installs secondary-device audio guard while player shell is mounted`).
|
||||
2. **Primær enhed påvirkes ikke negativt**
|
||||
- Guard er scoped til player-shell lifecycle og restore'r original `play` ved destroy.
|
||||
3. **Enkel test/verifikation dokumenteret**
|
||||
- Dokumenteret her + testkørsel nedenfor.
|
||||
|
||||
## Testkørsel
|
||||
- Kommando:
|
||||
- `cd frontend/angular && npm test -- src/app/features/player/player-shell.component.spec.ts`
|
||||
- Resultat: bestået (inkl. audio-guard test).
|
||||
55
docs/ISSUE-224-TRUNK-SEQUENCE-175.md
Normal file
55
docs/ISSUE-224-TRUNK-SEQUENCE-175.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Issue #224 — Trunk-sekvens for #175 (A/B/C)
|
||||
|
||||
Formål: gøre #175 scheduler-klar som tre små, uafhængige og mergeklare bidder.
|
||||
|
||||
## Sekvens
|
||||
|
||||
### A) Backend i18n baseline
|
||||
- Tracking issue: #225
|
||||
- Scope:
|
||||
- Backend resolver til locale (da/en)
|
||||
- Fallback til `en` ved unsupported locale
|
||||
- Stabil fejlkontrakt i payload (`error_code`, `error`, `locale`)
|
||||
- Mergebarhed: Kan merges uden frontend-ændringer.
|
||||
- Acceptance:
|
||||
- Backend tests dækker `da` + fallback `en`
|
||||
- Kontraktfelter er stabile i response
|
||||
|
||||
### B) Shared key-map + locale-kontrakt
|
||||
- Tracking issue: #226
|
||||
- Scope:
|
||||
- Én shared key-map for lobby/kerneflow
|
||||
- Locale-kontrakt (tilladte locales, default locale, fallback-regler)
|
||||
- Dokumentation af naming + ownership
|
||||
- Mergebarhed: Kan merges uden host/player UI-migrering.
|
||||
- Acceptance:
|
||||
- Shared kontrakt findes ét sted
|
||||
- Begge sider kan importere den
|
||||
- Docs opdateret med da/en eksempler
|
||||
|
||||
### C) Angular host/player integration + hardcoded-text cleanup
|
||||
- Tracking issue: #227
|
||||
- Scope:
|
||||
- Angular host/player kerneflow bruger shared keys
|
||||
- Hardcoded tekster fjernes i aftalte kernekomponenter
|
||||
- Sprogskift verificeres i kritiske states
|
||||
- Mergebarhed: Kan merges selvstændigt når frontend-tests er grønne.
|
||||
- Acceptance:
|
||||
- Korrekt i18n-copy i da/en i kerneflow
|
||||
- Ingen hardcoded kerneflow-tekster tilbage
|
||||
- Frontend tests/smoke grønne
|
||||
|
||||
## PR-grænser (per bid)
|
||||
- 1 PR pr. bid (A/B/C) mod `main`
|
||||
- Mål: ~200–300 net LOC per PR (ekskl. generated artefakter)
|
||||
- Undgå cross-layer scope creep
|
||||
- Review-tid <30 min
|
||||
|
||||
## Overordnet acceptance for #224
|
||||
- A/B/C-sekvens er tydelig med links
|
||||
- Hver bid er mergebar isoleret
|
||||
- Scheduler kan assign’e direkte uden ekstra afklaring
|
||||
|
||||
## Verification (docs-only)
|
||||
- Verificeret at dokumentet kun beskriver trunk-sekvensen for issue #224 og linker til #225/#226/#227.
|
||||
- Ingen runtime-kode ændret; der er derfor ikke kørt kode/tests i denne PR.
|
||||
44
docs/ISSUE-225-BACKEND-I18N-BASELINE-ARTIFACT.md
Normal file
44
docs/ISSUE-225-BACKEND-I18N-BASELINE-ARTIFACT.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# ISSUE-225 Artifact — Backend i18n baseline (resolver + fallback)
|
||||
|
||||
Issue: **#225** (`[MVP][READY] #175-A: Backend i18n baseline (resolver + fallback)`)
|
||||
|
||||
## Scope verified
|
||||
|
||||
- Backend locale resolver supports `da` + `en` and normalizes language tags.
|
||||
- Unsupported locale requests fall back to default locale (`en`).
|
||||
- Error payload contract is stable for API errors:
|
||||
- `error_code`
|
||||
- `error`
|
||||
- `locale`
|
||||
|
||||
## Implementation references
|
||||
|
||||
- Locale resolution + fallback chain:
|
||||
- `lobby/i18n.py`
|
||||
- `resolve_locale()`
|
||||
- `resolve_error_message()`
|
||||
- `api_error()`
|
||||
- Shared locale contract source:
|
||||
- `shared/i18n/lobby.json` (`locales.default=en`, supported includes `en`, `da`)
|
||||
|
||||
## Acceptance checks run
|
||||
|
||||
Command:
|
||||
|
||||
```bash
|
||||
.venv/bin/python manage.py test \
|
||||
lobby.tests.I18nResolverTests \
|
||||
lobby.tests.LobbyFlowTests \
|
||||
lobby.tests.StartRoundTests
|
||||
```
|
||||
|
||||
Result (2026-03-02):
|
||||
|
||||
- `Ran 28 tests in 24.781s — OK`
|
||||
- `System check identified no issues (0 silenced).`
|
||||
- Confirms resolver behavior for locale normalization + fallback and stable error payload fields across flow endpoints.
|
||||
|
||||
## Notes
|
||||
|
||||
- Existing merged follow-ups in `main` include Accept-Language parsing fixes for q-values and locale tag normalization.
|
||||
- This artifact documents the final baseline state and verification evidence for #225.
|
||||
30
docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md
Normal file
30
docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# ISSUE-226 — Shared key-map + locale-kontrakt (backend/frontend)
|
||||
|
||||
## Source of truth
|
||||
- Single shared artifact: `shared/i18n/lobby.json`
|
||||
- Ownership is documented under `contract.ownership` in the same artifact.
|
||||
|
||||
## Locale contract
|
||||
Defined under `contract.locale`:
|
||||
- default locale: `en`
|
||||
- supported locales: `en`, `da`
|
||||
- fallback rule: use default locale when requested locale is unsupported or a key translation is missing.
|
||||
|
||||
## Shared backend→frontend key-map
|
||||
Defined under `contract.backend_to_frontend_error_keys`.
|
||||
|
||||
Examples:
|
||||
- `session_not_found -> session_not_found`
|
||||
- `session_not_joinable -> join_failed`
|
||||
- `round_start_invalid_phase -> start_round_failed`
|
||||
|
||||
This allows backend error codes to remain stable while frontend copy keys stay UX-oriented.
|
||||
|
||||
## da/en example values
|
||||
From `shared/i18n/lobby.json`:
|
||||
- `frontend.errors.session_code_required.en = "Session code is required."`
|
||||
- `frontend.errors.session_code_required.da = "Sessionskoden er påkrævet."`
|
||||
|
||||
## Verification
|
||||
- Backend: `python manage.py test lobby.tests.I18nResolverTests`
|
||||
- Frontend: `npm test -- --run tests/lobby-i18n.contract.test.ts`
|
||||
16
docs/ISSUE-250-PRIMARY-DEVICE-AUDIO-POLICY-ARTIFACT.md
Normal file
16
docs/ISSUE-250-PRIMARY-DEVICE-AUDIO-POLICY-ARTIFACT.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Issue #250 Artifact — MVP guardrail (telefon-klient uden lydafspilning)
|
||||
|
||||
## Scope
|
||||
Implementeret guardrail for `primary-device only` audio policy i SPA player-flow.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **Telefon-klient flow indeholder ingen audio-play init-path**
|
||||
- Test: `player-shell.component.spec.ts` → `does not trigger original media play during player-shell init path`.
|
||||
2. **Primær enhed policy er dokumenteret og testbar**
|
||||
- Policy i contract: `shared/i18n/lobby.json` → `frontend.capabilities.client_has_no_audio_output=true`.
|
||||
- Testbar via eksisterende guard-tests + init-path test i player-shell specs.
|
||||
3. **Krav er refereret i SPA-plan/cutover-noter**
|
||||
- Dokumenteret i `docs/spa-cutover-flag.md` under *MVP audio policy guardrail (telefon-klient)*.
|
||||
|
||||
## UX/i18n note
|
||||
- Player shell viser advarselstekst via i18n key: `frontend.ui.player.audio_policy_notice`.
|
||||
124
docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md
Normal file
124
docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Issue #251 — Release-often lane for SPA MVP (3 micro-PR batches)
|
||||
|
||||
## Formål
|
||||
Bryde SPA MVP-arbejdet op i **3 merge-klare micro-PRs** med tydelige acceptance criteria,
|
||||
så vi kan levere værdi oftere, reducere review-risiko og holde `main` grøn.
|
||||
|
||||
## Scope (issue-bound)
|
||||
Denne plan dækker kun planlægning/acceptance for den kommende SPA MVP-lane.
|
||||
Implementering af de konkrete features sker i efterfølgende PRs.
|
||||
|
||||
## Hard acceptance criteria for issue #251
|
||||
- [x] Der findes en dokumenteret plan med præcis **3 batches**.
|
||||
- [x] Hver batch har:
|
||||
- [x] mål og afgrænsning
|
||||
- [x] konkrete leverancer (kodeområder)
|
||||
- [x] test/checks før merge
|
||||
- [x] rollback-note
|
||||
- [x] "ikke med i denne batch" for at undgå scope creep
|
||||
- [x] Batch-rækkefølgen er dependencies-sikker (batch B bygger på batch A, batch C på batch B).
|
||||
- [x] Hver batch kan merges/releaseres uafhængigt uden at blokere drift på `main`.
|
||||
- [x] Planen linker til konkrete dev-opgaver for lane-kørsel.
|
||||
|
||||
## Batch-plan (merge-klare micro-PRs)
|
||||
|
||||
### Batch A — SPA shell + routing baseline
|
||||
**Mål:** Et stabilt SPA-skelet med route-struktur og guard-basics.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/app.routes.ts` (host/player entry routes + fallback)
|
||||
- `frontend/angular/src/app/session-route-context.ts` (baseline route guards)
|
||||
- `frontend/angular/src/app/app.component.*` (shell-nav + route outlet wiring)
|
||||
- `lobby/templates/lobby/spa_shell.html` (kompatibel shell-entry ved SPA cutover)
|
||||
|
||||
**Done-kriterier**
|
||||
- Host- og player-entry routes kan åbnes uden runtime-fejl i samme SPA-shell.
|
||||
- Route guards afviser ugyldige parametre deterministisk (ingen hard crash).
|
||||
- `USE_SPA_UI=false` fortsætter med legacy-flow uden regression.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/app.routes.spec.ts src/app/session-route-context.spec.ts`
|
||||
- `cd frontend/angular && npm run build`
|
||||
- Manual smoke: `/lobby/ui/host` + `/lobby/ui/player` (både `USE_SPA_UI=false` og `true`).
|
||||
|
||||
**Rollback-note**
|
||||
- Sæt `USE_SPA_UI=false` og redeploy; verificér legacy routes svarer 200.
|
||||
|
||||
**Ikke med i batch A**
|
||||
- Fuld gameplay-state synkronisering.
|
||||
- Audio/polish og i18n finpudsning ud over baseline wiring.
|
||||
|
||||
---
|
||||
|
||||
### Batch B — Session-state + host/player sync MVP
|
||||
**Mål:** Korrekt synkronisering af session-state mellem host og spillerklient.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/features/host/host-shell.component.ts`
|
||||
- `frontend/angular/src/app/features/player/player-shell.component.ts`
|
||||
- `frontend/src/api/angular-client.ts` (MVP-kald for status/phase-overgange)
|
||||
|
||||
**Done-kriterier**
|
||||
- Host handlinger (`start`, `show`, `mix`, `score`, `next`, `finish`) afspejles hos player uden side-reload.
|
||||
- Session-phase transitions er deterministiske i happy-path (`lobby -> question -> score -> next/finish`).
|
||||
- Guardrails reducerer race-condition regressions ved hurtige phase-skift.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts`
|
||||
- `cd frontend && npm test -- --run tests/angular-api-client.test.ts`
|
||||
- Manual smoke: host action -> player phase sync indenfor forventet latenstid.
|
||||
|
||||
**Rollback-note**
|
||||
- Slå `USE_SPA_UI=false`, redeploy, og kør hurtig gameplay-smoke i legacy flow.
|
||||
|
||||
**Ikke med i batch B**
|
||||
- Avanceret UX-polish/animation.
|
||||
- Udvidet observability udenfor MVP-kritiske logs.
|
||||
|
||||
---
|
||||
|
||||
### Batch C — Lobby/join/start minimal flow + release readiness
|
||||
**Mål:** Gøre SPA MVP release-klar med fokus på stabilitet og driftssikkerhed omkring det minimale flow.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts` + relevante shell-tests
|
||||
- `docs/UI_SMOKE.md` + `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md`
|
||||
- `CHANGELOG.md` release-input for SPA MVP lane
|
||||
|
||||
**Done-kriterier**
|
||||
- End-to-end minimal flow (`lobby -> join -> start`) er dokumenteret PASS i SPA.
|
||||
- Fejl-/empty-/loading states for flowets kritiske skærme er verificeret.
|
||||
- Driftsteam kan udføre cutover + rollback uden tvetydighed.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/i18n-mvp-flow-smoke.spec.ts`
|
||||
- `python manage.py test lobby.tests.LobbyFlowTests`
|
||||
- Opdateret staging-smoke artifact med UTC tidsstempler og gate-resultat.
|
||||
|
||||
**Rollback-note**
|
||||
- Brug eksisterende playbook i `docs/spa-cutover-flag.md` (`USE_SPA_UI=false` + asset-version rollback).
|
||||
|
||||
**Ikke med i batch C**
|
||||
- Post-MVP featureudvidelser.
|
||||
- Større refactors uden direkte release-værdi.
|
||||
|
||||
## Rækkefølge og parallel-kørsel
|
||||
- **Dependency-rækkefølge:** A -> B -> C.
|
||||
- **Kan køres parallelt uden konflikt:**
|
||||
- Test-/doc-forberedelse til C kan startes parallelt med B (ingen blokering af runtime-kode), men merges først efter B.
|
||||
- Drift-smoke templates kan opdateres tidligt, så længe de ikke ændrer runtime-adfærd.
|
||||
- **Må ikke køre parallelt:**
|
||||
- Runtime routing/guard ændringer i A og session-sync logik i B på samme filer uden feature-flag koordinering.
|
||||
|
||||
## Konkret lane-opgavebinding (dev-opgaver)
|
||||
- Batch A PR: `feat/issue-251-batch-1-spa-shell-routing`
|
||||
- Batch B PR: `feat/issue-251-batch-2-session-sync`
|
||||
- Batch C PR: `feat/issue-251-batch-3-lobby-join-start-release-readiness`
|
||||
|
||||
Hver PR skal linke tilbage til issue #251 og inkludere test-evidence + rollback-check.
|
||||
|
||||
## Merge-gate for alle 3 batches
|
||||
- Små PRs (mål: reviewbar størrelse, helst < ~300 netto-linjer når muligt).
|
||||
- Grøn CI/checks før review-request.
|
||||
- Tydelig PR-beskrivelse med: scope, test evidence, out-of-scope.
|
||||
- Ingen skjulte sideeffekter på tværs af apps/domæner.
|
||||
@@ -0,0 +1,32 @@
|
||||
# ISSUE-257 Artifact — Shared i18n keyspace + frontend loader (da/en, Angular-first)
|
||||
|
||||
Issue: **#257** (`[MVP][READY] #175-B: Shared i18n keyspace + frontend loader`)
|
||||
|
||||
## Acceptance checklist
|
||||
|
||||
- [x] **Delt key-strategi dokumenteret (frontend/backend)**
|
||||
- Arkitektur/deling beskrevet i `docs/I18N_ARCHITECTURE.md`.
|
||||
- Shared contract + keyspace source of truth: `shared/i18n/lobby.json`.
|
||||
|
||||
- [x] **Frontend loader kan indlæse da+en med samme keyspace**
|
||||
- Shared loader: `frontend/shared/i18n/lobby-loader.ts`.
|
||||
- Angular-first integration via `frontend/angular/src/app/lobby-i18n.ts` (samme loader/samme keyspace).
|
||||
- Locale-normalisering inkluderer underscore/hyphen variants (`da_DK` → `da`).
|
||||
|
||||
- [x] **Minimal check for key-paritet da/en**
|
||||
- `collectLocaleParityIssues(...)` i shared loader.
|
||||
- Testet i `frontend/tests/lobby-loader.parity.test.ts`.
|
||||
|
||||
- [x] **Ingen API-kontraktbrud**
|
||||
- Contract-test: `frontend/tests/lobby-i18n.contract.test.ts`.
|
||||
- Drift-check mellem manifest og katalog: `scripts/check_i18n_drift.py`.
|
||||
|
||||
## Kørte checks
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
cd frontend && npm test -- --run tests/lobby-loader.parity.test.ts tests/lobby-i18n.contract.test.ts
|
||||
cd frontend/angular && npm test -- --run src/app/lobby-i18n.spec.ts src/app/i18n-mvp-flow-smoke.spec.ts
|
||||
```
|
||||
|
||||
Resultat: alle checks grønne.
|
||||
37
docs/ISSUE-257-SHARED-I18N-LOADER-ARTIFACT.md
Normal file
37
docs/ISSUE-257-SHARED-I18N-LOADER-ARTIFACT.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# ISSUE-257 Artifact — shared i18n keyspace + frontend loader (Angular-first)
|
||||
|
||||
Issue: **#257** (`[MVP][READY] #175-B: Shared i18n keyspace + frontend loader (da/en, Angular-first)`)
|
||||
|
||||
## Acceptance mapping
|
||||
|
||||
### 1) Delt key-strategi dokumenteret (frontend/backend)
|
||||
- Shared contract source: `shared/i18n/lobby.json`
|
||||
- Architecture doc: `docs/I18N_ARCHITECTURE.md`
|
||||
- Key-map/contract doc: `docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md`
|
||||
|
||||
### 2) Frontend loader kan indlæse da+en med samme keyspace
|
||||
- Shared loader: `frontend/shared/i18n/lobby-loader.ts`
|
||||
- Angular-first consumer path:
|
||||
- `frontend/src/spa/lobby-i18n.ts`
|
||||
- Angular shell/tests continue to consume same shared catalog through shared loader contract.
|
||||
|
||||
### 3) Minimal check for key-paritet da/en
|
||||
- Guard test: `frontend/tests/lobby-loader.parity.test.ts`
|
||||
- Contract test: `frontend/tests/lobby-i18n.contract.test.ts`
|
||||
|
||||
### 4) Ingen API-kontraktbrud
|
||||
- Frontend API contract smoke:
|
||||
- `frontend/angular/src/app/api-contract-smoke.spec.ts`
|
||||
- `frontend/tests/angular-api-client.test.ts`
|
||||
|
||||
## Verification run (this lane)
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm test -- --run tests/lobby-loader.parity.test.ts tests/lobby-i18n.contract.test.ts tests/angular-api-client.test.ts
|
||||
|
||||
cd ../frontend/angular
|
||||
npm test -- --run src/app/api-contract-smoke.spec.ts
|
||||
```
|
||||
|
||||
Result: PASS (all selected suites green).
|
||||
18
docs/ISSUE-260-PHONE-CLIENT-NO-AUDIO-GUARD-ARTIFACT.md
Normal file
18
docs/ISSUE-260-PHONE-CLIENT-NO-AUDIO-GUARD-ARTIFACT.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Issue #260 Artifact — Phone/client no-audio guard (primary-device only playback)
|
||||
|
||||
## Scope
|
||||
Added regression coverage for MVP audio policy to ensure phone/client flows never claim playback ownership, while primary-device playback stays unaffected.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **client/phone triggers no playback**
|
||||
- Existing test coverage retained in `player-shell.component.spec.ts`:
|
||||
- `does not trigger original media play during player-shell init path`
|
||||
- `installs secondary-device audio guard while player shell is mounted`
|
||||
2. **primary device playback unaffected**
|
||||
- New negative test in `player-shell.component.spec.ts`:
|
||||
- `keeps primary-device playback untouched when no-audio capability is disabled`
|
||||
3. **one negative test for phone audio**
|
||||
- Existing negative path preserved:
|
||||
- `does not trigger original media play during player-shell init path`
|
||||
4. **no backend contract changes**
|
||||
- Frontend test/docs-only scope; no backend contract files changed.
|
||||
80
docs/ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md
Normal file
80
docs/ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# ISSUE-277 Artifact — shared i18n registry parity report (Django ↔ Angular MVP)
|
||||
|
||||
Issue: **#277** (`[READY][#175][P3] Shared i18n registry artifact: backend/frontend keyspace parity report`)
|
||||
|
||||
## Artifact metadata
|
||||
|
||||
- `artifact_id`: `issue-277-shared-i18n-parity-report`
|
||||
- `artifact_version`: `1.0`
|
||||
- `catalog_source`: `shared/i18n/lobby.json`
|
||||
- `generator`: `scripts/report_i18n_parity.py`
|
||||
|
||||
## Naming/version rules (email-manager-inspired strategy)
|
||||
|
||||
- **Single canonical artifact per issue**: issue-bundne rapporter navngives `docs/ISSUE-<nr>-<slug>-ARTIFACT.md`.
|
||||
- **Stable artifact identity**: `artifact_id` ændres ikke ved tekstlige opdateringer i samme rapporttype; det er den faste reference i review/ops.
|
||||
- **Explicit artifact versioning**: `artifact_version` bumpes, når rapportlogik eller scope ændres, så drift/review kan se forskel på format- vs. dataændringer.
|
||||
- **Shared namespace first**: keys refereres med fulde navnerum (`frontend.ui.*`, `frontend.errors.*`, `backend.error_codes.*`, `backend.errors.*`) i stedet for lokale aliases i artefakter.
|
||||
- **Source-of-truth before consumers**: rapporten afledes fra `shared/i18n/lobby.json`; Django/Angular beskrives som consumers af samme registry og ikke som parallelle kontrakter.
|
||||
|
||||
## MVP-critical parity summary
|
||||
|
||||
- Frontend UI gameplay keys checked: **16** → `OK`
|
||||
- Frontend error keys checked: **7** → `OK`
|
||||
- Backend gameplay/error codes checked: **9** → `OK`
|
||||
- Distinct frontend error keys reached from backend MVP flow: **6** (`join_failed, nickname_invalid, nickname_taken, session_code_required, session_not_found, start_round_failed`)
|
||||
|
||||
Status: **Shared locale matrix is aligned (`en`, `da`) and backend→frontend error handling is contract-complete for MVP-critical flow.**
|
||||
|
||||
## Django ↔ Angular parity matrix (MVP-critical error contract)
|
||||
|
||||
| Backend code (`backend.error_codes.*`) | Django message key (`backend.errors.*`) | Angular key (`frontend.errors.*`) | Locales `en/da` | Parity note |
|
||||
|---|---|---|---|---|
|
||||
| `session_code_required` | `session_code_required` | `session_code_required` | `OK` | 1:1 |
|
||||
| `nickname_invalid` | `nickname_invalid` | `nickname_invalid` | `OK` | 1:1 |
|
||||
| `session_not_found` | `session_not_found` | `session_not_found` | `OK` | 1:1 |
|
||||
| `session_not_joinable` | `session_not_joinable` | `join_failed` | `OK` | mapped alias |
|
||||
| `nickname_taken` | `nickname_taken` | `nickname_taken` | `OK` | 1:1 |
|
||||
| `category_slug_required` | `category_slug_required` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `category_not_found` | `category_not_found` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `round_start_invalid_phase` | `round_start_invalid_phase` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `round_already_configured` | `round_already_configured` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
|
||||
## Scope notes
|
||||
|
||||
- **Django** consumes backend codes/messages directly from `shared/i18n/lobby.json` via `lobby/i18n.py`.
|
||||
- **Angular** consumes the same registry via `frontend/shared/i18n/lobby-loader.ts` and runtime helpers in `frontend/angular/src/app/lobby-i18n.ts`.
|
||||
- **Parity in MVP** is therefore strongest on the shared error contract and locale matrix; gameplay UI labels are frontend-owned but still live in the same registry.
|
||||
|
||||
## Verified MVP gameplay UI keyspace present in the shared registry
|
||||
|
||||
- `frontend.ui.host.title`
|
||||
- `frontend.ui.player.title`
|
||||
- `frontend.ui.common.session_code`
|
||||
- `frontend.ui.player.nickname`
|
||||
- `frontend.ui.player.join`
|
||||
- `frontend.ui.host.start_round`
|
||||
- `frontend.ui.host.show_question`
|
||||
- `frontend.ui.player.lie_label`
|
||||
- `frontend.ui.player.submit_lie`
|
||||
- `frontend.ui.player.submit_guess`
|
||||
- `frontend.ui.host.mix_answers`
|
||||
- `frontend.ui.host.calculate_scores`
|
||||
- `frontend.ui.host.load_scoreboard`
|
||||
- `frontend.ui.host.final_leaderboard`
|
||||
- `frontend.ui.player.final_leaderboard`
|
||||
- `frontend.ui.common.points_short`
|
||||
|
||||
## Concrete deviations / follow-up items
|
||||
|
||||
1. **Error granularity collapse remains intentional**: backend codes `category_slug_required, category_not_found, round_start_invalid_phase, round_already_configured` all map to `frontend.errors.start_round_failed`. Follow-up only if product wants case-specific Angular copy instead of one shared host failure message.
|
||||
2. **Frontend-only fallback copy is not mirrored in Django**: `frontend.errors.unknown` and `frontend.errors.session_fetch_failed` are Angular-side resilience keys, not backend contract keys. Follow-up if API responses should expose stable backend equivalents for these states.
|
||||
3. **Gameplay UI labels are registry-shared but not backend-rendered**: `frontend.ui.host.*`, `frontend.ui.player.*`, and `frontend.ui.common.*` are available in the shared artifact, but Django currently consumes only the backend error slice. Follow-up only if server-rendered views must guarantee the same UI label surface as Angular.
|
||||
|
||||
## Re-run
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
python3 scripts/report_i18n_parity.py
|
||||
python3 scripts/check_i18n_parity_artifact.py
|
||||
```
|
||||
34
docs/i18n-drift-check.md
Normal file
34
docs/i18n-drift-check.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# i18n key manifest + drift check
|
||||
|
||||
Issue: #240
|
||||
|
||||
This repo keeps shared lobby keyspaces in two files:
|
||||
|
||||
- Contract source: `shared/i18n/lobby.json`
|
||||
- Key manifest: `shared/i18n/key-manifest.json`
|
||||
|
||||
The manifest is intentionally small and explicit. It lists:
|
||||
|
||||
- Supported locales (`locales`)
|
||||
- Frontend error key set (`frontend_error_keys`)
|
||||
- Backend error code set (`backend_error_codes`)
|
||||
- Backend translation key set (`backend_error_keys`)
|
||||
- Optional contract-only aliases (`allowed_contract_only_backend_codes`)
|
||||
|
||||
## Local check
|
||||
|
||||
Run the read-only drift checker from repo root:
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
```
|
||||
|
||||
The script returns non-zero when it detects drift, including:
|
||||
|
||||
- key set mismatch between manifest and shared catalog
|
||||
- missing backend→frontend mapping coverage
|
||||
- mapping to unknown frontend keys
|
||||
- mappings for unknown backend codes
|
||||
- missing/empty locale translations (`en`/`da`)
|
||||
|
||||
No CI gating changes are included in this task; this is a local guardrail.
|
||||
69
docs/i18n-keymap.md
Normal file
69
docs/i18n-keymap.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# i18n key-map bootstrap (Angular host/player MVP)
|
||||
|
||||
Issue: #220
|
||||
Scope: Lobby → Join → Start round → Round → Reveal → Scoreboard
|
||||
Locales: `en`, `da`
|
||||
|
||||
This document is the gameplay key-namespace map for Angular host/player MVP.
|
||||
It maps existing text keys only (no feature expansion) and stays aligned with `shared/i18n/lobby.json`.
|
||||
|
||||
## Key families
|
||||
|
||||
- `host` — `frontend.ui.host.*` host-facing gameplay actions and status text.
|
||||
- `player` — `frontend.ui.player.*` player-facing gameplay actions and status text.
|
||||
- `system` — shared UI labels used across host/player views (implemented under `frontend.ui.common.*` in `shared/i18n/lobby.json`).
|
||||
- `errors` — user-facing error keys shown by frontend (`frontend.errors.*`) plus backend code → frontend key bridge via `backend.error_codes.*` / `contract.backend_to_frontend_error_keys.*`.
|
||||
|
||||
## Gameplay flow key map
|
||||
|
||||
| Flow step | Family | Key | en | da |
|
||||
|---|---|---|---|---|
|
||||
| Lobby | `host` | `host.title` | Host gameplay flow | Vært gameplay-flow |
|
||||
| Lobby | `player` | `player.title` | Player gameplay flow | Spiller gameplay-flow |
|
||||
| Lobby | `system` (`frontend.ui.common`) | `common.session_code` | Session code | Sessionskode |
|
||||
| Lobby | `player` | `player.nickname` | Nickname | Kaldenavn |
|
||||
| Join | `player` | `player.join` | Join | Join |
|
||||
| Start round | `host` | `host.start_round` | Start round | Start runde |
|
||||
| Round | `host` | `host.show_question` | Show question | Vis spørgsmål |
|
||||
| Round | `player` | `player.lie_label` | Lie | Løgn |
|
||||
| Round | `player` | `player.submit_lie` | Submit lie | Send løgn |
|
||||
| Round | `player` | `player.submit_guess` | Submit guess | Send gæt |
|
||||
| Reveal | `host` | `host.mix_answers` | Mix answers → guess | Bland svar → gæt |
|
||||
| Reveal | `host` | `host.calculate_scores` | Calculate scores → reveal | Udregn score → afslør |
|
||||
| Scoreboard | `host` | `host.load_scoreboard` | Load scoreboard | Hent scoreboard |
|
||||
| Scoreboard | `host` | `host.final_leaderboard` | Final leaderboard | Finale leaderboard |
|
||||
| Scoreboard | `player` | `player.final_leaderboard` | Final leaderboard | Finale leaderboard |
|
||||
| Scoreboard | `system` (`frontend.ui.common`) | `common.points_short` | pts | point |
|
||||
|
||||
## Frontend error keys used in flow scope
|
||||
|
||||
| Error family | Key | en | da |
|
||||
|---|---|---|---|
|
||||
| Join | `frontend.errors.session_code_required` | Session code is required. | Sessionskoden er påkrævet. |
|
||||
| Join | `frontend.errors.session_not_found` | Session code is invalid or the session no longer exists. | Sessionskoden er ugyldig, eller sessionen findes ikke længere. |
|
||||
| Join | `frontend.errors.nickname_invalid` | Nickname must be between 2 and 40 characters. | Kaldenavn skal være mellem 2 og 40 tegn. |
|
||||
| Join | `frontend.errors.nickname_taken` | Nickname is already taken. | Kaldenavnet er allerede taget. |
|
||||
| Join | `frontend.errors.join_failed` | Join failed. Check code or nickname and try again. | Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen. |
|
||||
| Start round | `frontend.errors.start_round_failed` | Could not start round. Refresh the lobby and try again. | Kunne ikke starte runden. Opdater lobbyen og prøv igen. |
|
||||
| Any | `frontend.errors.unknown` | Action failed. Refresh status and try again. | Handlingen fejlede. Opdater status og prøv igen. |
|
||||
|
||||
## Backend→frontend mapping for gameplay errors
|
||||
|
||||
Mapped in `contract.backend_to_frontend_error_keys` (source: `shared/i18n/lobby.json`):
|
||||
|
||||
> Note: `host_only_action` is **not** part of the current shared contract mapping and is intentionally not listed here.
|
||||
|
||||
- `session_code_required` → `session_code_required`
|
||||
- `nickname_invalid` → `nickname_invalid`
|
||||
- `session_not_found` → `session_not_found`
|
||||
- `session_not_joinable` → `join_failed`
|
||||
- `nickname_taken` → `nickname_taken`
|
||||
- `category_slug_required` → `start_round_failed`
|
||||
- `category_not_found` → `start_round_failed`
|
||||
- `round_start_invalid_phase` → `start_round_failed`
|
||||
- `round_already_configured` → `start_round_failed`
|
||||
|
||||
## Notes
|
||||
|
||||
- This is a bootstrap key-map doc for MVP mergeability.
|
||||
- The key/value source of truth remains `shared/i18n/lobby.json`.
|
||||
@@ -65,3 +65,10 @@ Target: rollback + sanity-verifikation inden for 10 minutter.
|
||||
- Flag ON (host deep-link): `UiScreenTests.test_host_screen_deeplink_preserves_spa_path_when_feature_flag_enabled`
|
||||
- Flag ON (player): `UiScreenTests.test_player_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||
- Smoke-checkliste for cutover paths: `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md` + `docs/UI_SMOKE.md`
|
||||
|
||||
|
||||
## MVP audio policy guardrail (telefon-klient)
|
||||
- Telefon-/player-klienten må ikke starte lydafspilning lokalt i MVP (`primary-device only`).
|
||||
- Policy er bundet til capability-flaget `frontend.capabilities.client_has_no_audio_output=true` i `shared/i18n/lobby.json`.
|
||||
- Brugeradvarsel i player UI leveres via i18n key: `frontend.ui.player.audio_policy_notice`.
|
||||
- Acceptance-spec er dækket i Angular tests (`player-shell.component.spec.ts`), inkl. at init-path ikke kalder original media `play`.
|
||||
|
||||
@@ -1,7 +1,15 @@
|
||||
import { ApplicationConfig } from '@angular/core';
|
||||
import { provideRouter, withHashLocation } from '@angular/router';
|
||||
|
||||
import { routes } from './app.routes';
|
||||
import { createWppApiClient, WPP_API_CLIENT } from './wpp-api-client';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [provideRouter(routes, withHashLocation())],
|
||||
providers: [
|
||||
provideRouter(routes, withHashLocation()),
|
||||
{
|
||||
provide: WPP_API_CLIENT,
|
||||
useFactory: () => createWppApiClient(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -55,7 +55,7 @@ type LeaderboardResponse = FinishGameResponse;
|
||||
<pre *ngIf="scoreboardPayload">{{ scoreboardPayload }}</pre>
|
||||
<div *ngIf="finalLeaderboard.length">
|
||||
<h3>{{ copy('host.final_leaderboard') }}</h3>
|
||||
<p *ngIf="finalWinner"><strong>{{ copy('host.winner') }}:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} pts)</p>
|
||||
<p *ngIf="finalWinner"><strong>{{ copy('host.winner') }}:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} {{ copy('common.points_short') }})</p>
|
||||
<ol>
|
||||
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||
</ol>
|
||||
@@ -156,7 +156,7 @@ export class HostShellComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -177,7 +177,7 @@ export class HostShellComponent implements OnInit, OnDestroy {
|
||||
await this.runAction(async () => {
|
||||
const state = await this.controller.startRound(this.sessionCode, this.categorySlug.trim());
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import lobbyCatalog from '../../../../../../shared/i18n/lobby.json';
|
||||
import { PlayerShellComponent } from './player-shell.component';
|
||||
|
||||
type FetchMock = ReturnType<typeof vi.fn>;
|
||||
@@ -350,4 +351,171 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('silences active media elements when secondary-device audio guard is installed', () => {
|
||||
const pauseAudio = vi.fn();
|
||||
const pauseVideo = vi.fn();
|
||||
const audioElement = { muted: false, pause: pauseAudio };
|
||||
const videoElement = { muted: false, pause: pauseVideo };
|
||||
const querySelectorAll = vi.fn().mockReturnValue([audioElement, videoElement]);
|
||||
|
||||
vi.stubGlobal('document', { querySelectorAll });
|
||||
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() },
|
||||
HTMLMediaElement: { prototype: { play: vi.fn().mockResolvedValue(undefined) } },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
expect(querySelectorAll).toHaveBeenCalledWith('audio,video');
|
||||
expect(audioElement.muted).toBe(true);
|
||||
expect(videoElement.muted).toBe(true);
|
||||
expect(pauseAudio).toHaveBeenCalledTimes(1);
|
||||
expect(pauseVideo).toHaveBeenCalledTimes(1);
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('installs secondary-device audio guard while player shell is mounted', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
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() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
const pause = vi.fn();
|
||||
const audioElement = { muted: false, defaultMuted: false, volume: 1, pause };
|
||||
|
||||
await expect(mediaPrototype.play.call(audioElement)).resolves.toBeUndefined();
|
||||
expect(audioElement.muted).toBe(true);
|
||||
expect(audioElement.defaultMuted).toBe(true);
|
||||
expect(audioElement.volume).toBe(0);
|
||||
expect(pause).toHaveBeenCalledTimes(1);
|
||||
|
||||
component.ngOnDestroy();
|
||||
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
});
|
||||
|
||||
it('keeps audio guard active until the last mounted player shell is destroyed', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
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() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const firstComponent = new PlayerShellComponent();
|
||||
const secondComponent = new PlayerShellComponent();
|
||||
|
||||
firstComponent.ngOnInit();
|
||||
secondComponent.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
|
||||
firstComponent.ngOnDestroy();
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
|
||||
secondComponent.ngOnDestroy();
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
});
|
||||
|
||||
it('does not trigger original media play during player-shell init path', () => {
|
||||
const originalPlay = vi.fn().mockResolvedValue(undefined);
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
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() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
expect(originalPlay).not.toHaveBeenCalled();
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('keeps primary-device playback untouched when no-audio capability is disabled', async () => {
|
||||
const originalPlay = vi.fn().mockResolvedValue(undefined);
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
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() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
(component as any).clientHasNoAudioOutput = false;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
expect(mediaPrototype.play).toBe(originalPlay);
|
||||
expect((mediaPrototype as any).__wppSecondaryDeviceAudioGuard__).toBeUndefined();
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('resolves i18n warning copy from shared catalog without key fallback', () => {
|
||||
const component = new PlayerShellComponent();
|
||||
|
||||
const notice = component.copy('player.audio_policy_notice');
|
||||
const expected = lobbyCatalog.frontend.ui.player.audio_policy_notice[component.locale];
|
||||
|
||||
expect(notice).toBe(expected);
|
||||
expect(notice).not.toBe('player.audio_policy_notice');
|
||||
});
|
||||
|
||||
it('gates template warning notice on the no-audio-output capability flag', () => {
|
||||
const templateSource = String((PlayerShellComponent as any).ɵcmp?.template);
|
||||
|
||||
expect(templateSource).toContain('clientHasNoAudioOutput');
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
expect(component.copy('player.audio_policy_notice')).not.toBe('player.audio_policy_notice');
|
||||
expect(component.clientHasNoAudioOutput).toBe(true);
|
||||
|
||||
(component as any).clientHasNoAudioOutput = false;
|
||||
expect(component.clientHasNoAudioOutput).toBe(false);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -16,6 +16,22 @@ interface SessionDetail {
|
||||
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
||||
type LoadingTransition = 'refresh' | 'join' | 'submit-lie' | 'submit-guess' | null;
|
||||
|
||||
type GuardableMediaElement = {
|
||||
muted?: boolean;
|
||||
defaultMuted?: boolean;
|
||||
volume?: number;
|
||||
pause?: () => void;
|
||||
};
|
||||
|
||||
type MediaPrototypeWithGuardState = {
|
||||
play?: (this: GuardableMediaElement) => Promise<void>;
|
||||
__wppSecondaryDeviceAudioGuard__?: {
|
||||
originalPlay: (this: GuardableMediaElement) => Promise<void>;
|
||||
installs: number;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
function resolveLocalStorage(): Storage | undefined {
|
||||
if (typeof window === 'undefined') {
|
||||
return undefined;
|
||||
@@ -29,6 +45,7 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
imports: [CommonModule, FormsModule],
|
||||
template: `
|
||||
<h2>{{ copy('player.title') }}</h2>
|
||||
<p *ngIf="clientHasNoAudioOutput" class="hint">{{ copy('player.audio_policy_notice') }}</p>
|
||||
|
||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||
@@ -113,6 +130,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stateSyncTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private unsubscribeLocale: (() => void) | null = null;
|
||||
private restoreAudioGuard: (() => void) | null = null;
|
||||
|
||||
constructor() {
|
||||
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||
@@ -129,6 +147,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
|
||||
this.locale = locale;
|
||||
});
|
||||
this.installSecondaryDeviceAudioGuard();
|
||||
|
||||
const hashRoute = window.location.hash.replace(/^#\/?/, '');
|
||||
const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
|
||||
@@ -158,6 +177,8 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
this.clearStateSyncTimer();
|
||||
this.unsubscribeLocale?.();
|
||||
this.unsubscribeLocale = null;
|
||||
this.restoreAudioGuard?.();
|
||||
this.restoreAudioGuard = null;
|
||||
}
|
||||
|
||||
private readonly handleOnline = (): void => {
|
||||
@@ -185,6 +206,79 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
private installSecondaryDeviceAudioGuard(): void {
|
||||
if (!this.clientHasNoAudioOutput || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.silenceExistingMediaElements();
|
||||
|
||||
const mediaPrototype = (window as Window & { HTMLMediaElement?: { prototype?: MediaPrototypeWithGuardState } }).HTMLMediaElement
|
||||
?.prototype;
|
||||
|
||||
if (!mediaPrototype || typeof mediaPrototype.play !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const guardState = mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
if (guardState) {
|
||||
guardState.installs += 1;
|
||||
} else {
|
||||
const originalPlay = mediaPrototype.play;
|
||||
mediaPrototype.play = function mediaGuardedPlay(this: GuardableMediaElement): Promise<void> {
|
||||
this.muted = true;
|
||||
this.defaultMuted = true;
|
||||
if (typeof this.volume === 'number') {
|
||||
this.volume = 0;
|
||||
}
|
||||
this.pause?.();
|
||||
return Promise.resolve();
|
||||
};
|
||||
mediaPrototype.__wppSecondaryDeviceAudioGuard__ = {
|
||||
originalPlay,
|
||||
installs: 1,
|
||||
};
|
||||
}
|
||||
|
||||
this.restoreAudioGuard = () => {
|
||||
const currentState = mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
if (!currentState) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentState.installs -= 1;
|
||||
if (currentState.installs <= 0) {
|
||||
mediaPrototype.play = currentState.originalPlay;
|
||||
delete mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private silenceExistingMediaElements(): void {
|
||||
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeElements = document.querySelectorAll('audio,video') as
|
||||
| NodeListOf<GuardableMediaElement>
|
||||
| GuardableMediaElement[]
|
||||
| undefined;
|
||||
|
||||
if (!activeElements || typeof (activeElements as { forEach?: unknown }).forEach !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
activeElements.forEach((element) => {
|
||||
element.muted = true;
|
||||
element.defaultMuted = true;
|
||||
if (typeof element.volume === 'number') {
|
||||
element.volume = 0;
|
||||
}
|
||||
element.pause?.();
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleStateSync(): void {
|
||||
this.clearStateSyncTimer();
|
||||
|
||||
@@ -232,7 +326,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
if (error instanceof Error && error.message) {
|
||||
return error.message;
|
||||
}
|
||||
return 'Unknown error';
|
||||
return this.copy('common.unknown_error');
|
||||
}
|
||||
|
||||
private markOnline(): void {
|
||||
@@ -356,7 +450,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -382,7 +476,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const state = await this.controller.joinLobby(this.sessionCode, this.nickname);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
|
||||
@@ -26,19 +26,22 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
host.ngOnInit();
|
||||
player.ngOnInit();
|
||||
|
||||
expect(host.copy('host.start_round')).toBe('Start round');
|
||||
expect(player.copy('player.submit_guess')).toBe('Submit guess');
|
||||
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('host.start_round')).toBe('Start runde');
|
||||
expect(player.copy('player.submit_guess')).toBe('Send gæt');
|
||||
expect(host.copy('game.host.start_round')).toBe('Start runde');
|
||||
expect(player.copy('game.player.submit_guess')).toBe('Send gæt');
|
||||
|
||||
player.ngOnDestroy();
|
||||
host.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('keeps audio routing policy primary-only (client has no audio output)', () => {
|
||||
it('keeps audio routing policy primary-only (client has no audio output)', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
@@ -46,16 +49,25 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
vi.stubGlobal('document', { querySelectorAll: vi.fn().mockReturnValue([]) });
|
||||
|
||||
const host = new HostShellComponent();
|
||||
const player = new PlayerShellComponent();
|
||||
host.ngOnInit();
|
||||
|
||||
expect(host.clientHasNoAudioOutput).toBe(true);
|
||||
expect(player.clientHasNoAudioOutput).toBe(true);
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
|
||||
const player = new PlayerShellComponent();
|
||||
player.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
|
||||
player.ngOnDestroy();
|
||||
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
|
||||
host.ngOnDestroy();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,6 +45,22 @@ describe('lobby i18n locale propagation', () => {
|
||||
expect(updates).toEqual(['en', 'da']);
|
||||
});
|
||||
|
||||
it('prefers backend-provided shell locale over browser defaults', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock(),
|
||||
});
|
||||
vi.stubGlobal('document', {
|
||||
body: { dataset: { wppLocale: 'da' } },
|
||||
querySelector: vi.fn(() => null),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
expect(i18n.resolvePreferredLocale()).toBe('da');
|
||||
});
|
||||
|
||||
it('falls back to default en translation when da key is intentionally missing', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
@@ -77,6 +93,36 @@ describe('lobby i18n locale propagation', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('resolves baseline shell/game keys from shared namespaces', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock({ 'wpp.locale': 'da' }),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'da-DK' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
const baselineKeys = [
|
||||
'lobby.shell.title',
|
||||
'lobby.shell.host_nav',
|
||||
'lobby.shell.player_nav',
|
||||
'lobby.shell.language_label',
|
||||
'common.refresh',
|
||||
'common.session_code',
|
||||
'game.host.title',
|
||||
'game.host.start_round',
|
||||
'game.player.title',
|
||||
'game.player.submit_guess',
|
||||
] as const;
|
||||
|
||||
for (const key of baselineKeys) {
|
||||
const value = i18n.t(key, 'da');
|
||||
expect(value).toBeTypeOf('string');
|
||||
expect(value.length).toBeGreaterThan(0);
|
||||
expect(value).not.toBe(key);
|
||||
}
|
||||
});
|
||||
|
||||
it('exposes primary-only audio routing policy to clients', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
|
||||
@@ -1,26 +1,15 @@
|
||||
import lobbyCatalog from '../../../../shared/i18n/lobby.json';
|
||||
|
||||
type SupportedLocale = (typeof lobbyCatalog.locales.supported)[number];
|
||||
|
||||
const DEFAULT_LOCALE = lobbyCatalog.locales.default as SupportedLocale;
|
||||
const SUPPORTED_LOCALES = lobbyCatalog.locales.supported as readonly SupportedLocale[];
|
||||
import {
|
||||
DEFAULT_LOCALE,
|
||||
LOBBY_I18N_CATALOG,
|
||||
normalizeLocale,
|
||||
type SupportedLocale,
|
||||
translateCatalogPath,
|
||||
} from '../../../shared/i18n/lobby-loader';
|
||||
|
||||
let activeLocale: SupportedLocale | null = null;
|
||||
const localeSubscribers = new Set<(locale: SupportedLocale) => void>();
|
||||
|
||||
export function normalizeLocale(rawLocale?: string | null): SupportedLocale {
|
||||
const locale = (rawLocale ?? '').trim().toLowerCase();
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
|
||||
return locale as SupportedLocale;
|
||||
}
|
||||
|
||||
const shortLocale = locale.split('-')[0] ?? '';
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(shortLocale)) {
|
||||
return shortLocale as SupportedLocale;
|
||||
}
|
||||
|
||||
return DEFAULT_LOCALE;
|
||||
}
|
||||
export { normalizeLocale };
|
||||
|
||||
export function resolvePreferredLocale(): SupportedLocale {
|
||||
if (activeLocale) {
|
||||
@@ -32,11 +21,14 @@ export function resolvePreferredLocale(): SupportedLocale {
|
||||
return activeLocale;
|
||||
}
|
||||
|
||||
const rootLocale =
|
||||
typeof document !== 'undefined' ? document.querySelector<HTMLElement>('app-root')?.dataset?.['wppLocale'] : null;
|
||||
const shellLocale = typeof document !== 'undefined' ? document.body?.dataset?.['wppLocale'] : null;
|
||||
const queryLocale = new URLSearchParams(window.location?.search ?? '').get('lang');
|
||||
const storedLocale = window.localStorage?.getItem?.('wpp.locale');
|
||||
const browserLocale = typeof navigator !== 'undefined' ? navigator.language : '';
|
||||
|
||||
activeLocale = normalizeLocale(queryLocale || storedLocale || browserLocale || DEFAULT_LOCALE);
|
||||
activeLocale = normalizeLocale(rootLocale || shellLocale || queryLocale || storedLocale || browserLocale || DEFAULT_LOCALE);
|
||||
return activeLocale;
|
||||
}
|
||||
|
||||
@@ -62,25 +54,21 @@ export function subscribeToLocaleChanges(callback: (locale: SupportedLocale) =>
|
||||
};
|
||||
}
|
||||
|
||||
export function t(key: string, locale: string): string {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const fallbackLocale = DEFAULT_LOCALE;
|
||||
const segments = key.split('.');
|
||||
|
||||
let cursor: unknown = lobbyCatalog.frontend.ui;
|
||||
for (const segment of segments) {
|
||||
if (!cursor || typeof cursor !== 'object' || !(segment in (cursor as Record<string, unknown>))) {
|
||||
return key;
|
||||
}
|
||||
cursor = (cursor as Record<string, unknown>)[segment];
|
||||
function resolveCatalogPath(key: string): string {
|
||||
if (key.startsWith('lobby.shell.')) {
|
||||
return key.replace(/^lobby\.shell\./, 'app.');
|
||||
}
|
||||
|
||||
if (!cursor || typeof cursor !== 'object') {
|
||||
return key;
|
||||
if (key.startsWith('game.host.')) {
|
||||
return key.replace(/^game\.host\./, 'host.');
|
||||
}
|
||||
|
||||
const translations = cursor as Record<string, string>;
|
||||
return translations[normalizedLocale] ?? translations[fallbackLocale] ?? key;
|
||||
if (key.startsWith('game.player.')) {
|
||||
return key.replace(/^game\.player\./, 'player.');
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export const clientHasNoAudioOutput = Boolean(lobbyCatalog.frontend.capabilities.client_has_no_audio_output);
|
||||
export function t(key: string, locale: string): string {
|
||||
return translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, resolveCatalogPath(key), locale);
|
||||
}
|
||||
|
||||
export const clientHasNoAudioOutput = Boolean(LOBBY_I18N_CATALOG.frontend.capabilities.client_has_no_audio_output);
|
||||
|
||||
@@ -69,6 +69,7 @@ describe('session route context', () => {
|
||||
sessionCode: 'AB12',
|
||||
playerId: 5,
|
||||
token: 'tok-5',
|
||||
locale: 'en',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -80,7 +81,25 @@ describe('session route context', () => {
|
||||
sessionCode: 'AB12',
|
||||
playerId: null,
|
||||
token: null,
|
||||
locale: 'en',
|
||||
});
|
||||
expect(sessionStorage.setItem).toHaveBeenCalledWith('wpp.host-session-code', 'AB12');
|
||||
});
|
||||
|
||||
it('resolvers normalize and expose locale from lang query param', () => {
|
||||
setWindow(storageMock(), storageMock());
|
||||
|
||||
expect(hostRouteContextResolver(route({}, { lang: 'da-DK' }) as never, {} as never).locale).toBe('da');
|
||||
expect(playerRouteContextResolver(route({}, { lang: 'EN' }) as never, {} as never).locale).toBe('en');
|
||||
});
|
||||
|
||||
it('does not reset persisted preferred locale when lang query param is absent', () => {
|
||||
const localStorage = storageMock({ 'wpp.locale': 'da' });
|
||||
setWindow(localStorage, storageMock());
|
||||
|
||||
expect(hostRouteContextResolver(route({}, { lang: 'da' }) as never, {} as never).locale).toBe('da');
|
||||
expect(hostRouteContextResolver(route({}, {}) as never, {} as never).locale).toBe('da');
|
||||
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith('wpp.locale', 'da');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,13 @@ import { inject } from '@angular/core';
|
||||
import { type ActivatedRouteSnapshot, type CanActivateFn, type ResolveFn, Router, type UrlTree } from '@angular/router';
|
||||
|
||||
import { createSessionContextStore } from '../../../src/spa/session-context-store';
|
||||
import { normalizeLocale, resolvePreferredLocale, setPreferredLocale } from './lobby-i18n';
|
||||
|
||||
export interface RouteSessionContext {
|
||||
sessionCode: string | null;
|
||||
playerId: number | null;
|
||||
token: string | null;
|
||||
locale: string;
|
||||
}
|
||||
|
||||
const HOST_STORAGE_KEY = 'wpp.host-session-code';
|
||||
@@ -61,6 +63,17 @@ export function resolveSessionCode(route: ActivatedRouteSnapshot, mode: 'host' |
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveRouteLocale(route: ActivatedRouteSnapshot): string {
|
||||
const langParam = route.queryParamMap.get('lang');
|
||||
if (langParam !== null) {
|
||||
const locale = normalizeLocale(langParam);
|
||||
setPreferredLocale(locale);
|
||||
return locale;
|
||||
}
|
||||
|
||||
return resolvePreferredLocale();
|
||||
}
|
||||
|
||||
async function sessionExists(code: string): Promise<boolean> {
|
||||
const response = await fetch(`/lobby/sessions/${encodeURIComponent(code)}`, {
|
||||
method: 'GET',
|
||||
@@ -118,23 +131,26 @@ export const playerRouteGuard: CanActivateFn = (route) => guard('player', route)
|
||||
|
||||
export const hostRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||
const code = resolveSessionCode(route, 'host');
|
||||
const locale = resolveRouteLocale(route);
|
||||
if (code) {
|
||||
window.sessionStorage.setItem(HOST_STORAGE_KEY, code);
|
||||
}
|
||||
return { sessionCode: code, playerId: null, token: null };
|
||||
return { sessionCode: code, playerId: null, token: null, locale };
|
||||
};
|
||||
|
||||
export const playerRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||
const code = resolveSessionCode(route, 'player');
|
||||
const locale = resolveRouteLocale(route);
|
||||
const context = createSessionContextStore(window.localStorage).get();
|
||||
|
||||
if (!code || !context || normalizeCode(context.sessionCode) !== code) {
|
||||
return { sessionCode: code, playerId: null, token: null };
|
||||
return { sessionCode: code, playerId: null, token: null, locale };
|
||||
}
|
||||
|
||||
return {
|
||||
sessionCode: code,
|
||||
playerId: Number.isInteger(context.playerId) && context.playerId > 0 ? context.playerId : null,
|
||||
token: context.token.trim() || null,
|
||||
locale,
|
||||
};
|
||||
};
|
||||
|
||||
43
frontend/angular/src/app/wpp-api-client.spec.ts
Normal file
43
frontend/angular/src/app/wpp-api-client.spec.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createWppApiClient } from './wpp-api-client';
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: vi.fn().mockResolvedValue(body),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
describe('WPP Angular API client skeleton', () => {
|
||||
it('normalizes host/player API calls through fetch transport', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(200, { session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 1 }, players: [], round_question: null, phase_view_model: { status: 'lobby', round_number: 1, players_count: 1, constraints: { min_players_to_start: 2, max_players_mvp: 8, min_players_reached: false, max_players_allowed: true }, host: { can_start_round: false, can_show_question: false, can_mix_answers: false, can_calculate_scores: false, can_reveal_scoreboard: false, can_start_next_round: false, can_finish_game: false }, player: { can_join: true, can_submit_lie: false, can_submit_guess: false, can_view_final_result: false } } }))
|
||||
.mockResolvedValueOnce(jsonResponse(201, { player: { id: 1, nickname: 'Luna', session_token: 'tok', score: 0 }, session: { code: 'ABCD12', status: 'lobby' } }));
|
||||
|
||||
const client = createWppApiClient(fetchMock);
|
||||
|
||||
const session = await client.getSession(' abcd12 ');
|
||||
const joined = await client.joinSession({ code: ' abcd12 ', nickname: ' Luna ' });
|
||||
|
||||
expect(session.ok).toBe(true);
|
||||
expect(joined.ok).toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'/lobby/sessions/ABCD12',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'same-origin' })
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'/lobby/sessions/join',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ code: 'ABCD12', nickname: 'Luna' }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
58
frontend/angular/src/app/wpp-api-client.ts
Normal file
58
frontend/angular/src/app/wpp-api-client.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
import {
|
||||
createAngularApiClient,
|
||||
type AngularApiClient,
|
||||
type AngularHttpClientLike,
|
||||
} from '../../../src/api/angular-client';
|
||||
|
||||
export const WPP_API_CLIENT = new InjectionToken<AngularApiClient>('WPP_API_CLIENT');
|
||||
|
||||
export interface FetchLike {
|
||||
(input: string, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
export function createFetchHttpClient(fetchImpl: FetchLike): AngularHttpClientLike {
|
||||
return {
|
||||
async get<T>(url: string): Promise<T> {
|
||||
const response = await fetchImpl(url, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw {
|
||||
status: response.status,
|
||||
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
||||
error: payload,
|
||||
};
|
||||
}
|
||||
return payload as T;
|
||||
},
|
||||
async post<T>(url: string, body: unknown): Promise<T> {
|
||||
const response = await fetchImpl(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw {
|
||||
status: response.status,
|
||||
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
||||
error: payload,
|
||||
};
|
||||
}
|
||||
return payload as T;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createWppApiClient(fetchImpl: FetchLike = fetch.bind(globalThis)): AngularApiClient {
|
||||
return createAngularApiClient(createFetchHttpClient(fetchImpl));
|
||||
}
|
||||
74
frontend/shared/i18n/lobby-loader.ts
Normal file
74
frontend/shared/i18n/lobby-loader.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
||||
|
||||
export type LobbyCatalog = typeof lobbyCatalog;
|
||||
export type SupportedLocale = LobbyCatalog['locales']['supported'][number];
|
||||
|
||||
export const LOBBY_I18N_CATALOG = lobbyCatalog;
|
||||
export const DEFAULT_LOCALE = lobbyCatalog.locales.default as SupportedLocale;
|
||||
export const SUPPORTED_LOCALES = lobbyCatalog.locales.supported as readonly SupportedLocale[];
|
||||
|
||||
export function normalizeLocale(rawLocale?: string | null): SupportedLocale {
|
||||
const locale = (rawLocale ?? '').trim().toLowerCase().replace(/_/g, '-');
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
|
||||
return locale as SupportedLocale;
|
||||
}
|
||||
|
||||
const shortLocale = locale.split('-')[0] ?? '';
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(shortLocale)) {
|
||||
return shortLocale as SupportedLocale;
|
||||
}
|
||||
|
||||
return DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
export function translateCatalogPath(
|
||||
root: Record<string, unknown>,
|
||||
keyPath: string,
|
||||
locale: string,
|
||||
fallback = DEFAULT_LOCALE,
|
||||
): string {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const segments = keyPath.split('.');
|
||||
|
||||
let cursor: unknown = root;
|
||||
for (const segment of segments) {
|
||||
if (!cursor || typeof cursor !== 'object' || !(segment in (cursor as Record<string, unknown>))) {
|
||||
return keyPath;
|
||||
}
|
||||
cursor = (cursor as Record<string, unknown>)[segment];
|
||||
}
|
||||
|
||||
if (!cursor || typeof cursor !== 'object') {
|
||||
return keyPath;
|
||||
}
|
||||
|
||||
const translations = cursor as Record<string, string>;
|
||||
return translations[normalizedLocale] ?? translations[fallback] ?? keyPath;
|
||||
}
|
||||
|
||||
export function collectLocaleParityIssues(
|
||||
node: unknown,
|
||||
locales: readonly string[] = SUPPORTED_LOCALES,
|
||||
path = '',
|
||||
): string[] {
|
||||
if (!node || typeof node !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const record = node as Record<string, unknown>;
|
||||
const keys = Object.keys(record);
|
||||
const isTranslationLeaf = keys.length > 0 && locales.every((locale) => locale in record);
|
||||
|
||||
if (isTranslationLeaf) {
|
||||
const issues: string[] = [];
|
||||
for (const locale of locales) {
|
||||
const value = record[locale];
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
issues.push(`${path || '<root>'} missing non-empty '${locale}' translation`);
|
||||
}
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
return keys.flatMap((key) => collectLocaleParityIssues(record[key], locales, path ? `${path}.${key}` : key));
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
HealthResponse,
|
||||
JoinSessionResponse,
|
||||
MixAnswersResponse,
|
||||
RevealPayload,
|
||||
ScoreboardResponse,
|
||||
SessionDetailResponse,
|
||||
ShowQuestionResponse,
|
||||
@@ -68,6 +69,57 @@ export function mapHealthResponse(payload: unknown): HealthResponse {
|
||||
};
|
||||
}
|
||||
|
||||
function mapRevealPayload(payload: unknown, path: string): RevealPayload {
|
||||
const reveal = asRecord(payload, path);
|
||||
const liesRaw = reveal.lies;
|
||||
const guessesRaw = reveal.guesses;
|
||||
|
||||
if (!Array.isArray(liesRaw)) {
|
||||
throw new Error(`Invalid API contract: expected array at ${path}.lies`);
|
||||
}
|
||||
if (!Array.isArray(guessesRaw)) {
|
||||
throw new Error(`Invalid API contract: expected array at ${path}.guesses`);
|
||||
}
|
||||
|
||||
return {
|
||||
round_question_id: readNumber(reveal, 'round_question_id', path),
|
||||
round_number: readNumber(reveal, 'round_number', path),
|
||||
prompt: readString(reveal, 'prompt', path),
|
||||
correct_answer: readString(reveal, 'correct_answer', path),
|
||||
lies: liesRaw.map((lie, index) => {
|
||||
const liePath = `${path}.lies[${index}]`;
|
||||
const record = asRecord(lie, liePath);
|
||||
return {
|
||||
player_id: readNumber(record, 'player_id', liePath),
|
||||
nickname: readString(record, 'nickname', liePath),
|
||||
text: readString(record, 'text', liePath),
|
||||
created_at: readString(record, 'created_at', liePath)
|
||||
};
|
||||
}),
|
||||
guesses: guessesRaw.map((guess, index) => {
|
||||
const guessPath = `${path}.guesses[${index}]`;
|
||||
const record = asRecord(guess, guessPath);
|
||||
const fooledPlayerId = record.fooled_player_id;
|
||||
if (fooledPlayerId !== null && !isNumber(fooledPlayerId)) {
|
||||
throw new Error(`Invalid API contract: expected number|null at ${guessPath}.fooled_player_id`);
|
||||
}
|
||||
const fooledPlayerNickname = record.fooled_player_nickname;
|
||||
if (fooledPlayerNickname !== undefined && !isString(fooledPlayerNickname)) {
|
||||
throw new Error(`Invalid API contract: expected string|undefined at ${guessPath}.fooled_player_nickname`);
|
||||
}
|
||||
return {
|
||||
player_id: readNumber(record, 'player_id', guessPath),
|
||||
nickname: readString(record, 'nickname', guessPath),
|
||||
selected_text: readString(record, 'selected_text', guessPath),
|
||||
is_correct: readBoolean(record, 'is_correct', guessPath),
|
||||
created_at: readString(record, 'created_at', guessPath),
|
||||
fooled_player_id: fooledPlayerId,
|
||||
...(fooledPlayerNickname === undefined ? {} : { fooled_player_nickname: fooledPlayerNickname })
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
const root = asRecord(payload, 'session_detail');
|
||||
const session = asRecord(root.session, 'session_detail.session');
|
||||
@@ -97,6 +149,7 @@ function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
};
|
||||
}
|
||||
|
||||
const revealRaw = root.reveal;
|
||||
const phase = asRecord(root.phase_view_model, 'session_detail.phase_view_model');
|
||||
const constraints = asRecord(phase.constraints, 'session_detail.phase_view_model.constraints');
|
||||
const host = asRecord(phase.host, 'session_detail.phase_view_model.host');
|
||||
@@ -129,6 +182,7 @@ function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
};
|
||||
}),
|
||||
round_question: roundQuestion,
|
||||
reveal: revealRaw === null || revealRaw === undefined ? null : mapRevealPayload(revealRaw, 'session_detail.reveal'),
|
||||
phase_view_model: {
|
||||
status: readString(phase, 'status', 'session_detail.phase_view_model'),
|
||||
round_number: readNumber(phase, 'round_number', 'session_detail.phase_view_model'),
|
||||
@@ -276,6 +330,7 @@ export function mapCalculateScoresResponse(payload: unknown): CalculateScoresRes
|
||||
round_number: readNumber(roundQuestion, 'round_number', 'calculate_scores.round_question')
|
||||
},
|
||||
events_created: readNumber(root, 'events_created', 'calculate_scores'),
|
||||
reveal: mapRevealPayload(root.reveal, 'calculate_scores.reveal'),
|
||||
leaderboard: leaderboardRaw.map((entry, index) => mapLeaderboardEntry(entry, `calculate_scores.leaderboard[${index}]`))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -57,10 +57,38 @@ export interface PhaseViewModel {
|
||||
};
|
||||
}
|
||||
|
||||
export interface RevealPlayerRef {
|
||||
player_id: number;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface RevealLie extends RevealPlayerRef {
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface RevealGuess extends RevealPlayerRef {
|
||||
selected_text: string;
|
||||
is_correct: boolean;
|
||||
created_at: string;
|
||||
fooled_player_id: number | null;
|
||||
fooled_player_nickname?: string;
|
||||
}
|
||||
|
||||
export interface RevealPayload {
|
||||
round_question_id: number;
|
||||
round_number: number;
|
||||
prompt: string;
|
||||
correct_answer: string;
|
||||
lies: RevealLie[];
|
||||
guesses: RevealGuess[];
|
||||
}
|
||||
|
||||
export interface SessionDetailResponse {
|
||||
session: SessionSummary;
|
||||
players: SessionPlayer[];
|
||||
round_question: SessionRoundQuestion | null;
|
||||
reveal: RevealPayload | null;
|
||||
phase_view_model: PhaseViewModel;
|
||||
}
|
||||
|
||||
@@ -138,6 +166,7 @@ export interface CalculateScoresResponse {
|
||||
round_number: number;
|
||||
};
|
||||
events_created: number;
|
||||
reveal: RevealPayload;
|
||||
leaderboard: Array<{ id: number; nickname: string; score: number }>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,23 +1,17 @@
|
||||
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
||||
import { DEFAULT_LOCALE, LOBBY_I18N_CATALOG, normalizeLocale } from '../../shared/i18n/lobby-loader';
|
||||
|
||||
const frontendErrors = lobbyCatalog.frontend.errors;
|
||||
const localeConfig = lobbyCatalog.locales;
|
||||
const frontendErrors = LOBBY_I18N_CATALOG.frontend.errors;
|
||||
const backendToFrontendErrorKeys = LOBBY_I18N_CATALOG.contract.backend_to_frontend_error_keys as Record<
|
||||
string,
|
||||
keyof typeof frontendErrors
|
||||
>;
|
||||
|
||||
type FrontendErrorKey = keyof typeof frontendErrors;
|
||||
type SupportedLocale = (typeof localeConfig.supported)[number];
|
||||
|
||||
function isFrontendErrorKey(value: string): value is FrontendErrorKey {
|
||||
return value in frontendErrors;
|
||||
}
|
||||
|
||||
function normalizeLocale(rawLocale?: string): SupportedLocale {
|
||||
const requested = (rawLocale ?? '').trim().toLowerCase();
|
||||
if (localeConfig.supported.includes(requested as SupportedLocale)) {
|
||||
return requested as SupportedLocale;
|
||||
}
|
||||
return localeConfig.default;
|
||||
}
|
||||
|
||||
export function lobbyMessage(key: FrontendErrorKey, locale?: string): string {
|
||||
const resolvedLocale = normalizeLocale(locale);
|
||||
const translations = frontendErrors[key] as Record<string, string>;
|
||||
@@ -25,8 +19,8 @@ export function lobbyMessage(key: FrontendErrorKey, locale?: string): string {
|
||||
if (translations[resolvedLocale]) {
|
||||
return translations[resolvedLocale];
|
||||
}
|
||||
if (translations[localeConfig.default]) {
|
||||
return translations[localeConfig.default];
|
||||
if (translations[DEFAULT_LOCALE]) {
|
||||
return translations[DEFAULT_LOCALE];
|
||||
}
|
||||
|
||||
return key;
|
||||
@@ -40,9 +34,15 @@ export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: Fronte
|
||||
const record = payload as Record<string, unknown>;
|
||||
const code = typeof record.error_code === 'string' ? record.error_code : '';
|
||||
const payloadLocale = typeof record.locale === 'string' ? record.locale : locale;
|
||||
if (!isFrontendErrorKey(code)) {
|
||||
return lobbyMessage(fallbackKey, payloadLocale);
|
||||
const mappedKey = code ? backendToFrontendErrorKeys[code] : undefined;
|
||||
|
||||
if (mappedKey && isFrontendErrorKey(mappedKey)) {
|
||||
return lobbyMessage(mappedKey, payloadLocale);
|
||||
}
|
||||
|
||||
return lobbyMessage(code, payloadLocale);
|
||||
if (isFrontendErrorKey(code)) {
|
||||
return lobbyMessage(code, payloadLocale);
|
||||
}
|
||||
|
||||
return lobbyMessage(fallbackKey, payloadLocale);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('createAngularApiClient', () => {
|
||||
{ id: 3, nickname: 'Bo', score: 0, is_connected: false }
|
||||
],
|
||||
round_question: null,
|
||||
reveal: null,
|
||||
phase_view_model: {
|
||||
status: 'lobby',
|
||||
round_number: 1,
|
||||
@@ -84,6 +85,7 @@ describe('createAngularApiClient', () => {
|
||||
if (session.ok) {
|
||||
expect(session.data.session.code).toBe('ABCD12');
|
||||
expect(session.data.session.host_id).toBe(1);
|
||||
expect(session.data.reveal).toBeNull();
|
||||
expect(session.data.phase_view_model.host.can_start_round).toBe(true);
|
||||
}
|
||||
|
||||
@@ -119,6 +121,7 @@ describe('createAngularApiClient', () => {
|
||||
session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 },
|
||||
players: [],
|
||||
round_question: null,
|
||||
reveal: null,
|
||||
phase_view_model: {
|
||||
status: 'lobby',
|
||||
round_number: 1,
|
||||
@@ -189,6 +192,117 @@ describe('createAngularApiClient', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('maps canonical reveal payload from session detail in reveal phase', async () => {
|
||||
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
|
||||
if (url === '/lobby/sessions/ABCD12') {
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'reveal', host_id: 1, current_round: 1, players_count: 3 },
|
||||
players: [
|
||||
{ id: 2, nickname: 'Maja', score: 4, is_connected: true },
|
||||
{ id: 3, nickname: 'Bo', score: 2, is_connected: true },
|
||||
{ id: 4, nickname: 'Ida', score: 5, is_connected: true }
|
||||
],
|
||||
round_question: {
|
||||
id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
shown_at: '2026-03-01T16:00:00Z',
|
||||
answers: [{ text: 'Edison' }, { text: 'Tesla' }]
|
||||
},
|
||||
reveal: {
|
||||
round_question_id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
correct_answer: 'Edison',
|
||||
lies: [
|
||||
{
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla',
|
||||
created_at: '2026-03-01T16:00:20Z'
|
||||
}
|
||||
],
|
||||
guesses: [
|
||||
{
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo',
|
||||
created_at: '2026-03-01T16:01:00Z'
|
||||
},
|
||||
{
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null,
|
||||
created_at: '2026-03-01T16:01:02Z'
|
||||
}
|
||||
]
|
||||
},
|
||||
phase_view_model: {
|
||||
status: 'reveal',
|
||||
round_number: 1,
|
||||
players_count: 3,
|
||||
constraints: {
|
||||
min_players_to_start: 2,
|
||||
max_players_mvp: 8,
|
||||
min_players_reached: true,
|
||||
max_players_allowed: true
|
||||
},
|
||||
host: {
|
||||
can_start_round: false,
|
||||
can_show_question: false,
|
||||
can_mix_answers: false,
|
||||
can_calculate_scores: false,
|
||||
can_reveal_scoreboard: true,
|
||||
can_start_next_round: true,
|
||||
can_finish_game: true
|
||||
},
|
||||
player: {
|
||||
can_join: false,
|
||||
can_submit_lie: false,
|
||||
can_submit_guess: false,
|
||||
can_view_final_result: false
|
||||
}
|
||||
}
|
||||
} as T;
|
||||
}
|
||||
|
||||
throw { status: 404, error: { error: 'Not found' } };
|
||||
});
|
||||
|
||||
const client = createAngularApiClient({ get, post: vi.fn() } as AngularHttpClientLike);
|
||||
const session = await client.getSession('abcd12');
|
||||
|
||||
expect(session.ok).toBe(true);
|
||||
if (session.ok) {
|
||||
expect(session.data.reveal?.correct_answer).toBe('Edison');
|
||||
expect(session.data.reveal?.lies[0]).toMatchObject({
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla'
|
||||
});
|
||||
expect(session.data.reveal?.guesses[0]).toMatchObject({
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo'
|
||||
});
|
||||
expect(session.data.reveal?.guesses[1]).toMatchObject({
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('returns parse error when successful payload breaks typed contract', async () => {
|
||||
const http = {
|
||||
get: vi.fn<AngularHttpClientLike['get']>(async <T>() => ({ ok: true } as T)),
|
||||
@@ -248,6 +362,39 @@ describe('createAngularApiClient', () => {
|
||||
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||
round_question: { id: 77, round_number: 1 },
|
||||
events_created: 3,
|
||||
reveal: {
|
||||
round_question_id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
correct_answer: 'Edison',
|
||||
lies: [
|
||||
{
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla',
|
||||
created_at: '2026-03-01T16:00:20Z'
|
||||
}
|
||||
],
|
||||
guesses: [
|
||||
{
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo',
|
||||
created_at: '2026-03-01T16:01:00Z'
|
||||
},
|
||||
{
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null,
|
||||
created_at: '2026-03-01T16:01:02Z'
|
||||
}
|
||||
]
|
||||
},
|
||||
leaderboard: [{ id: 2, nickname: 'Maja', score: 11 }]
|
||||
} as T;
|
||||
}
|
||||
@@ -305,6 +452,29 @@ describe('createAngularApiClient', () => {
|
||||
|
||||
const calculateScores = await client.calculateScores('abcd12', 77);
|
||||
expect(calculateScores.ok).toBe(true);
|
||||
if (calculateScores.ok) {
|
||||
expect(calculateScores.data.reveal.correct_answer).toBe('Edison');
|
||||
expect(calculateScores.data.reveal.lies[0]).toMatchObject({
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla'
|
||||
});
|
||||
expect(calculateScores.data.reveal.guesses[0]).toMatchObject({
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo'
|
||||
});
|
||||
expect(calculateScores.data.reveal.guesses[1]).toMatchObject({
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null
|
||||
});
|
||||
}
|
||||
|
||||
const scoreboard = await client.getScoreboard('abcd12');
|
||||
expect(scoreboard.ok).toBe(true);
|
||||
|
||||
@@ -14,10 +14,16 @@ describe('shared i18n keyspace contract', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps backend error-code keyspace aligned with backend translations', () => {
|
||||
for (const [code, key] of Object.entries(lobbyCatalog.backend.error_codes)) {
|
||||
expect(code).toBe(key);
|
||||
expect(lobbyCatalog.backend.errors[key as keyof typeof lobbyCatalog.backend.errors]).toBeDefined();
|
||||
it('keeps backend error-code keyspace aligned with shared backend→frontend map and backend translations', () => {
|
||||
for (const [code, backendKey] of Object.entries(lobbyCatalog.backend.error_codes)) {
|
||||
const frontendKey =
|
||||
lobbyCatalog.contract.backend_to_frontend_error_keys[
|
||||
code as keyof typeof lobbyCatalog.contract.backend_to_frontend_error_keys
|
||||
];
|
||||
|
||||
expect(lobbyCatalog.backend.errors[backendKey as keyof typeof lobbyCatalog.backend.errors]).toBeDefined();
|
||||
expect(frontendKey, `missing frontend mapping for ${code}`).toBeTruthy();
|
||||
expect(lobbyCatalog.frontend.errors[frontendKey as keyof typeof lobbyCatalog.frontend.errors]).toBeDefined();
|
||||
}
|
||||
|
||||
for (const [key, translations] of Object.entries(lobbyCatalog.backend.errors)) {
|
||||
@@ -42,10 +48,19 @@ describe('lobbyMessage locale handling', () => {
|
||||
).toBe('Sessionskoden er ugyldig, eller sessionen findes ikke længere.');
|
||||
});
|
||||
|
||||
it('falls back when backend error code has no frontend translation key', () => {
|
||||
it('uses shared backend→frontend key-map at runtime even when fallback key differs', () => {
|
||||
expect(
|
||||
lobbyMessageFromApiPayload(
|
||||
{ error_code: 'session_not_joinable', locale: 'da' },
|
||||
'start_round_failed',
|
||||
),
|
||||
).toBe('Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen.');
|
||||
});
|
||||
|
||||
it('falls back to caller-provided fallback key for unknown backend error codes', () => {
|
||||
expect(
|
||||
lobbyMessageFromApiPayload(
|
||||
{ error_code: 'unknown_backend_key', locale: 'da' },
|
||||
'join_failed',
|
||||
),
|
||||
).toBe('Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen.');
|
||||
|
||||
38
frontend/tests/lobby-loader.parity.test.ts
Normal file
38
frontend/tests/lobby-loader.parity.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
collectLocaleParityIssues,
|
||||
LOBBY_I18N_CATALOG,
|
||||
normalizeLocale,
|
||||
SUPPORTED_LOCALES,
|
||||
translateCatalogPath,
|
||||
} from '../shared/i18n/lobby-loader';
|
||||
|
||||
describe('shared lobby i18n loader parity', () => {
|
||||
it('keeps da/en translation parity in shared keyspace', () => {
|
||||
const issues = collectLocaleParityIssues(LOBBY_I18N_CATALOG, SUPPORTED_LOCALES);
|
||||
expect(issues).toEqual([]);
|
||||
});
|
||||
|
||||
it('normalizes browser-style locale tags to supported keyspace locales', () => {
|
||||
expect(normalizeLocale('da-DK')).toBe('da');
|
||||
expect(normalizeLocale('da_DK')).toBe('da');
|
||||
expect(normalizeLocale('en-US')).toBe('en');
|
||||
expect(normalizeLocale('en_US')).toBe('en');
|
||||
expect(normalizeLocale('fr-FR')).toBe('en');
|
||||
});
|
||||
|
||||
it('resolves shared frontend ui keys with fallback-safe behavior', () => {
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'host.start_round', 'da-DK'),
|
||||
).toBe('Start runde');
|
||||
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'app.language_label', 'en-US'),
|
||||
).toBe('Language');
|
||||
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'host.non_existing_key', 'da'),
|
||||
).toBe('host.non_existing_key');
|
||||
});
|
||||
});
|
||||
@@ -1,42 +1,62 @@
|
||||
import json
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
from django.http import HttpRequest, JsonResponse
|
||||
from django.utils.translation import get_language_from_request
|
||||
|
||||
from partyhub.i18n_bootstrap import locale_config, shared_i18n_catalog
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def lobby_i18n_catalog() -> dict:
|
||||
catalog_path = Path(__file__).resolve().parents[1] / "shared" / "i18n" / "lobby.json"
|
||||
with catalog_path.open(encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
return shared_i18n_catalog()
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def i18n_locale_config() -> tuple[str, tuple[str, ...]]:
|
||||
locales = lobby_i18n_catalog().get("locales", {})
|
||||
default_locale = str(locales.get("default", "en")).strip().lower() or "en"
|
||||
supported_locales = tuple(
|
||||
locale.strip().lower() for locale in locales.get("supported", ["en", "da"]) if str(locale).strip()
|
||||
) or ("en", "da")
|
||||
return default_locale, supported_locales
|
||||
return locale_config()
|
||||
|
||||
|
||||
def lobby_i18n_errors() -> dict:
|
||||
return lobby_i18n_catalog().get("backend", {}).get("error_codes", {})
|
||||
return shared_i18n_catalog().get("backend", {}).get("error_codes", {})
|
||||
|
||||
|
||||
def lobby_i18n_error_messages() -> dict:
|
||||
return lobby_i18n_catalog().get("backend", {}).get("errors", {})
|
||||
return shared_i18n_catalog().get("backend", {}).get("errors", {})
|
||||
|
||||
|
||||
def _quality_value(language_candidate: str) -> float | None:
|
||||
for parameter in language_candidate.split(";")[1:]:
|
||||
key, separator, value = parameter.partition("=")
|
||||
if separator and key.strip().lower() == "q":
|
||||
try:
|
||||
return float(value.strip())
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def resolve_locale(request: HttpRequest) -> str:
|
||||
default_locale, supported_locales = i18n_locale_config()
|
||||
requested = (get_language_from_request(request) or "").split("-", 1)[0].lower()
|
||||
|
||||
accept_language = request.META.get("HTTP_ACCEPT_LANGUAGE") or ""
|
||||
ranked_candidates: list[tuple[float, int, str]] = []
|
||||
for index, candidate in enumerate(accept_language.split(",")):
|
||||
quality = _quality_value(candidate)
|
||||
if quality is not None and quality <= 0:
|
||||
continue
|
||||
|
||||
tag = candidate.split(";", 1)[0]
|
||||
normalized = tag.strip().replace("_", "-").split("-", 1)[0].lower()
|
||||
if normalized not in supported_locales:
|
||||
continue
|
||||
|
||||
ranked_candidates.append((quality if quality is not None else 1.0, index, normalized))
|
||||
|
||||
if ranked_candidates:
|
||||
ranked_candidates.sort(key=lambda entry: (-entry[0], entry[1]))
|
||||
return ranked_candidates[0][2]
|
||||
|
||||
requested = (get_language_from_request(request) or "").replace("_", "-").split("-", 1)[0].lower()
|
||||
if requested in supported_locales:
|
||||
return requested
|
||||
return default_locale
|
||||
|
||||
@@ -89,6 +89,8 @@ var connectionRetryInFlight=false;
|
||||
var playerShellFatalError=false;
|
||||
var playerShellRecoverInFlight=false;
|
||||
var playerCriticalHydrated=false;
|
||||
function silencePlayerMediaElements(){if(typeof document==="undefined"||typeof document.querySelectorAll!=="function"){return;}var elements=document.querySelectorAll("audio,video");if(!elements||typeof elements.forEach!=="function"){return;}elements.forEach(function(element){if(!element){return;}element.muted=true;if(typeof element.pause==="function"){element.pause();}});}
|
||||
function installSecondaryDeviceAudioGuard(){if(typeof window==="undefined"){return;}silencePlayerMediaElements();var mediaProto=window.HTMLMediaElement&&window.HTMLMediaElement.prototype;if(!mediaProto||typeof mediaProto.play!=="function"){return;}if(mediaProto.__wppSecondaryDeviceAudioGuardInstalled){return;}mediaProto.__wppSecondaryDeviceAudioGuardInstalled=true;mediaProto.__wppSecondaryDeviceAudioGuardOriginalPlay=mediaProto.play;mediaProto.play=function(){return Promise.resolve();};}
|
||||
function setPlayerCriticalLoading(isLoading){var skeleton=document.getElementById("playerCriticalSkeleton");var view=document.getElementById("playerCriticalView");if(!skeleton||!view){return;}skeleton.style.display=isLoading?"block":"none";view.style.display=isLoading?"none":"block";}
|
||||
function hydratePlayerCriticalView(data){var phaseEl=document.getElementById("playerCriticalPhase");var roundEl=document.getElementById("playerCriticalRound");var joinEl=document.getElementById("playerCriticalJoin");if(phaseEl){phaseEl.textContent="Fase: "+phaseLabel(currentSessionStatus||((data&&data.session&&data.session.status)||""));}
|
||||
if(roundEl){roundEl.textContent="Round question: "+(rq()||"afventer");}
|
||||
@@ -153,6 +155,7 @@ function submitGuess(){if(guessSubmitted){return Promise.resolve({error:"guess_a
|
||||
["code","nickname","playerId","sessionToken","roundQuestionId"].forEach(function(fieldId){var field=document.getElementById(fieldId);if(!field){return;}field.addEventListener("input",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});field.addEventListener("change",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});});
|
||||
window.addEventListener("error",function(event){setPlayerShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
||||
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setPlayerShellFatalError(detail);});
|
||||
installSecondaryDeviceAudioGuard();
|
||||
setPlayerCriticalLoading(true);
|
||||
updatePhaseStatus();
|
||||
updateGuessSubmitState();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="da">
|
||||
<html lang="{{ shell_locale|default:'en' }}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>WPP SPA Shell</title>
|
||||
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css?v={{ spa_asset_version|urlencode }}">
|
||||
</head>
|
||||
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">
|
||||
<app-root data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">Indlæser Angular app-shell…</app-root>
|
||||
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}" data-wpp-locale="{{ shell_locale|default:'en' }}">
|
||||
<app-root data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}" data-wpp-locale="{{ shell_locale|default:'en' }}">Indlæser Angular app-shell…</app-root>
|
||||
<script type="module" src="{{ spa_asset_base }}/main.js?v={{ spa_asset_version|urlencode }}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
237
lobby/tests.py
237
lobby/tests.py
@@ -20,7 +20,7 @@ from fupogfakta.models import (
|
||||
RoundConfig,
|
||||
RoundQuestion,
|
||||
)
|
||||
from lobby.i18n import i18n_locale_config, lobby_i18n_catalog, resolve_error_message
|
||||
from lobby.i18n import i18n_locale_config, lobby_i18n_catalog, resolve_error_message, resolve_locale
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
@@ -138,6 +138,17 @@ class LobbyFlowTests(TestCase):
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Session code is required")
|
||||
|
||||
def test_join_error_payload_uses_stable_i18n_contract_keys(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": " ", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(sorted(response.json().keys()), ["error", "error_code", "locale"])
|
||||
|
||||
def test_session_detail_returns_players(self):
|
||||
session = GameSession.objects.create(host=self.host, code="LMNO45")
|
||||
Player.objects.create(session=session, nickname="Mia", score=7)
|
||||
@@ -209,6 +220,8 @@ class StartRoundTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can start round")
|
||||
|
||||
def test_start_round_requires_existing_active_category_with_questions(self):
|
||||
@@ -228,6 +241,8 @@ class StartRoundTests(TestCase):
|
||||
content_type="application/json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "category_has_no_questions")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Category has no active questions")
|
||||
|
||||
def test_start_round_rejects_non_lobby_session(self):
|
||||
@@ -244,6 +259,36 @@ class StartRoundTests(TestCase):
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error"], "Round can only be started from lobby")
|
||||
|
||||
def test_start_round_error_localizes_to_danish(self):
|
||||
self.client.login(username="other", password="secret123")
|
||||
|
||||
response = self.client.post(
|
||||
reverse("lobby:start_round", kwargs={"code": self.session.code}),
|
||||
data={"category_slug": self.category.slug},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Kun værten kan starte runden")
|
||||
|
||||
def test_start_round_error_falls_back_to_english_for_unsupported_locale(self):
|
||||
self.client.login(username="other", password="secret123")
|
||||
|
||||
response = self.client.post(
|
||||
reverse("lobby:start_round", kwargs={"code": self.session.code}),
|
||||
data={"category_slug": self.category.slug},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="fr",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can start round")
|
||||
|
||||
|
||||
class LieSubmissionTests(TestCase):
|
||||
def setUp(self):
|
||||
@@ -434,6 +479,8 @@ class MixAnswersTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_mix_answers")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can mix answers")
|
||||
|
||||
def test_mix_answers_deduplicates_case_insensitive_lies(self):
|
||||
@@ -640,6 +687,7 @@ class ScoreCalculationTests(TestCase):
|
||||
self.player_three = Player.objects.create(session=self.session, nickname="Nora")
|
||||
|
||||
def test_host_can_calculate_scores_and_transition_to_reveal(self):
|
||||
LieAnswer.objects.create(round_question=self.round_question, player=self.player_three, text="Padel")
|
||||
Guess.objects.create(round_question=self.round_question, player=self.player_one, selected_text="Tennis", is_correct=True)
|
||||
Guess.objects.create(
|
||||
round_question=self.round_question,
|
||||
@@ -668,6 +716,57 @@ class ScoreCalculationTests(TestCase):
|
||||
payload = response.json()
|
||||
self.assertEqual(payload["session"]["status"], GameSession.Status.REVEAL)
|
||||
self.assertEqual(payload["events_created"], 2)
|
||||
self.assertEqual(payload["reveal"]["correct_answer"], "Tennis")
|
||||
self.assertEqual(
|
||||
payload["reveal"]["lies"],
|
||||
[
|
||||
{
|
||||
"player_id": self.player_three.id,
|
||||
"nickname": "Nora",
|
||||
"text": "Padel",
|
||||
"created_at": payload["reveal"]["lies"][0]["created_at"],
|
||||
}
|
||||
],
|
||||
)
|
||||
self.assertEqual(
|
||||
[
|
||||
{
|
||||
"player_id": item["player_id"],
|
||||
"nickname": item["nickname"],
|
||||
"selected_text": item["selected_text"],
|
||||
"is_correct": item["is_correct"],
|
||||
"fooled_player_id": item["fooled_player_id"],
|
||||
"fooled_player_nickname": item.get("fooled_player_nickname"),
|
||||
}
|
||||
for item in payload["reveal"]["guesses"]
|
||||
],
|
||||
[
|
||||
{
|
||||
"player_id": self.player_one.id,
|
||||
"nickname": "Luna",
|
||||
"selected_text": "Tennis",
|
||||
"is_correct": True,
|
||||
"fooled_player_id": None,
|
||||
"fooled_player_nickname": None,
|
||||
},
|
||||
{
|
||||
"player_id": self.player_two.id,
|
||||
"nickname": "Mads",
|
||||
"selected_text": "Padel",
|
||||
"is_correct": False,
|
||||
"fooled_player_id": self.player_three.id,
|
||||
"fooled_player_nickname": "Nora",
|
||||
},
|
||||
{
|
||||
"player_id": self.player_three.id,
|
||||
"nickname": "Nora",
|
||||
"selected_text": "Padel",
|
||||
"is_correct": False,
|
||||
"fooled_player_id": self.player_three.id,
|
||||
"fooled_player_nickname": "Nora",
|
||||
},
|
||||
],
|
||||
)
|
||||
|
||||
self.player_one.refresh_from_db()
|
||||
self.player_three.refresh_from_db()
|
||||
@@ -999,6 +1098,10 @@ class UiScreenTests(TestCase):
|
||||
self.assertContains(response, "clearPlayerShellFatalError")
|
||||
self.assertContains(response, "updatePlayerShellErrorBoundary")
|
||||
self.assertContains(response, "player_shell_runtime_error")
|
||||
self.assertContains(response, "installSecondaryDeviceAudioGuard")
|
||||
self.assertContains(response, "silencePlayerMediaElements")
|
||||
self.assertContains(response, "querySelectorAll(\"audio,video\")")
|
||||
self.assertNotContains(response, "<audio")
|
||||
self.assertContains(response, "window.addEventListener(\"error\"")
|
||||
|
||||
@override_settings(USE_SPA_UI=False)
|
||||
@@ -1098,7 +1201,62 @@ class SessionDetailRoundQuestionTests(TestCase):
|
||||
self.assertEqual(payload["round_question"]["id"], round_question.id)
|
||||
self.assertEqual(payload["round_question"]["prompt"], self.question.prompt)
|
||||
|
||||
def test_session_detail_includes_reveal_payload_for_active_round_question(self):
|
||||
self.session.status = GameSession.Status.REVEAL
|
||||
self.session.save(update_fields=["status"])
|
||||
round_question = RoundQuestion.objects.create(
|
||||
session=self.session,
|
||||
round_number=1,
|
||||
question=self.question,
|
||||
correct_answer=self.question.correct_answer,
|
||||
)
|
||||
liar = Player.objects.create(session=self.session, nickname="Bluffer")
|
||||
guesser = Player.objects.create(session=self.session, nickname="Guesser")
|
||||
LieAnswer.objects.create(round_question=round_question, player=liar, text="Tesla")
|
||||
Guess.objects.create(
|
||||
round_question=round_question,
|
||||
player=guesser,
|
||||
selected_text="Tesla",
|
||||
is_correct=False,
|
||||
fooled_player=liar,
|
||||
)
|
||||
|
||||
response = self.client.get(reverse("lobby:session_detail", kwargs={"code": self.session.code}))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
payload = response.json()
|
||||
self.assertEqual(payload["reveal"]["round_question_id"], round_question.id)
|
||||
self.assertEqual(payload["reveal"]["correct_answer"], "Edison")
|
||||
self.assertEqual(
|
||||
[
|
||||
{"player_id": lie["player_id"], "nickname": lie["nickname"], "text": lie["text"]}
|
||||
for lie in payload["reveal"]["lies"]
|
||||
],
|
||||
[{"player_id": liar.id, "nickname": "Bluffer", "text": "Tesla"}],
|
||||
)
|
||||
self.assertEqual(
|
||||
[
|
||||
{
|
||||
"player_id": guess["player_id"],
|
||||
"nickname": guess["nickname"],
|
||||
"selected_text": guess["selected_text"],
|
||||
"is_correct": guess["is_correct"],
|
||||
"fooled_player_id": guess["fooled_player_id"],
|
||||
"fooled_player_nickname": guess.get("fooled_player_nickname"),
|
||||
}
|
||||
for guess in payload["reveal"]["guesses"]
|
||||
],
|
||||
[
|
||||
{
|
||||
"player_id": guesser.id,
|
||||
"nickname": "Guesser",
|
||||
"selected_text": "Tesla",
|
||||
"is_correct": False,
|
||||
"fooled_player_id": liar.id,
|
||||
"fooled_player_nickname": "Bluffer",
|
||||
}
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class SessionDetailPhaseViewModelTests(TestCase):
|
||||
@@ -1216,6 +1374,71 @@ class SmokeStagingCommandTests(TestCase):
|
||||
|
||||
|
||||
class I18nResolverTests(TestCase):
|
||||
def test_resolve_locale_accepts_language_tags_and_normalizes_to_supported_base_locale(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da-DK,da;q=0.9,en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_accepts_underscore_language_tags(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da_DK",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_uses_next_supported_language_when_primary_is_unsupported(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="fr-FR, da;q=0.9, en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_skips_q0_languages_and_falls_back_to_next_supported(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da;q=0, en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_resolve_locale_prefers_highest_quality_supported_language(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da;q=0.8, en;q=0.9",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_resolve_locale_defaults_to_en_when_header_missing(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_missing_backend_key_returns_key_deterministically(self):
|
||||
self.assertEqual(resolve_error_message(key="missing_key", locale="da"), "missing_key")
|
||||
|
||||
@@ -1252,10 +1475,14 @@ class I18nResolverTests(TestCase):
|
||||
self.assertTrue(translations.get("en"), f"frontend key {key} missing en")
|
||||
self.assertTrue(translations.get("da"), f"frontend key {key} missing da")
|
||||
|
||||
def test_backend_error_codes_map_to_same_named_translation_keys(self):
|
||||
def test_backend_error_codes_map_via_shared_backend_frontend_key_map(self):
|
||||
catalog = lobby_i18n_catalog()
|
||||
backend_errors = catalog["backend"]["errors"]
|
||||
frontend_errors = catalog["frontend"]["errors"]
|
||||
shared_map = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
|
||||
for code, key in catalog["backend"]["error_codes"].items():
|
||||
self.assertEqual(code, key)
|
||||
self.assertIn(key, backend_errors)
|
||||
for code, backend_key in catalog["backend"]["error_codes"].items():
|
||||
frontend_key = shared_map.get(code)
|
||||
self.assertIn(backend_key, backend_errors)
|
||||
self.assertTrue(frontend_key, f"missing frontend mapping for backend code: {code}")
|
||||
self.assertIn(frontend_key, frontend_errors)
|
||||
|
||||
@@ -5,7 +5,7 @@ from django.shortcuts import render
|
||||
from fupogfakta.models import Category
|
||||
|
||||
from .feature_flags import use_spa_ui
|
||||
from .i18n import lobby_i18n_catalog
|
||||
from .i18n import lobby_i18n_catalog, resolve_locale
|
||||
|
||||
|
||||
def _render_spa_shell(request, shell_route: str, shell_kind: str):
|
||||
@@ -18,6 +18,7 @@ def _render_spa_shell(request, shell_route: str, shell_kind: str):
|
||||
"spa_asset_base": settings.WPP_SPA_ASSET_BASE,
|
||||
"spa_asset_version": getattr(settings, "WPP_SPA_ASSET_VERSION", "dev"),
|
||||
"lobby_i18n": lobby_i18n_catalog(),
|
||||
"shell_locale": resolve_locale(request),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
134
lobby/views.py
134
lobby/views.py
@@ -61,6 +61,52 @@ def _create_unique_session_code() -> str:
|
||||
raise RuntimeError("Could not generate unique session code")
|
||||
|
||||
|
||||
def _build_player_ref(player: Player | None) -> dict | None:
|
||||
if player is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"player_id": player.id,
|
||||
"nickname": player.nickname,
|
||||
}
|
||||
|
||||
|
||||
def _build_reveal_payload(round_question: RoundQuestion | None) -> dict | None:
|
||||
if round_question is None:
|
||||
return None
|
||||
|
||||
lies = [
|
||||
{
|
||||
**_build_player_ref(lie.player),
|
||||
"text": lie.text,
|
||||
"created_at": lie.created_at.isoformat(),
|
||||
}
|
||||
for lie in round_question.lies.select_related("player").order_by("created_at", "id")
|
||||
]
|
||||
|
||||
guesses = []
|
||||
for guess in round_question.guesses.select_related("player", "fooled_player").order_by("created_at", "id"):
|
||||
guess_payload = {
|
||||
**_build_player_ref(guess.player),
|
||||
"selected_text": guess.selected_text,
|
||||
"is_correct": guess.is_correct,
|
||||
"created_at": guess.created_at.isoformat(),
|
||||
"fooled_player_id": guess.fooled_player_id,
|
||||
}
|
||||
if guess.fooled_player is not None:
|
||||
guess_payload["fooled_player_nickname"] = guess.fooled_player.nickname
|
||||
guesses.append(guess_payload)
|
||||
|
||||
return {
|
||||
"round_question_id": round_question.id,
|
||||
"round_number": round_question.round_number,
|
||||
"prompt": round_question.question.prompt,
|
||||
"correct_answer": round_question.correct_answer,
|
||||
"lies": lies,
|
||||
"guesses": guesses,
|
||||
}
|
||||
|
||||
|
||||
def _build_phase_view_model(session: GameSession, *, players_count: int, has_round_question: bool) -> dict:
|
||||
status = session.status
|
||||
in_lobby = status == GameSession.Status.LOBBY
|
||||
@@ -238,6 +284,9 @@ def session_detail(request: HttpRequest, code: str) -> JsonResponse:
|
||||
},
|
||||
"players": players,
|
||||
"round_question": round_question_payload,
|
||||
"reveal": _build_reveal_payload(current_round_question)
|
||||
if session.status == GameSession.Status.REVEAL and current_round_question
|
||||
else None,
|
||||
"phase_view_model": phase_view_model,
|
||||
}
|
||||
)
|
||||
@@ -268,7 +317,11 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can start round"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_start_round", "host_only_start_round"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LOBBY:
|
||||
return api_error(
|
||||
@@ -287,7 +340,11 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
)
|
||||
|
||||
if not Question.objects.filter(category=category, is_active=True).exists():
|
||||
return JsonResponse({"error": "Category has no active questions"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("category_has_no_questions", "category_has_no_questions"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
@@ -340,21 +397,41 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can show question"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_show_question", "host_only_show_question"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LIE:
|
||||
return JsonResponse({"error": "Question can only be shown in lie phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("show_question_invalid_phase", "show_question_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
round_config = RoundConfig.objects.get(session=session, number=session.current_round)
|
||||
except RoundConfig.DoesNotExist:
|
||||
return JsonResponse({"error": "Round config missing"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_config_missing", "round_config_missing"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
if RoundQuestion.objects.filter(session=session, round_number=session.current_round).exists():
|
||||
return JsonResponse({"error": "Question already shown for this round"}, status=409)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("question_already_shown", "question_already_shown"),
|
||||
status=409,
|
||||
)
|
||||
|
||||
used_question_ids = RoundQuestion.objects.filter(session=session).values_list("question_id", flat=True)
|
||||
available_questions = Question.objects.filter(
|
||||
@@ -363,7 +440,11 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
).exclude(pk__in=used_question_ids)
|
||||
|
||||
if not available_questions.exists():
|
||||
return JsonResponse({"error": "No available questions in category"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("no_available_questions", "no_available_questions"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
question = random.choice(list(available_questions))
|
||||
round_question = RoundQuestion.objects.create(
|
||||
@@ -473,13 +554,25 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can mix answers"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_mix_answers", "host_only_mix_answers"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return JsonResponse({"error": "Answers can only be mixed in lie or guess phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
round_question = RoundQuestion.objects.get(
|
||||
@@ -488,12 +581,20 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
round_number=session.current_round,
|
||||
)
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return JsonResponse({"error": "Round question not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_question_not_found", "round_question_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return JsonResponse({"error": "Answers can only be mixed in lie or guess phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
locked_round_question = RoundQuestion.objects.select_for_update().get(pk=round_question.pk)
|
||||
|
||||
@@ -509,7 +610,11 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
deduped_answers.append(text.strip())
|
||||
|
||||
if len(deduped_answers) < 2:
|
||||
return JsonResponse({"error": "Not enough answers to mix"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("not_enough_answers_to_mix", "not_enough_answers_to_mix"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
random.shuffle(deduped_answers)
|
||||
locked_round_question.mixed_answers = deduped_answers
|
||||
@@ -853,6 +958,7 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
"id": round_question.id,
|
||||
"round_number": round_question.round_number,
|
||||
},
|
||||
"reveal": _build_reveal_payload(round_question),
|
||||
"events_created": len(score_events),
|
||||
"leaderboard": leaderboard,
|
||||
}
|
||||
|
||||
30
partyhub/i18n_bootstrap.py
Normal file
30
partyhub/i18n_bootstrap.py
Normal file
@@ -0,0 +1,30 @@
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
_LOCALE_LABELS = {
|
||||
"en": "English",
|
||||
"da": "Danish",
|
||||
}
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def shared_i18n_catalog() -> dict:
|
||||
catalog_path = Path(__file__).resolve().parents[1] / "shared" / "i18n" / "lobby.json"
|
||||
with catalog_path.open(encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def locale_config() -> tuple[str, tuple[str, ...]]:
|
||||
locales = shared_i18n_catalog().get("locales", {})
|
||||
default_locale = str(locales.get("default", "en")).strip().lower() or "en"
|
||||
supported_locales = tuple(
|
||||
locale.strip().lower() for locale in locales.get("supported", ["en", "da"]) if str(locale).strip()
|
||||
) or ("en", "da")
|
||||
return default_locale, supported_locales
|
||||
|
||||
|
||||
def django_languages() -> list[tuple[str, str]]:
|
||||
_default_locale, supported_locales = locale_config()
|
||||
return [(locale, _LOCALE_LABELS.get(locale, locale.upper())) for locale in supported_locales]
|
||||
@@ -1,6 +1,8 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
from partyhub.i18n_bootstrap import django_languages, locale_config
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
@@ -90,11 +92,8 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
|
||||
]
|
||||
|
||||
LANGUAGE_CODE = 'en'
|
||||
LANGUAGES = [
|
||||
('en', 'English'),
|
||||
('da', 'Danish'),
|
||||
]
|
||||
LANGUAGE_CODE, _SUPPORTED_LOCALES = locale_config()
|
||||
LANGUAGES = django_languages()
|
||||
LOCALE_PATHS = [BASE_DIR / 'locale']
|
||||
TIME_ZONE = 'Europe/Copenhagen'
|
||||
USE_I18N = True
|
||||
|
||||
28
partyhub/tests_i18n_bootstrap.py
Normal file
28
partyhub/tests_i18n_bootstrap.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
|
||||
from partyhub.i18n_bootstrap import django_languages, locale_config, shared_i18n_catalog
|
||||
|
||||
|
||||
class I18nBootstrapTests(TestCase):
|
||||
def test_shared_catalog_bootstraps_default_and_supported_locales(self):
|
||||
default_locale, supported_locales = locale_config()
|
||||
|
||||
self.assertEqual(default_locale, "en")
|
||||
self.assertEqual(supported_locales, ("en", "da"))
|
||||
|
||||
def test_django_language_settings_bootstrap_from_shared_i18n_catalog(self):
|
||||
default_locale, supported_locales = locale_config()
|
||||
|
||||
self.assertEqual(settings.LANGUAGE_CODE, default_locale)
|
||||
self.assertEqual(tuple(code for code, _ in settings.LANGUAGES), supported_locales)
|
||||
self.assertEqual(settings.LANGUAGES, django_languages())
|
||||
|
||||
def test_locale_contract_in_catalog_matches_django_language_codes(self):
|
||||
catalog_locales = shared_i18n_catalog()["locales"]
|
||||
|
||||
self.assertEqual(settings.LANGUAGE_CODE, catalog_locales["default"])
|
||||
self.assertEqual(
|
||||
[code for code, _ in settings.LANGUAGES],
|
||||
catalog_locales["supported"],
|
||||
)
|
||||
214
scripts/build_i18n_parity_report.py
Normal file
214
scripts/build_i18n_parity_report.py
Normal file
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the shared i18n parity artifact for MVP-critical Django/Angular keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
ARTIFACT_PATH = REPO_ROOT / "shared" / "i18n" / "artifacts" / "lobby-mvp-keyspace-parity-report.v1.json"
|
||||
DJANGO_VIEWS_PATH = REPO_ROOT / "lobby" / "views.py"
|
||||
FRONTEND_VERTICAL_SLICE_PATH = REPO_ROOT / "frontend" / "src" / "spa" / "vertical-slice.ts"
|
||||
ANGULAR_I18N_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "lobby-i18n.ts"
|
||||
ANGULAR_HOST_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "features" / "host" / "host-shell.component.ts"
|
||||
ANGULAR_PLAYER_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "features" / "player" / "player-shell.component.ts"
|
||||
|
||||
ARTIFACT_NAME = "shared.i18n.lobby.mvp_keyspace_parity_report"
|
||||
ARTIFACT_VERSION = "v1"
|
||||
|
||||
|
||||
class ParityError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _read_text(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _load_catalog() -> dict[str, Any]:
|
||||
return json.loads(_read_text(CATALOG_PATH))
|
||||
|
||||
|
||||
def _catalog_hash() -> str:
|
||||
return hashlib.sha256(CATALOG_PATH.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _sorted_unique(values: list[str]) -> list[str]:
|
||||
return sorted({value for value in values})
|
||||
|
||||
|
||||
def _extract_matches(path: Path, pattern: str) -> list[str]:
|
||||
return re.findall(pattern, _read_text(path), re.MULTILINE)
|
||||
|
||||
|
||||
def _resolve_frontend_ui_key(key: str) -> str:
|
||||
if key.startswith("lobby.shell."):
|
||||
return key.replace("lobby.shell.", "app.", 1)
|
||||
if key.startswith("game.host."):
|
||||
return key.replace("game.host.", "host.", 1)
|
||||
if key.startswith("game.player."):
|
||||
return key.replace("game.player.", "player.", 1)
|
||||
return key
|
||||
|
||||
|
||||
def _has_nested_key(root: dict[str, Any], dotted_key: str) -> bool:
|
||||
current: Any = root
|
||||
for part in dotted_key.split("."):
|
||||
if not isinstance(current, dict) or part not in current:
|
||||
return False
|
||||
current = current[part]
|
||||
return isinstance(current, dict)
|
||||
|
||||
|
||||
def build_report() -> dict[str, Any]:
|
||||
catalog = _load_catalog()
|
||||
locales = list(catalog["locales"]["supported"])
|
||||
frontend_errors: dict[str, Any] = catalog["frontend"]["errors"]
|
||||
frontend_ui: dict[str, Any] = catalog["frontend"]["ui"]
|
||||
backend_error_codes: dict[str, str] = catalog["backend"]["error_codes"]
|
||||
backend_errors: dict[str, Any] = catalog["backend"]["errors"]
|
||||
backend_to_frontend: dict[str, str] = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
|
||||
django_error_codes = _sorted_unique(
|
||||
_extract_matches(DJANGO_VIEWS_PATH, r'ERROR_CODES\.get\("([a-z0-9_]+)"')
|
||||
)
|
||||
frontend_runtime_error_fallbacks = _sorted_unique(
|
||||
_extract_matches(FRONTEND_VERTICAL_SLICE_PATH, r"lobbyMessageFromApiPayload\([^\n]+?'([a-z0-9_]+)'\)")
|
||||
+ _extract_matches(FRONTEND_VERTICAL_SLICE_PATH, r"lobbyMessage\('([a-z0-9_]+)'\)")
|
||||
)
|
||||
angular_copy_keys = _sorted_unique(
|
||||
_extract_matches(ANGULAR_HOST_PATH, r"copy\('([A-Za-z0-9_\.]+)'\)")
|
||||
+ _extract_matches(ANGULAR_PLAYER_PATH, r"copy\('([A-Za-z0-9_\.]+)'\)")
|
||||
)
|
||||
angular_catalog_paths = [_resolve_frontend_ui_key(key) for key in angular_copy_keys]
|
||||
|
||||
missing_backend_codes = [code for code in django_error_codes if code not in backend_error_codes]
|
||||
missing_backend_translations = [code for code in django_error_codes if code not in backend_errors]
|
||||
missing_contract_mappings = [code for code in django_error_codes if code not in backend_to_frontend]
|
||||
mapped_frontend_error_keys = _sorted_unique(
|
||||
[backend_to_frontend[code] for code in django_error_codes if code in backend_to_frontend]
|
||||
)
|
||||
missing_frontend_error_keys = [key for key in mapped_frontend_error_keys if key not in frontend_errors]
|
||||
missing_frontend_runtime_fallbacks = [key for key in frontend_runtime_error_fallbacks if key not in frontend_errors]
|
||||
missing_angular_catalog_paths = [path for path in angular_catalog_paths if not _has_nested_key(frontend_ui, path)]
|
||||
|
||||
dead_contract_aliases = _sorted_unique([code for code in backend_to_frontend if code not in backend_error_codes])
|
||||
many_to_one_mappings: dict[str, list[str]] = defaultdict(list)
|
||||
for code in django_error_codes:
|
||||
frontend_key = backend_to_frontend.get(code)
|
||||
if frontend_key:
|
||||
many_to_one_mappings[frontend_key].append(code)
|
||||
many_to_one_mappings = {
|
||||
frontend_key: sorted(codes)
|
||||
for frontend_key, codes in sorted(many_to_one_mappings.items())
|
||||
if len(codes) > 1
|
||||
}
|
||||
|
||||
blocking_issues = {
|
||||
"missing_backend_codes": missing_backend_codes,
|
||||
"missing_backend_translations": missing_backend_translations,
|
||||
"missing_contract_mappings": missing_contract_mappings,
|
||||
"missing_frontend_error_keys": missing_frontend_error_keys,
|
||||
"missing_frontend_runtime_fallbacks": missing_frontend_runtime_fallbacks,
|
||||
"missing_angular_catalog_paths": missing_angular_catalog_paths,
|
||||
}
|
||||
status = "pass" if not any(blocking_issues.values()) else "fail"
|
||||
|
||||
follow_ups: list[dict[str, str]] = []
|
||||
if dead_contract_aliases:
|
||||
follow_ups.append(
|
||||
{
|
||||
"priority": "need-to-have",
|
||||
"item": "Either add missing backend/error_codes + backend/errors entries for dead contract aliases or remove them from contract.backend_to_frontend_error_keys.",
|
||||
"evidence": ", ".join(dead_contract_aliases),
|
||||
}
|
||||
)
|
||||
if many_to_one_mappings:
|
||||
follow_ups.append(
|
||||
{
|
||||
"priority": "nice-to-have",
|
||||
"item": "Decide whether grouped backend codes should keep collapsing into one Angular fallback key or be split into more specific frontend error copy as UX matures.",
|
||||
"evidence": "; ".join(
|
||||
f"{frontend_key} <= {', '.join(codes)}" for frontend_key, codes in many_to_one_mappings.items()
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"artifact_name": ARTIFACT_NAME,
|
||||
"artifact_version": ARTIFACT_VERSION,
|
||||
"naming_version_rule": "Keep a stable artifact_name and append only explicit schema-major suffixes to the filename/version (v1, v2, ...). Update artifact_version only when the report shape changes; refresh content in-place for catalog/keyspace changes.",
|
||||
"source_of_truth": {
|
||||
"catalog": str(CATALOG_PATH.relative_to(REPO_ROOT)),
|
||||
"catalog_sha256": _catalog_hash(),
|
||||
"source_paths": [
|
||||
str(path.relative_to(REPO_ROOT))
|
||||
for path in [
|
||||
DJANGO_VIEWS_PATH,
|
||||
FRONTEND_VERTICAL_SLICE_PATH,
|
||||
ANGULAR_I18N_PATH,
|
||||
ANGULAR_HOST_PATH,
|
||||
ANGULAR_PLAYER_PATH,
|
||||
]
|
||||
],
|
||||
},
|
||||
"scope": {
|
||||
"issue": 277,
|
||||
"related_epic": 175,
|
||||
"mvp_locales": locales,
|
||||
"definition": "MVP-critical keys are the Django error codes emitted by lobby/views.py plus the Angular fallback/UI keys consumed by the host/player MVP shells.",
|
||||
},
|
||||
"parity": {
|
||||
"status": status,
|
||||
"django_backend_error_codes_used_by_mvp": django_error_codes,
|
||||
"angular_frontend_error_fallback_keys_used_by_mvp": frontend_runtime_error_fallbacks,
|
||||
"angular_ui_keys_used_by_mvp": angular_copy_keys,
|
||||
"angular_ui_catalog_paths": angular_catalog_paths,
|
||||
"backend_codes_mapped_to_frontend_error_keys": {code: backend_to_frontend[code] for code in django_error_codes if code in backend_to_frontend},
|
||||
"unique_frontend_error_keys_reached_from_django": mapped_frontend_error_keys,
|
||||
"blocking_issues": blocking_issues,
|
||||
"follow_ups": follow_ups,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_report() -> None:
|
||||
report = build_report()
|
||||
ARTIFACT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
ARTIFACT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def check_report() -> None:
|
||||
report = build_report()
|
||||
if not ARTIFACT_PATH.exists():
|
||||
raise ParityError(f"artifact missing: {ARTIFACT_PATH}")
|
||||
existing = json.loads(_read_text(ARTIFACT_PATH))
|
||||
if existing != report:
|
||||
raise ParityError("artifact out of date; run scripts/build_i18n_parity_report.py --write")
|
||||
if report["parity"]["status"] != "pass":
|
||||
raise ParityError(json.dumps(report["parity"]["blocking_issues"], indent=2))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--write", action="store_true")
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.write:
|
||||
write_report()
|
||||
if args.check:
|
||||
check_report()
|
||||
if not args.write and not args.check:
|
||||
print(json.dumps(build_report(), indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
132
scripts/check_i18n_drift.py
Executable file
132
scripts/check_i18n_drift.py
Executable file
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only drift check for shared i18n key coverage.
|
||||
|
||||
Compares `shared/i18n/key-manifest.json` against `shared/i18n/lobby.json` and
|
||||
fails fast when keyspaces drift between frontend/backend contract sections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
MANIFEST_PATH = REPO_ROOT / "shared" / "i18n" / "key-manifest.json"
|
||||
|
||||
|
||||
def _load_json(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
def _as_set(value: Any) -> set[str]:
|
||||
if not isinstance(value, list):
|
||||
return set()
|
||||
return {str(item) for item in value}
|
||||
|
||||
|
||||
def _require_translations(
|
||||
errors: dict[str, Any],
|
||||
locales: set[str],
|
||||
label: str,
|
||||
failures: list[str],
|
||||
) -> None:
|
||||
for key, translations in errors.items():
|
||||
if not isinstance(translations, dict):
|
||||
failures.append(f"{label}.{key} must be an object of locale->message")
|
||||
continue
|
||||
|
||||
for locale in sorted(locales):
|
||||
value = translations.get(locale)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
failures.append(f"{label}.{key} missing non-empty '{locale}' translation")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
catalog = _load_json(CATALOG_PATH)
|
||||
manifest = _load_json(MANIFEST_PATH)
|
||||
|
||||
failures: list[str] = []
|
||||
|
||||
manifest_locales = _as_set(manifest.get("locales"))
|
||||
catalog_locales = _as_set(catalog.get("locales", {}).get("supported"))
|
||||
if manifest_locales != catalog_locales:
|
||||
failures.append(
|
||||
"locale set mismatch: "
|
||||
f"manifest={sorted(manifest_locales)} catalog={sorted(catalog_locales)}"
|
||||
)
|
||||
|
||||
frontend_manifest = _as_set(manifest.get("frontend_error_keys"))
|
||||
frontend_catalog = set(catalog.get("frontend", {}).get("errors", {}).keys())
|
||||
if frontend_manifest != frontend_catalog:
|
||||
failures.append(
|
||||
"frontend error key mismatch: "
|
||||
f"manifest-only={sorted(frontend_manifest - frontend_catalog)} "
|
||||
f"catalog-only={sorted(frontend_catalog - frontend_manifest)}"
|
||||
)
|
||||
|
||||
backend_code_manifest = _as_set(manifest.get("backend_error_codes"))
|
||||
backend_code_catalog = set(catalog.get("backend", {}).get("error_codes", {}).keys())
|
||||
if backend_code_manifest != backend_code_catalog:
|
||||
failures.append(
|
||||
"backend error code mismatch: "
|
||||
f"manifest-only={sorted(backend_code_manifest - backend_code_catalog)} "
|
||||
f"catalog-only={sorted(backend_code_catalog - backend_code_manifest)}"
|
||||
)
|
||||
|
||||
backend_key_manifest = _as_set(manifest.get("backend_error_keys"))
|
||||
backend_key_catalog = set(catalog.get("backend", {}).get("errors", {}).keys())
|
||||
if backend_key_manifest != backend_key_catalog:
|
||||
failures.append(
|
||||
"backend error key mismatch: "
|
||||
f"manifest-only={sorted(backend_key_manifest - backend_key_catalog)} "
|
||||
f"catalog-only={sorted(backend_key_catalog - backend_key_manifest)}"
|
||||
)
|
||||
|
||||
backend_to_frontend = catalog.get("contract", {}).get("backend_to_frontend_error_keys", {})
|
||||
if not isinstance(backend_to_frontend, dict):
|
||||
failures.append("contract.backend_to_frontend_error_keys must be an object")
|
||||
backend_to_frontend = {}
|
||||
|
||||
for code in sorted(backend_code_catalog):
|
||||
frontend_key = backend_to_frontend.get(code)
|
||||
if frontend_key is None:
|
||||
failures.append(f"missing contract mapping for backend code '{code}'")
|
||||
continue
|
||||
if frontend_key not in frontend_catalog:
|
||||
failures.append(
|
||||
f"mapping for backend code '{code}' points to unknown frontend key '{frontend_key}'"
|
||||
)
|
||||
|
||||
allowed_contract_only_codes = _as_set(manifest.get("allowed_contract_only_backend_codes"))
|
||||
unknown_mapping_codes = set(backend_to_frontend.keys()) - backend_code_catalog
|
||||
disallowed_unknown_mapping_codes = unknown_mapping_codes - allowed_contract_only_codes
|
||||
if disallowed_unknown_mapping_codes:
|
||||
failures.append(
|
||||
"contract contains mappings for unknown backend codes: "
|
||||
f"{sorted(disallowed_unknown_mapping_codes)}"
|
||||
)
|
||||
|
||||
_require_translations(catalog.get("frontend", {}).get("errors", {}), manifest_locales, "frontend.errors", failures)
|
||||
_require_translations(catalog.get("backend", {}).get("errors", {}), manifest_locales, "backend.errors", failures)
|
||||
|
||||
if failures:
|
||||
print("i18n drift check FAILED")
|
||||
for failure in failures:
|
||||
print(f" - {failure}")
|
||||
return 1
|
||||
|
||||
print("i18n drift check OK")
|
||||
print(f" - locales: {sorted(manifest_locales)}")
|
||||
print(f" - frontend error keys: {len(frontend_catalog)}")
|
||||
print(f" - backend error codes: {len(backend_code_catalog)}")
|
||||
print(f" - backend error keys: {len(backend_key_catalog)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
36
scripts/check_i18n_parity_artifact.py
Normal file
36
scripts/check_i18n_parity_artifact.py
Normal file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Guard issue #277 parity artifact against non-deterministic regeneration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
ARTIFACT_PATH = REPO_ROOT / "docs" / "ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md"
|
||||
REPORT_SCRIPT = REPO_ROOT / "scripts" / "report_i18n_parity.py"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
before = sha256(ARTIFACT_PATH)
|
||||
|
||||
for run in range(1, 3):
|
||||
subprocess.run([sys.executable, str(REPORT_SCRIPT)], cwd=REPO_ROOT, check=True)
|
||||
after = sha256(ARTIFACT_PATH)
|
||||
if after != before:
|
||||
raise SystemExit(
|
||||
f"issue #277 parity artifact is not deterministic after run {run}: {before} != {after}"
|
||||
)
|
||||
|
||||
print(f"issue #277 parity artifact deterministic: {before}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
196
scripts/report_i18n_parity.py
Normal file
196
scripts/report_i18n_parity.py
Normal file
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate issue #277 shared i18n parity artifact.
|
||||
|
||||
Read-only report over the shared lobby i18n catalog, with focus on MVP-critical
|
||||
backend/frontend parity used by Django and Angular.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
OUTPUT_PATH = REPO_ROOT / "docs" / "ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md"
|
||||
ARTIFACT_ID = "issue-277-shared-i18n-parity-report"
|
||||
ARTIFACT_VERSION = "1.0"
|
||||
|
||||
MVP_FRONTEND_UI_KEYS = [
|
||||
"frontend.ui.host.title",
|
||||
"frontend.ui.player.title",
|
||||
"frontend.ui.common.session_code",
|
||||
"frontend.ui.player.nickname",
|
||||
"frontend.ui.player.join",
|
||||
"frontend.ui.host.start_round",
|
||||
"frontend.ui.host.show_question",
|
||||
"frontend.ui.player.lie_label",
|
||||
"frontend.ui.player.submit_lie",
|
||||
"frontend.ui.player.submit_guess",
|
||||
"frontend.ui.host.mix_answers",
|
||||
"frontend.ui.host.calculate_scores",
|
||||
"frontend.ui.host.load_scoreboard",
|
||||
"frontend.ui.host.final_leaderboard",
|
||||
"frontend.ui.player.final_leaderboard",
|
||||
"frontend.ui.common.points_short",
|
||||
]
|
||||
|
||||
MVP_FRONTEND_ERROR_KEYS = [
|
||||
"frontend.errors.session_code_required",
|
||||
"frontend.errors.session_not_found",
|
||||
"frontend.errors.nickname_invalid",
|
||||
"frontend.errors.nickname_taken",
|
||||
"frontend.errors.join_failed",
|
||||
"frontend.errors.start_round_failed",
|
||||
"frontend.errors.unknown",
|
||||
]
|
||||
|
||||
MVP_BACKEND_CODES = [
|
||||
"backend.error_codes.session_code_required",
|
||||
"backend.error_codes.nickname_invalid",
|
||||
"backend.error_codes.session_not_found",
|
||||
"backend.error_codes.session_not_joinable",
|
||||
"backend.error_codes.nickname_taken",
|
||||
"backend.error_codes.category_slug_required",
|
||||
"backend.error_codes.category_not_found",
|
||||
"backend.error_codes.round_start_invalid_phase",
|
||||
"backend.error_codes.round_already_configured",
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MappingRow:
|
||||
backend_code: str
|
||||
backend_key: str
|
||||
frontend_key: str
|
||||
locales_ok: bool
|
||||
parity_status: str
|
||||
note: str
|
||||
|
||||
|
||||
def load_catalog() -> dict:
|
||||
return json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def get_path(data: dict, dotted: str):
|
||||
node = data
|
||||
for part in dotted.split("."):
|
||||
node = node[part]
|
||||
return node
|
||||
|
||||
|
||||
def translation_state(data: dict, dotted: str) -> tuple[bool, list[str]]:
|
||||
translations = get_path(data, dotted)
|
||||
missing = [locale for locale in ("en", "da") if not isinstance(translations.get(locale), str) or not translations[locale].strip()]
|
||||
return (not missing, missing)
|
||||
|
||||
|
||||
def build_mapping_rows(catalog: dict) -> list[MappingRow]:
|
||||
rows: list[MappingRow] = []
|
||||
mapping = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
backend_errors = catalog["backend"]["errors"]
|
||||
|
||||
for dotted_code in MVP_BACKEND_CODES:
|
||||
code = dotted_code.removeprefix("backend.error_codes.")
|
||||
backend_key = catalog["backend"]["error_codes"][code]
|
||||
frontend_key = mapping[code]
|
||||
backend_locales_ok, _ = translation_state(catalog, f"backend.errors.{backend_key}")
|
||||
frontend_locales_ok, _ = translation_state(catalog, f"frontend.errors.{frontend_key}")
|
||||
note = "1:1" if code == frontend_key else "many:1 collapse" if frontend_key == "start_round_failed" else "mapped alias"
|
||||
rows.append(
|
||||
MappingRow(
|
||||
backend_code=code,
|
||||
backend_key=backend_key,
|
||||
frontend_key=frontend_key,
|
||||
locales_ok=backend_locales_ok and frontend_locales_ok,
|
||||
parity_status="aligned" if frontend_key in backend_errors or code == frontend_key else "mapped",
|
||||
note=note,
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def render_report(catalog: dict) -> str:
|
||||
mapping_rows = build_mapping_rows(catalog)
|
||||
frontend_ui_ok = all(translation_state(catalog, key)[0] for key in MVP_FRONTEND_UI_KEYS)
|
||||
frontend_error_ok = all(translation_state(catalog, key)[0] for key in MVP_FRONTEND_ERROR_KEYS)
|
||||
backend_code_ok = all(translation_state(catalog, f"backend.errors.{catalog['backend']['error_codes'][key.removeprefix('backend.error_codes.')]}" )[0] for key in MVP_BACKEND_CODES)
|
||||
mapped_frontend_keys = sorted({row.frontend_key for row in mapping_rows})
|
||||
collapsed_codes = [row.backend_code for row in mapping_rows if row.frontend_key == "start_round_failed"]
|
||||
|
||||
lines: list[str] = []
|
||||
lines.append("# ISSUE-277 Artifact — shared i18n registry parity report (Django ↔ Angular MVP)")
|
||||
lines.append("")
|
||||
lines.append("Issue: **#277** (`[READY][#175][P3] Shared i18n registry artifact: backend/frontend keyspace parity report`)")
|
||||
lines.append("")
|
||||
lines.append("## Artifact metadata")
|
||||
lines.append("")
|
||||
lines.append(f"- `artifact_id`: `{ARTIFACT_ID}`")
|
||||
lines.append(f"- `artifact_version`: `{ARTIFACT_VERSION}`")
|
||||
lines.append(f"- `catalog_source`: `{CATALOG_PATH.relative_to(REPO_ROOT)}`")
|
||||
lines.append(f"- `generator`: `scripts/{Path(__file__).name}`")
|
||||
lines.append("")
|
||||
lines.append("## Naming/version rules (email-manager-inspired strategy)")
|
||||
lines.append("")
|
||||
lines.append("- **Single canonical artifact per issue**: issue-bundne rapporter navngives `docs/ISSUE-<nr>-<slug>-ARTIFACT.md`.")
|
||||
lines.append("- **Stable artifact identity**: `artifact_id` ændres ikke ved tekstlige opdateringer i samme rapporttype; det er den faste reference i review/ops.")
|
||||
lines.append("- **Explicit artifact versioning**: `artifact_version` bumpes, når rapportlogik eller scope ændres, så drift/review kan se forskel på format- vs. dataændringer.")
|
||||
lines.append("- **Shared namespace first**: keys refereres med fulde navnerum (`frontend.ui.*`, `frontend.errors.*`, `backend.error_codes.*`, `backend.errors.*`) i stedet for lokale aliases i artefakter.")
|
||||
lines.append("- **Source-of-truth before consumers**: rapporten afledes fra `shared/i18n/lobby.json`; Django/Angular beskrives som consumers af samme registry og ikke som parallelle kontrakter.")
|
||||
lines.append("")
|
||||
lines.append("## MVP-critical parity summary")
|
||||
lines.append("")
|
||||
lines.append(f"- Frontend UI gameplay keys checked: **{len(MVP_FRONTEND_UI_KEYS)}** → `{'OK' if frontend_ui_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Frontend error keys checked: **{len(MVP_FRONTEND_ERROR_KEYS)}** → `{'OK' if frontend_error_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Backend gameplay/error codes checked: **{len(MVP_BACKEND_CODES)}** → `{'OK' if backend_code_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Distinct frontend error keys reached from backend MVP flow: **{len(mapped_frontend_keys)}** (`{', '.join(mapped_frontend_keys)}`)")
|
||||
lines.append("")
|
||||
lines.append("Status: **Shared locale matrix is aligned (`en`, `da`) and backend→frontend error handling is contract-complete for MVP-critical flow.**")
|
||||
lines.append("")
|
||||
lines.append("## Django ↔ Angular parity matrix (MVP-critical error contract)")
|
||||
lines.append("")
|
||||
lines.append("| Backend code (`backend.error_codes.*`) | Django message key (`backend.errors.*`) | Angular key (`frontend.errors.*`) | Locales `en/da` | Parity note |")
|
||||
lines.append("|---|---|---|---|---|")
|
||||
for row in mapping_rows:
|
||||
lines.append(
|
||||
f"| `{row.backend_code}` | `{row.backend_key}` | `{row.frontend_key}` | `{'OK' if row.locales_ok else 'DRIFT'}` | {row.note} |"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("## Scope notes")
|
||||
lines.append("")
|
||||
lines.append("- **Django** consumes backend codes/messages directly from `shared/i18n/lobby.json` via `lobby/i18n.py`.")
|
||||
lines.append("- **Angular** consumes the same registry via `frontend/shared/i18n/lobby-loader.ts` and runtime helpers in `frontend/angular/src/app/lobby-i18n.ts`.")
|
||||
lines.append("- **Parity in MVP** is therefore strongest on the shared error contract and locale matrix; gameplay UI labels are frontend-owned but still live in the same registry.")
|
||||
lines.append("")
|
||||
lines.append("## Verified MVP gameplay UI keyspace present in the shared registry")
|
||||
lines.append("")
|
||||
for key in MVP_FRONTEND_UI_KEYS:
|
||||
lines.append(f"- `{key}`")
|
||||
lines.append("")
|
||||
lines.append("## Concrete deviations / follow-up items")
|
||||
lines.append("")
|
||||
lines.append(f"1. **Error granularity collapse remains intentional**: backend codes `{', '.join(collapsed_codes)}` all map to `frontend.errors.start_round_failed`. Follow-up only if product wants case-specific Angular copy instead of one shared host failure message.")
|
||||
lines.append("2. **Frontend-only fallback copy is not mirrored in Django**: `frontend.errors.unknown` and `frontend.errors.session_fetch_failed` are Angular-side resilience keys, not backend contract keys. Follow-up if API responses should expose stable backend equivalents for these states.")
|
||||
lines.append("3. **Gameplay UI labels are registry-shared but not backend-rendered**: `frontend.ui.host.*`, `frontend.ui.player.*`, and `frontend.ui.common.*` are available in the shared artifact, but Django currently consumes only the backend error slice. Follow-up only if server-rendered views must guarantee the same UI label surface as Angular.")
|
||||
lines.append("")
|
||||
lines.append("## Re-run")
|
||||
lines.append("")
|
||||
lines.append("```bash")
|
||||
lines.append("python3 scripts/check_i18n_drift.py")
|
||||
lines.append("python3 scripts/report_i18n_parity.py")
|
||||
lines.append("python3 scripts/check_i18n_parity_artifact.py")
|
||||
lines.append("```")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
catalog = load_catalog()
|
||||
OUTPUT_PATH.write_text(render_report(catalog), encoding="utf-8")
|
||||
print(OUTPUT_PATH.relative_to(REPO_ROOT))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
212
shared/i18n/artifacts/lobby-mvp-keyspace-parity-report.v1.json
Normal file
212
shared/i18n/artifacts/lobby-mvp-keyspace-parity-report.v1.json
Normal file
@@ -0,0 +1,212 @@
|
||||
{
|
||||
"artifact_name": "shared.i18n.lobby.mvp_keyspace_parity_report",
|
||||
"artifact_version": "v1",
|
||||
"naming_version_rule": "Keep a stable artifact_name and append only explicit schema-major suffixes to the filename/version (v1, v2, ...). Update artifact_version only when the report shape changes; refresh content in-place for catalog/keyspace changes.",
|
||||
"source_of_truth": {
|
||||
"catalog": "shared/i18n/lobby.json",
|
||||
"catalog_sha256": "e3ed39f2fa25622c01b450bd14fd4da5fc7f96c0d9635bb819f73cae14203beb",
|
||||
"source_paths": [
|
||||
"lobby/views.py",
|
||||
"frontend/src/spa/vertical-slice.ts",
|
||||
"frontend/angular/src/app/lobby-i18n.ts",
|
||||
"frontend/angular/src/app/features/host/host-shell.component.ts",
|
||||
"frontend/angular/src/app/features/player/player-shell.component.ts"
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"issue": 277,
|
||||
"related_epic": 175,
|
||||
"mvp_locales": [
|
||||
"en",
|
||||
"da"
|
||||
],
|
||||
"definition": "MVP-critical keys are the Django error codes emitted by lobby/views.py plus the Angular fallback/UI keys consumed by the host/player MVP shells."
|
||||
},
|
||||
"parity": {
|
||||
"status": "pass",
|
||||
"django_backend_error_codes_used_by_mvp": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
],
|
||||
"angular_frontend_error_fallback_keys_used_by_mvp": [
|
||||
"join_failed",
|
||||
"session_code_required",
|
||||
"session_fetch_failed",
|
||||
"start_round_failed"
|
||||
],
|
||||
"angular_ui_keys_used_by_mvp": [
|
||||
"common.back_to_join",
|
||||
"common.points_short",
|
||||
"common.prompt",
|
||||
"common.refresh",
|
||||
"common.retry",
|
||||
"common.round",
|
||||
"common.round_question_id",
|
||||
"common.session_code",
|
||||
"common.status",
|
||||
"common.unknown_error",
|
||||
"host.audio_locale_hint",
|
||||
"host.calculate_scores",
|
||||
"host.category",
|
||||
"host.final_leaderboard",
|
||||
"host.finish_game",
|
||||
"host.finish_game_failed",
|
||||
"host.load_scoreboard",
|
||||
"host.mix_answers",
|
||||
"host.next_round_failed",
|
||||
"host.retry_finish",
|
||||
"host.retry_next_round",
|
||||
"host.retry_scoreboard",
|
||||
"host.scoreboard_failed",
|
||||
"host.session_code_required",
|
||||
"host.session_refresh_failed",
|
||||
"host.show_question",
|
||||
"host.start_next_round",
|
||||
"host.start_round",
|
||||
"host.title",
|
||||
"host.winner",
|
||||
"player.audio_policy_notice",
|
||||
"player.final_leaderboard",
|
||||
"player.guess_submit_failed",
|
||||
"player.join",
|
||||
"player.join_failed",
|
||||
"player.lie_label",
|
||||
"player.lie_submit_failed",
|
||||
"player.loading_join",
|
||||
"player.loading_refresh",
|
||||
"player.loading_submit_guess",
|
||||
"player.loading_submit_lie",
|
||||
"player.nickname",
|
||||
"player.offline_text",
|
||||
"player.reconnecting_text",
|
||||
"player.retry_guess_submit",
|
||||
"player.retry_lie_submit",
|
||||
"player.retry_now",
|
||||
"player.session_refresh_failed",
|
||||
"player.submit_guess",
|
||||
"player.submit_lie",
|
||||
"player.title"
|
||||
],
|
||||
"angular_ui_catalog_paths": [
|
||||
"common.back_to_join",
|
||||
"common.points_short",
|
||||
"common.prompt",
|
||||
"common.refresh",
|
||||
"common.retry",
|
||||
"common.round",
|
||||
"common.round_question_id",
|
||||
"common.session_code",
|
||||
"common.status",
|
||||
"common.unknown_error",
|
||||
"host.audio_locale_hint",
|
||||
"host.calculate_scores",
|
||||
"host.category",
|
||||
"host.final_leaderboard",
|
||||
"host.finish_game",
|
||||
"host.finish_game_failed",
|
||||
"host.load_scoreboard",
|
||||
"host.mix_answers",
|
||||
"host.next_round_failed",
|
||||
"host.retry_finish",
|
||||
"host.retry_next_round",
|
||||
"host.retry_scoreboard",
|
||||
"host.scoreboard_failed",
|
||||
"host.session_code_required",
|
||||
"host.session_refresh_failed",
|
||||
"host.show_question",
|
||||
"host.start_next_round",
|
||||
"host.start_round",
|
||||
"host.title",
|
||||
"host.winner",
|
||||
"player.audio_policy_notice",
|
||||
"player.final_leaderboard",
|
||||
"player.guess_submit_failed",
|
||||
"player.join",
|
||||
"player.join_failed",
|
||||
"player.lie_label",
|
||||
"player.lie_submit_failed",
|
||||
"player.loading_join",
|
||||
"player.loading_refresh",
|
||||
"player.loading_submit_guess",
|
||||
"player.loading_submit_lie",
|
||||
"player.nickname",
|
||||
"player.offline_text",
|
||||
"player.reconnecting_text",
|
||||
"player.retry_guess_submit",
|
||||
"player.retry_lie_submit",
|
||||
"player.retry_now",
|
||||
"player.session_refresh_failed",
|
||||
"player.submit_guess",
|
||||
"player.submit_lie",
|
||||
"player.title"
|
||||
],
|
||||
"backend_codes_mapped_to_frontend_error_keys": {
|
||||
"category_has_no_questions": "start_round_failed",
|
||||
"category_not_found": "start_round_failed",
|
||||
"category_slug_required": "start_round_failed",
|
||||
"host_only_mix_answers": "start_round_failed",
|
||||
"host_only_show_question": "start_round_failed",
|
||||
"host_only_start_round": "start_round_failed",
|
||||
"mix_answers_invalid_phase": "start_round_failed",
|
||||
"nickname_invalid": "nickname_invalid",
|
||||
"nickname_taken": "nickname_taken",
|
||||
"no_available_questions": "start_round_failed",
|
||||
"not_enough_answers_to_mix": "start_round_failed",
|
||||
"question_already_shown": "start_round_failed",
|
||||
"round_already_configured": "start_round_failed",
|
||||
"round_config_missing": "start_round_failed",
|
||||
"round_question_not_found": "start_round_failed",
|
||||
"round_start_invalid_phase": "start_round_failed",
|
||||
"session_code_required": "session_code_required",
|
||||
"session_not_found": "session_not_found",
|
||||
"session_not_joinable": "join_failed",
|
||||
"show_question_invalid_phase": "start_round_failed"
|
||||
},
|
||||
"unique_frontend_error_keys_reached_from_django": [
|
||||
"join_failed",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"start_round_failed"
|
||||
],
|
||||
"blocking_issues": {
|
||||
"missing_backend_codes": [],
|
||||
"missing_backend_translations": [],
|
||||
"missing_contract_mappings": [],
|
||||
"missing_frontend_error_keys": [],
|
||||
"missing_frontend_runtime_fallbacks": [],
|
||||
"missing_angular_catalog_paths": []
|
||||
},
|
||||
"follow_ups": [
|
||||
{
|
||||
"priority": "need-to-have",
|
||||
"item": "Either add missing backend/error_codes + backend/errors entries for dead contract aliases or remove them from contract.backend_to_frontend_error_keys.",
|
||||
"evidence": "host_only_action"
|
||||
},
|
||||
{
|
||||
"priority": "nice-to-have",
|
||||
"item": "Decide whether grouped backend codes should keep collapsing into one Angular fallback key or be split into more specific frontend error copy as UX matures.",
|
||||
"evidence": "start_round_failed <= category_has_no_questions, category_not_found, category_slug_required, host_only_mix_answers, host_only_show_question, host_only_start_round, mix_answers_invalid_phase, no_available_questions, not_enough_answers_to_mix, question_already_shown, round_already_configured, round_config_missing, round_question_not_found, round_start_invalid_phase, show_question_invalid_phase"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
60
shared/i18n/key-manifest.json
Normal file
60
shared/i18n/key-manifest.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"locales": ["en", "da"],
|
||||
"frontend_error_keys": [
|
||||
"join_failed",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"session_code_required",
|
||||
"session_fetch_failed",
|
||||
"session_not_found",
|
||||
"start_round_failed",
|
||||
"unknown"
|
||||
],
|
||||
"backend_error_codes": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
],
|
||||
"allowed_contract_only_backend_codes": [
|
||||
"host_only_action"
|
||||
],
|
||||
"backend_error_keys": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
]
|
||||
}
|
||||
@@ -74,6 +74,14 @@
|
||||
"round": {
|
||||
"en": "round",
|
||||
"da": "runde"
|
||||
},
|
||||
"points_short": {
|
||||
"en": "pts",
|
||||
"da": "point"
|
||||
},
|
||||
"unknown_error": {
|
||||
"en": "Unknown error",
|
||||
"da": "Ukendt fejl"
|
||||
}
|
||||
},
|
||||
"app": {
|
||||
@@ -256,6 +264,10 @@
|
||||
"guess_submit_failed": {
|
||||
"en": "Guess submit failed",
|
||||
"da": "Gætte-fejl"
|
||||
},
|
||||
"audio_policy_notice": {
|
||||
"en": "Audio playback is disabled on phone clients. Sound is available on the primary host device.",
|
||||
"da": "Lydafspilning er slået fra på telefon-klienten. Lyd afspilles kun på den primære værtsenhed."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -273,7 +285,18 @@
|
||||
"category_slug_required": "category_slug_required",
|
||||
"category_not_found": "category_not_found",
|
||||
"round_start_invalid_phase": "round_start_invalid_phase",
|
||||
"round_already_configured": "round_already_configured"
|
||||
"round_already_configured": "round_already_configured",
|
||||
"category_has_no_questions": "category_has_no_questions",
|
||||
"show_question_invalid_phase": "show_question_invalid_phase",
|
||||
"round_config_missing": "round_config_missing",
|
||||
"question_already_shown": "question_already_shown",
|
||||
"no_available_questions": "no_available_questions",
|
||||
"mix_answers_invalid_phase": "mix_answers_invalid_phase",
|
||||
"round_question_not_found": "round_question_not_found",
|
||||
"not_enough_answers_to_mix": "not_enough_answers_to_mix",
|
||||
"host_only_start_round": "host_only_start_round",
|
||||
"host_only_show_question": "host_only_show_question",
|
||||
"host_only_mix_answers": "host_only_mix_answers"
|
||||
},
|
||||
"errors": {
|
||||
"session_code_required": {
|
||||
@@ -311,7 +334,89 @@
|
||||
"round_already_configured": {
|
||||
"en": "Round already configured",
|
||||
"da": "Runden er allerede konfigureret"
|
||||
},
|
||||
"category_has_no_questions": {
|
||||
"en": "Category has no active questions",
|
||||
"da": "Kategorien har ingen aktive spørgsmål"
|
||||
},
|
||||
"show_question_invalid_phase": {
|
||||
"en": "Question can only be shown in lie phase",
|
||||
"da": "Spørgsmålet kan kun vises i løgnefasen"
|
||||
},
|
||||
"round_config_missing": {
|
||||
"en": "Round config missing",
|
||||
"da": "Rundekonfiguration mangler"
|
||||
},
|
||||
"question_already_shown": {
|
||||
"en": "Question already shown for this round",
|
||||
"da": "Spørgsmålet er allerede vist for denne runde"
|
||||
},
|
||||
"no_available_questions": {
|
||||
"en": "No available questions in category",
|
||||
"da": "Ingen tilgængelige spørgsmål i kategorien"
|
||||
},
|
||||
"mix_answers_invalid_phase": {
|
||||
"en": "Answers can only be mixed in lie or guess phase",
|
||||
"da": "Svar kan kun blandes i løgne- eller gættefasen"
|
||||
},
|
||||
"round_question_not_found": {
|
||||
"en": "Round question not found",
|
||||
"da": "Rundespørgsmål blev ikke fundet"
|
||||
},
|
||||
"not_enough_answers_to_mix": {
|
||||
"en": "Not enough answers to mix",
|
||||
"da": "Ikke nok svar at blande"
|
||||
},
|
||||
"host_only_start_round": {
|
||||
"en": "Only host can start round",
|
||||
"da": "Kun værten kan starte runden"
|
||||
},
|
||||
"host_only_show_question": {
|
||||
"en": "Only host can show question",
|
||||
"da": "Kun værten kan vise spørgsmålet"
|
||||
},
|
||||
"host_only_mix_answers": {
|
||||
"en": "Only host can mix answers",
|
||||
"da": "Kun værten kan blande svar"
|
||||
}
|
||||
}
|
||||
},
|
||||
"contract": {
|
||||
"ownership": {
|
||||
"artifact": "shared/i18n/lobby.json",
|
||||
"backend": "lobby/* reads backend/errors + backend/error_codes",
|
||||
"frontend": "frontend/* reads frontend/errors + frontend/ui + contract/backend_to_frontend_error_keys"
|
||||
},
|
||||
"locale": {
|
||||
"default": "en",
|
||||
"supported": [
|
||||
"en",
|
||||
"da"
|
||||
],
|
||||
"fallback": "Use default locale when requested locale is unsupported or key translation is missing."
|
||||
},
|
||||
"backend_to_frontend_error_keys": {
|
||||
"session_code_required": "session_code_required",
|
||||
"nickname_invalid": "nickname_invalid",
|
||||
"session_not_found": "session_not_found",
|
||||
"session_not_joinable": "join_failed",
|
||||
"nickname_taken": "nickname_taken",
|
||||
"category_slug_required": "start_round_failed",
|
||||
"category_not_found": "start_round_failed",
|
||||
"round_start_invalid_phase": "start_round_failed",
|
||||
"round_already_configured": "start_round_failed",
|
||||
"host_only_start_round": "start_round_failed",
|
||||
"host_only_show_question": "start_round_failed",
|
||||
"host_only_mix_answers": "start_round_failed",
|
||||
"host_only_action": "start_round_failed",
|
||||
"category_has_no_questions": "start_round_failed",
|
||||
"show_question_invalid_phase": "start_round_failed",
|
||||
"round_config_missing": "start_round_failed",
|
||||
"question_already_shown": "start_round_failed",
|
||||
"no_available_questions": "start_round_failed",
|
||||
"mix_answers_invalid_phase": "start_round_failed",
|
||||
"round_question_not_found": "start_round_failed",
|
||||
"not_enough_answers_to_mix": "start_round_failed"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user