Compare commits
51 Commits
wpp-dev-la
...
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 |
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)
|
||||
|
||||
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.
|
||||
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
|
||||
```
|
||||
@@ -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(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -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>;
|
||||
@@ -400,7 +401,14 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
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();
|
||||
|
||||
@@ -436,4 +444,78 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
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,18 +16,21 @@ 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?: () => Promise<void>;
|
||||
play?: (this: GuardableMediaElement) => Promise<void>;
|
||||
__wppSecondaryDeviceAudioGuard__?: {
|
||||
originalPlay: () => Promise<void>;
|
||||
originalPlay: (this: GuardableMediaElement) => Promise<void>;
|
||||
installs: number;
|
||||
};
|
||||
};
|
||||
|
||||
type GuardableMediaElement = {
|
||||
muted?: boolean;
|
||||
pause?: () => void;
|
||||
};
|
||||
|
||||
function resolveLocalStorage(): Storage | undefined {
|
||||
if (typeof window === 'undefined') {
|
||||
@@ -42,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>
|
||||
@@ -221,7 +225,15 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
guardState.installs += 1;
|
||||
} else {
|
||||
const originalPlay = mediaPrototype.play;
|
||||
mediaPrototype.play = () => Promise.resolve();
|
||||
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,
|
||||
@@ -242,6 +254,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private silenceExistingMediaElements(): void {
|
||||
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
|
||||
return;
|
||||
@@ -258,6 +271,10 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
|
||||
activeElements.forEach((element) => {
|
||||
element.muted = true;
|
||||
element.defaultMuted = true;
|
||||
if (typeof element.volume === 'number') {
|
||||
element.volume = 0;
|
||||
}
|
||||
element.pause?.();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -38,7 +38,10 @@ describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
@@ -79,24 +68,7 @@ function resolveCatalogPath(key: string): string {
|
||||
}
|
||||
|
||||
export function t(key: string, locale: string): string {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const fallbackLocale = DEFAULT_LOCALE;
|
||||
const segments = resolveCatalogPath(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];
|
||||
}
|
||||
|
||||
if (!cursor || typeof cursor !== 'object') {
|
||||
return key;
|
||||
}
|
||||
|
||||
const translations = cursor as Record<string, string>;
|
||||
return translations[normalizedLocale] ?? translations[fallbackLocale] ?? key;
|
||||
return translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, resolveCatalogPath(key), locale);
|
||||
}
|
||||
|
||||
export const clientHasNoAudioOutput = Boolean(lobbyCatalog.frontend.capabilities.client_has_no_audio_output);
|
||||
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,24 +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 backendToFrontendErrorKeys = lobbyCatalog.contract.backend_to_frontend_error_keys as Record<string, keyof typeof frontendErrors>;
|
||||
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>;
|
||||
@@ -26,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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
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,46 +1,60 @@
|
||||
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()
|
||||
|
||||
raw_accept_language = (request.META.get("HTTP_ACCEPT_LANGUAGE") or "").split(",", 1)[0]
|
||||
raw_requested = raw_accept_language.split(";", 1)[0].strip().replace("_", "-").split("-", 1)[0].lower()
|
||||
if raw_requested in supported_locales:
|
||||
return raw_requested
|
||||
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:
|
||||
|
||||
151
lobby/tests.py
151
lobby/tests.py
@@ -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)
|
||||
@@ -676,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,
|
||||
@@ -704,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()
|
||||
@@ -1138,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):
|
||||
@@ -1278,6 +1396,39 @@ class I18nResolverTests(TestCase):
|
||||
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"),
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
)
|
||||
@@ -909,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())
|
||||
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"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -264,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."
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user