Compare commits
114 Commits
feat/issue
...
dev/issue-
| Author | SHA1 | Date | |
|---|---|---|---|
| 2c524d7d2d | |||
| f0ebc25da7 | |||
| b968ea4430 | |||
| 5a580964c4 | |||
| e0aba3fdf6 | |||
| c0c3ecd90c | |||
| b8a9fbf6d1 | |||
| 9594a8fcb0 | |||
| e4841afbaa | |||
| ee2a202f34 | |||
| f73b99b637 | |||
| 6d99741305 | |||
| cf58ba8067 | |||
| f7ed3d9407 | |||
| 951e24b57d | |||
| 63fce7760a | |||
| 8899bf547c | |||
| 0dad635311 | |||
| 7c7a6b6a08 | |||
| f87e0b60cf | |||
| aa2d636e90 | |||
| 9219648231 | |||
| 377fb712e1 | |||
| bb90295d26 | |||
| f9e1999e74 | |||
| 0c515ed2b7 | |||
| 0bb15f749b | |||
| 361f78b1c8 | |||
| 4d46611910 | |||
| ed72f9a824 | |||
| 3474d68c57 | |||
| 0bc4e6f066 | |||
| b18b05cc70 | |||
| ed57efb1b3 | |||
| 1faadbea4d | |||
| dc6af7547c | |||
| 1f98f01283 | |||
| a278934960 | |||
| c1391e8dc5 | |||
| 8d3df1f850 | |||
| 6838cc0efc | |||
| 9deae85a56 | |||
| 4b2b21fe57 | |||
| 5538a91800 | |||
| 79b694c590 | |||
| 87c1a0ee6c | |||
| c34a52e83e | |||
| edf9460ceb | |||
| a0a1424e90 | |||
| 60e58f6214 | |||
| a658ef5f80 | |||
| 258025ac4e | |||
| f28a390f95 | |||
| a1bb1ccbed | |||
| ee025e8deb | |||
| b977016ef4 | |||
| 1b899a30a2 | |||
| 187b26e561 | |||
| 0b4ddaf43f | |||
| 7a3d649e11 | |||
| f50f6a08ae | |||
| 000a486db1 | |||
| 845e94b726 | |||
| 5fe8f92ee4 | |||
| e2f184d1bc | |||
| ab41798220 | |||
| c7ff3d96de | |||
| 3398aead7f | |||
| 97945ede92 | |||
| 3655bad847 | |||
| fdef33f44a | |||
| bc78f79f78 | |||
| 784622058a | |||
| 257732e2ab | |||
| 64fe273691 | |||
| cd6fb06343 | |||
| 508d462bb6 | |||
| e435a41660 | |||
| b9bfe55f93 | |||
| 8e21ca8e5e | |||
| ddf8e874e2 | |||
| 21a25a063c | |||
| 4e300e4631 | |||
| 5fe9939057 | |||
| 59cabcb56c | |||
| d0c97e1d9c | |||
| bb8109baf6 | |||
| 32770f54b4 | |||
| a4c0d0603d | |||
| bb823575db | |||
| 3bc3ff8cc1 | |||
| c626b19eda | |||
| bde56a2346 | |||
| 9498391366 | |||
| 011bbde840 | |||
| d3963367e4 | |||
| abe0d91080 | |||
| 63ac0d38e1 | |||
| fab0244361 | |||
| f3bd071322 | |||
| 1675e041d6 | |||
| dd3b48067a | |||
| b55b379134 | |||
| 377722eb9a | |||
| f9efb3c5e4 | |||
| 9e47a3a139 | |||
| fcfb3b21b1 | |||
| 778b8e2817 | |||
| 6cff552572 | |||
| 53e1be1471 | |||
| a6738e2297 | |||
| 988a8e5302 | |||
| cb9ef8e627 | |||
| fd1fbbf5e7 |
@@ -31,3 +31,14 @@ jobs:
|
||||
|
||||
- name: Tests
|
||||
run: python manage.py test lobby -v 1
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
|
||||
- name: Install SPA dependencies
|
||||
run: npm ci --prefix frontend/angular
|
||||
|
||||
- name: SPA Angular smoke tests
|
||||
run: npm --prefix frontend/angular test
|
||||
|
||||
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)
|
||||
|
||||
49
docs/I18N_ARCHITECTURE.md
Normal file
49
docs/I18N_ARCHITECTURE.md
Normal file
@@ -0,0 +1,49 @@
|
||||
# Shared i18n architecture (frontend + backend)
|
||||
|
||||
## Scope
|
||||
Issue #175 requires one shared i18n contract for MVP host/player flows across frontend and backend.
|
||||
|
||||
## Source of truth
|
||||
- Catalog: `shared/i18n/lobby.json`
|
||||
- Locales:
|
||||
- supported: `en`, `da`
|
||||
- default/fallback: `en`
|
||||
|
||||
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:
|
||||
- `frontend.ui.common.*`
|
||||
- `frontend.ui.host.*`
|
||||
- `frontend.ui.player.*`
|
||||
- `frontend.errors.*`
|
||||
- `backend.errors.*`
|
||||
- `backend.error_codes.*`
|
||||
- UI lookup keys in Angular are shortened aliases mapped under `frontend.ui`, e.g.:
|
||||
- `host.start_round`
|
||||
- `player.submit_guess`
|
||||
- `common.session_code`
|
||||
- Backend API errors return stable code + localized message:
|
||||
- `error_code` = machine-stable key from `backend.error_codes`
|
||||
- `error` = localized message from `backend.errors`
|
||||
- `locale` = resolved request locale
|
||||
|
||||
## Fallback model (robust)
|
||||
1. Resolve requested locale (`Accept-Language` on backend, user/browser preference on frontend).
|
||||
2. If locale unsupported -> use default `en`.
|
||||
3. If key missing -> return key and log warning.
|
||||
4. If locale translation missing for key -> fallback to `en` translation.
|
||||
|
||||
## Audio-routing policy
|
||||
- Catalog capability: `frontend.capabilities.client_has_no_audio_output = true`
|
||||
- Host/player clients expose this as a read-only capability flag.
|
||||
- Policy: phone clients must not play audio directly; only primary/host output is allowed.
|
||||
|
||||
## Verification
|
||||
- Backend tests: `lobby/tests.py` i18n coverage for locale selection + fallback + error-code/message matrix.
|
||||
- Frontend smoke/e2e-level unit coverage:
|
||||
- `frontend/angular/src/app/lobby-i18n.spec.ts`
|
||||
- `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)
|
||||
35
docs/ISSUE-175-I18N-SHARED-CONTRACT-ARTIFACT.md
Normal file
35
docs/ISSUE-175-I18N-SHARED-CONTRACT-ARTIFACT.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# ISSUE-175 Artifact — shared i18n contract + MVP host/player flow
|
||||
|
||||
## Delivered
|
||||
- Shared i18n contract is centralized in `shared/i18n/lobby.json` (da/en, default `en`, robust fallback).
|
||||
- Frontend host/player MVP copy is read via shared keys (no hardcoded Danish strings in Angular MVP flow components).
|
||||
- Backend error messages resolve from shared keyspace with locale-aware API payload (`error_code`, `error`, `locale`).
|
||||
- Audio-routing policy is explicit and shared: `frontend.capabilities.client_has_no_audio_output=true`.
|
||||
- Architecture + key naming documented in `docs/I18N_ARCHITECTURE.md`.
|
||||
|
||||
## Smoke / e2e evidence
|
||||
### Backend locale + fallback
|
||||
Command:
|
||||
```bash
|
||||
. .venv/bin/activate && python manage.py test \
|
||||
lobby.tests.LobbyFlowTests.test_join_error_localizes_to_danish_with_accept_language_header \
|
||||
lobby.tests.LobbyFlowTests.test_join_error_falls_back_to_english_for_unsupported_locale \
|
||||
lobby.tests.I18nResolverTests
|
||||
```
|
||||
Result:
|
||||
- PASS (7 tests)
|
||||
- Confirms `da` localization and fallback to `en` for unsupported locale.
|
||||
|
||||
### Frontend host/player + language switch + audio policy
|
||||
Command:
|
||||
```bash
|
||||
cd frontend/angular
|
||||
npm test -- --run \
|
||||
src/app/lobby-i18n.spec.ts \
|
||||
src/app/i18n-mvp-flow-smoke.spec.ts \
|
||||
src/app/features/host/host-shell.component.spec.ts \
|
||||
src/app/features/player/player-shell.component.spec.ts
|
||||
```
|
||||
Result:
|
||||
- PASS (22 tests)
|
||||
- Includes smoke for host/player copy in **both en and da** and verifies primary-only audio policy flag (`clientHasNoAudioOutput=true`).
|
||||
47
docs/ISSUE-188-SPA-CUTOVER-HARDENING-ARTIFACT.md
Normal file
47
docs/ISSUE-188-SPA-CUTOVER-HARDENING-ARTIFACT.md
Normal file
@@ -0,0 +1,47 @@
|
||||
# Issue #188 Artifact — SPA cutover hardening (asset versioning + rollback)
|
||||
|
||||
## Scope
|
||||
Acceptance for `[READY][SPA][P11] Cutover hardening`:
|
||||
1. Dokumenteret strategi for cache-busting/versionering af SPA assets i Django staticfiles/reverse proxy setup.
|
||||
2. Konfigurerbar rollback-procedure for `USE_SPA_UI` (trin-for-trin, target <10 min).
|
||||
3. Smoke-artefakt for både SPA on/off i samme release-vindue.
|
||||
4. Ingen gameplay-ændringer.
|
||||
|
||||
## 1) Asset versioning/cache-busting strategi
|
||||
Implementeret i SPA shell render-path:
|
||||
|
||||
- Konfiguration i `partyhub/settings.py`:
|
||||
- `WPP_SPA_ASSET_BASE` (eksisterende)
|
||||
- `WPP_SPA_ASSET_VERSION` (ny)
|
||||
- `lobby/ui_views.py` injicerer `spa_asset_version` til template-context.
|
||||
- `lobby/templates/lobby/spa_shell.html` appender `?v={{ spa_asset_version }}` på:
|
||||
- `styles.css`
|
||||
- `main.js`
|
||||
|
||||
Effekt:
|
||||
- Ny release-version (fx SHA/tag) kan tvinge cache-miss i browser/proxy uden ændring af route.
|
||||
- Rollback kan pege på tidligere stabil version-token med samme mekanisme.
|
||||
|
||||
## 2) Rollback playbook (`USE_SPA_UI`) — target <10 min
|
||||
Dokumenteret i `docs/spa-cutover-flag.md`:
|
||||
|
||||
1. Sæt `USE_SPA_UI=false`.
|
||||
2. Sæt `WPP_SPA_ASSET_VERSION` til sidste stabile release-token.
|
||||
3. Deploy/reload app-processer.
|
||||
4. Verificér legacy routes (`/lobby/ui/host` + `/lobby/ui/player`).
|
||||
5. Kør hurtig smoke sanity.
|
||||
6. Log trigger/timestamp/resultat i smoke artifact.
|
||||
|
||||
## 3) Smoke artifact for SPA OFF/ON i samme release-vindue
|
||||
Dokumenteret i:
|
||||
- `docs/UI_SMOKE.md` (sektion: "Samme release-vindue: SPA OFF + ON verifikation")
|
||||
- `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md` (template udvidet med release-window check + `WPP_SPA_ASSET_VERSION`)
|
||||
|
||||
Krav:
|
||||
- OFF-pass (legacy) og ON-pass (SPA) køres i samme deploy/release-vindue.
|
||||
- Begge passes logges i samme artifact med UTC timestamps og version-token.
|
||||
|
||||
## Non-goals bekræftet
|
||||
- Ingen gameplay-regler ændret.
|
||||
- Ingen API-kontrakter ændret.
|
||||
- Ingen UX-redesign; kun drift/cutover-hardening.
|
||||
57
docs/ISSUE-200-SPA-HOST-PLAYER-PHASE-SYNC-ARTIFACT.md
Normal file
57
docs/ISSUE-200-SPA-HOST-PLAYER-PHASE-SYNC-ARTIFACT.md
Normal file
@@ -0,0 +1,57 @@
|
||||
# Issue #200 Artifact — SPA host→player phase sync (no reload)
|
||||
|
||||
## Scope
|
||||
Acceptance for `[READY][SPA][P14] Gameplay MVP-del 5`:
|
||||
1. Host handlinger (`start round` / `næste fase`) propagere korrekt til player-ruter i SPA.
|
||||
2. Happy-path artefakt for én fuld faseovergang uden page reload.
|
||||
3. Sync-fejl giver kontrolleret fallback/error state.
|
||||
|
||||
Afgrænsning overholdt: ingen nye spilregler og ingen redesign af backend event-model.
|
||||
|
||||
## Happy-path faseovergang (uden page reload)
|
||||
Reference-flow i Angular shell:
|
||||
|
||||
1. **Host starter runde/fase**
|
||||
- Host action kalder backend endpoint (`POST /lobby/sessions/:code/start` eller fase-endpoint)
|
||||
- Host shell hydrerer session igen (`GET /lobby/sessions/:code`)
|
||||
- Host route synkes via hash-rewrite i samme SPA shell:
|
||||
- `#/host/<phase>/<CODE>`
|
||||
- Implementeret i `HostShellComponent.syncRouteFromSession()`
|
||||
|
||||
2. **Player modtager ny fase via state sync**
|
||||
- Player shell kører periodisk session-refresh (3s), uden hard reload
|
||||
- Når `session.status` ændrer sig, synkes hash-route i samme SPA shell:
|
||||
- `#/player/<phase>/<CODE>`
|
||||
- Implementeret i `PlayerShellComponent.syncRouteFromSession()`
|
||||
|
||||
3. **Ingen page reload**
|
||||
- Routing sker med `window.history.replaceState(...)`
|
||||
- URL opdateres i eksisterende SPA instans (ingen template-hop, ingen full refresh)
|
||||
|
||||
## Kontrolleret fallback ved sync-fejl
|
||||
Når player-sync fejler (netværk/fetch/session-refresh):
|
||||
|
||||
- UI går i kontrolleret connection-state:
|
||||
- `reconnecting` ved online netværksfejl
|
||||
- `offline` når browser rapporterer offline
|
||||
- Fejl vises med retry/back-to-join handlinger
|
||||
- Reconnect forsøges igen via timer (`scheduleReconnect`) uden at crashe shell
|
||||
|
||||
## Verifikation (tests)
|
||||
Kørt i `frontend/angular` med Vitest:
|
||||
|
||||
- `src/app/features/host/host-shell.component.spec.ts`
|
||||
- Verificerer host-faseflow og hash-route sync uden reload
|
||||
- `src/app/features/player/player-shell.component.spec.ts`
|
||||
- Verificerer periodisk player state sync + hash-route sync
|
||||
- Verificerer reconnect/offline fallback ved sync-fejl
|
||||
- `src/app/api-contract-smoke.spec.ts`
|
||||
- `src/app/session-route-context.spec.ts`
|
||||
|
||||
Kommando:
|
||||
|
||||
```bash
|
||||
npm test -- --reporter=dot
|
||||
```
|
||||
|
||||
Resultat: **4/4 testfiler grønne, 22/22 tests bestået**.
|
||||
36
docs/ISSUE-205-I18N-FOUNDATION.md
Normal file
36
docs/ISSUE-205-I18N-FOUNDATION.md
Normal file
@@ -0,0 +1,36 @@
|
||||
# Issue #205 — Django i18n foundation (da/en)
|
||||
|
||||
## Implemented acceptance checks
|
||||
|
||||
- **Django i18n setup for `en` + `da` with `en` fallback**
|
||||
- `LANGUAGE_CODE` set to `en`.
|
||||
- `LANGUAGES = [('en', 'English'), ('da', 'Danish')]`.
|
||||
- `LocaleMiddleware` enabled in middleware chain.
|
||||
- **Shared-key resolver/adapter (no ad hoc backend mapping)**
|
||||
- Backend error responses now resolve from shared catalog keys in `shared/i18n/lobby.json`.
|
||||
- `lobby.i18n.api_error()` accepts a shared key and resolves locale-specific text.
|
||||
- **Representative API flow documented with key/locale behavior**
|
||||
- `POST /lobby/join` with empty code returns:
|
||||
- `error_code: "session_code_required"`
|
||||
- localized `error`
|
||||
- resolved `locale`
|
||||
- **Missing key handling deterministic and loggable**
|
||||
- `resolve_error_message()` returns key string when key/translation is missing.
|
||||
- Warning is logged (`lobby.i18n` logger) for missing key/translation.
|
||||
|
||||
## Example response behavior
|
||||
|
||||
### Request
|
||||
`POST /lobby/join` with empty code and header `Accept-Language: da`
|
||||
|
||||
### Response (400)
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Sessionskode er påkrævet",
|
||||
"error_code": "session_code_required",
|
||||
"locale": "da"
|
||||
}
|
||||
```
|
||||
|
||||
If locale is unsupported (e.g. `fr`), response uses `locale: "en"` and English message.
|
||||
35
docs/ISSUE-207-I18N-AUDIO-SMOKE-ARTIFACT.md
Normal file
35
docs/ISSUE-207-I18N-AUDIO-SMOKE-ARTIFACT.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Issue #207 Artifact — da/en locale switch + audio routing (primary-only)
|
||||
|
||||
## Scope
|
||||
Acceptance for `[READY][i18n][P19]`:
|
||||
1. Verify one MVP host+player flow in both `en` and `da` locale context.
|
||||
2. Verify controlled fallback to `en` when a locale key is missing.
|
||||
3. Verify audio-routing policy is primary-only (client/player has no audio output).
|
||||
|
||||
No new feature behavior added — this is verification-only evidence.
|
||||
|
||||
## Smoke/e2e evidence (Angular shell test run)
|
||||
Executed from `frontend/angular`:
|
||||
|
||||
```bash
|
||||
npm test -- --reporter=dot src/app/lobby-i18n.spec.ts src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts
|
||||
```
|
||||
|
||||
Evidence covered by the run:
|
||||
- `lobby-i18n.spec.ts`
|
||||
- subscriber locale switch updates (`en -> da -> en`)
|
||||
- controlled fallback where `da` key is removed during test and `en` copy is returned
|
||||
- `clientHasNoAudioOutput === true` (primary-only audio routing)
|
||||
- `host-shell.component.spec.ts`
|
||||
- host actions and route sync in SPA (no reload)
|
||||
- `player-shell.component.spec.ts`
|
||||
- player session refresh/sync path and retry behavior
|
||||
|
||||
## Policy evidence
|
||||
- Shared catalog capability: `shared/i18n/lobby.json`
|
||||
- `frontend.capabilities.client_has_no_audio_output = true`
|
||||
- Angular host/player shells bind this capability:
|
||||
- `HostShellComponent.clientHasNoAudioOutput`
|
||||
- `PlayerShellComponent.clientHasNoAudioOutput`
|
||||
|
||||
Conclusion: locale switching works in `da`/`en`, fallback resolves to `en` when locale key is intentionally missing, and client audio remains disabled by policy (`primary-only`).
|
||||
20
docs/ISSUE-223-PLAYER-AUDIO-GUARD-ARTIFACT.md
Normal file
20
docs/ISSUE-223-PLAYER-AUDIO-GUARD-ARTIFACT.md
Normal file
@@ -0,0 +1,20 @@
|
||||
# Issue #223 — Telefon-klient audio guard (artifact)
|
||||
|
||||
## Scope leveret
|
||||
- Telefon-/player-klient installerer en eksplicit audio guard ved mount (`installSecondaryDeviceAudioGuard`).
|
||||
- Guard overskriver `HTMLMediaElement.prototype.play` til en no-op på secondary device (client policy: `client_has_no_audio_output=true`).
|
||||
- Guard fjernes igen ved unmount (`ngOnDestroy`) så øvrige flows/enheder ikke påvirkes.
|
||||
- Ingen audio-controls er eksponeret i player-shell UI.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **Telefon-klient trigger ikke audio playback i kerneflow**
|
||||
- Verificeret af test: `player-shell.component.spec.ts` (`installs secondary-device audio guard while player shell is mounted`).
|
||||
2. **Primær enhed påvirkes ikke negativt**
|
||||
- Guard er scoped til player-shell lifecycle og restore'r original `play` ved destroy.
|
||||
3. **Enkel test/verifikation dokumenteret**
|
||||
- Dokumenteret her + testkørsel nedenfor.
|
||||
|
||||
## Testkørsel
|
||||
- Kommando:
|
||||
- `cd frontend/angular && npm test -- src/app/features/player/player-shell.component.spec.ts`
|
||||
- Resultat: bestået (inkl. audio-guard test).
|
||||
55
docs/ISSUE-224-TRUNK-SEQUENCE-175.md
Normal file
55
docs/ISSUE-224-TRUNK-SEQUENCE-175.md
Normal file
@@ -0,0 +1,55 @@
|
||||
# Issue #224 — Trunk-sekvens for #175 (A/B/C)
|
||||
|
||||
Formål: gøre #175 scheduler-klar som tre små, uafhængige og mergeklare bidder.
|
||||
|
||||
## Sekvens
|
||||
|
||||
### A) Backend i18n baseline
|
||||
- Tracking issue: #225
|
||||
- Scope:
|
||||
- Backend resolver til locale (da/en)
|
||||
- Fallback til `en` ved unsupported locale
|
||||
- Stabil fejlkontrakt i payload (`error_code`, `error`, `locale`)
|
||||
- Mergebarhed: Kan merges uden frontend-ændringer.
|
||||
- Acceptance:
|
||||
- Backend tests dækker `da` + fallback `en`
|
||||
- Kontraktfelter er stabile i response
|
||||
|
||||
### B) Shared key-map + locale-kontrakt
|
||||
- Tracking issue: #226
|
||||
- Scope:
|
||||
- Én shared key-map for lobby/kerneflow
|
||||
- Locale-kontrakt (tilladte locales, default locale, fallback-regler)
|
||||
- Dokumentation af naming + ownership
|
||||
- Mergebarhed: Kan merges uden host/player UI-migrering.
|
||||
- Acceptance:
|
||||
- Shared kontrakt findes ét sted
|
||||
- Begge sider kan importere den
|
||||
- Docs opdateret med da/en eksempler
|
||||
|
||||
### C) Angular host/player integration + hardcoded-text cleanup
|
||||
- Tracking issue: #227
|
||||
- Scope:
|
||||
- Angular host/player kerneflow bruger shared keys
|
||||
- Hardcoded tekster fjernes i aftalte kernekomponenter
|
||||
- Sprogskift verificeres i kritiske states
|
||||
- Mergebarhed: Kan merges selvstændigt når frontend-tests er grønne.
|
||||
- Acceptance:
|
||||
- Korrekt i18n-copy i da/en i kerneflow
|
||||
- Ingen hardcoded kerneflow-tekster tilbage
|
||||
- Frontend tests/smoke grønne
|
||||
|
||||
## PR-grænser (per bid)
|
||||
- 1 PR pr. bid (A/B/C) mod `main`
|
||||
- Mål: ~200–300 net LOC per PR (ekskl. generated artefakter)
|
||||
- Undgå cross-layer scope creep
|
||||
- Review-tid <30 min
|
||||
|
||||
## Overordnet acceptance for #224
|
||||
- A/B/C-sekvens er tydelig med links
|
||||
- Hver bid er mergebar isoleret
|
||||
- Scheduler kan assign’e direkte uden ekstra afklaring
|
||||
|
||||
## Verification (docs-only)
|
||||
- Verificeret at dokumentet kun beskriver trunk-sekvensen for issue #224 og linker til #225/#226/#227.
|
||||
- Ingen runtime-kode ændret; der er derfor ikke kørt kode/tests i denne PR.
|
||||
44
docs/ISSUE-225-BACKEND-I18N-BASELINE-ARTIFACT.md
Normal file
44
docs/ISSUE-225-BACKEND-I18N-BASELINE-ARTIFACT.md
Normal file
@@ -0,0 +1,44 @@
|
||||
# ISSUE-225 Artifact — Backend i18n baseline (resolver + fallback)
|
||||
|
||||
Issue: **#225** (`[MVP][READY] #175-A: Backend i18n baseline (resolver + fallback)`)
|
||||
|
||||
## Scope verified
|
||||
|
||||
- Backend locale resolver supports `da` + `en` and normalizes language tags.
|
||||
- Unsupported locale requests fall back to default locale (`en`).
|
||||
- Error payload contract is stable for API errors:
|
||||
- `error_code`
|
||||
- `error`
|
||||
- `locale`
|
||||
|
||||
## Implementation references
|
||||
|
||||
- Locale resolution + fallback chain:
|
||||
- `lobby/i18n.py`
|
||||
- `resolve_locale()`
|
||||
- `resolve_error_message()`
|
||||
- `api_error()`
|
||||
- Shared locale contract source:
|
||||
- `shared/i18n/lobby.json` (`locales.default=en`, supported includes `en`, `da`)
|
||||
|
||||
## Acceptance checks run
|
||||
|
||||
Command:
|
||||
|
||||
```bash
|
||||
.venv/bin/python manage.py test \
|
||||
lobby.tests.I18nResolverTests \
|
||||
lobby.tests.LobbyFlowTests \
|
||||
lobby.tests.StartRoundTests
|
||||
```
|
||||
|
||||
Result (2026-03-02):
|
||||
|
||||
- `Ran 28 tests in 24.781s — OK`
|
||||
- `System check identified no issues (0 silenced).`
|
||||
- Confirms resolver behavior for locale normalization + fallback and stable error payload fields across flow endpoints.
|
||||
|
||||
## Notes
|
||||
|
||||
- Existing merged follow-ups in `main` include Accept-Language parsing fixes for q-values and locale tag normalization.
|
||||
- This artifact documents the final baseline state and verification evidence for #225.
|
||||
30
docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md
Normal file
30
docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md
Normal file
@@ -0,0 +1,30 @@
|
||||
# ISSUE-226 — Shared key-map + locale-kontrakt (backend/frontend)
|
||||
|
||||
## Source of truth
|
||||
- Single shared artifact: `shared/i18n/lobby.json`
|
||||
- Ownership is documented under `contract.ownership` in the same artifact.
|
||||
|
||||
## Locale contract
|
||||
Defined under `contract.locale`:
|
||||
- default locale: `en`
|
||||
- supported locales: `en`, `da`
|
||||
- fallback rule: use default locale when requested locale is unsupported or a key translation is missing.
|
||||
|
||||
## Shared backend→frontend key-map
|
||||
Defined under `contract.backend_to_frontend_error_keys`.
|
||||
|
||||
Examples:
|
||||
- `session_not_found -> session_not_found`
|
||||
- `session_not_joinable -> join_failed`
|
||||
- `round_start_invalid_phase -> start_round_failed`
|
||||
|
||||
This allows backend error codes to remain stable while frontend copy keys stay UX-oriented.
|
||||
|
||||
## da/en example values
|
||||
From `shared/i18n/lobby.json`:
|
||||
- `frontend.errors.session_code_required.en = "Session code is required."`
|
||||
- `frontend.errors.session_code_required.da = "Sessionskoden er påkrævet."`
|
||||
|
||||
## Verification
|
||||
- Backend: `python manage.py test lobby.tests.I18nResolverTests`
|
||||
- Frontend: `npm test -- --run tests/lobby-i18n.contract.test.ts`
|
||||
16
docs/ISSUE-250-PRIMARY-DEVICE-AUDIO-POLICY-ARTIFACT.md
Normal file
16
docs/ISSUE-250-PRIMARY-DEVICE-AUDIO-POLICY-ARTIFACT.md
Normal file
@@ -0,0 +1,16 @@
|
||||
# Issue #250 Artifact — MVP guardrail (telefon-klient uden lydafspilning)
|
||||
|
||||
## Scope
|
||||
Implementeret guardrail for `primary-device only` audio policy i SPA player-flow.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **Telefon-klient flow indeholder ingen audio-play init-path**
|
||||
- Test: `player-shell.component.spec.ts` → `does not trigger original media play during player-shell init path`.
|
||||
2. **Primær enhed policy er dokumenteret og testbar**
|
||||
- Policy i contract: `shared/i18n/lobby.json` → `frontend.capabilities.client_has_no_audio_output=true`.
|
||||
- Testbar via eksisterende guard-tests + init-path test i player-shell specs.
|
||||
3. **Krav er refereret i SPA-plan/cutover-noter**
|
||||
- Dokumenteret i `docs/spa-cutover-flag.md` under *MVP audio policy guardrail (telefon-klient)*.
|
||||
|
||||
## UX/i18n note
|
||||
- Player shell viser advarselstekst via i18n key: `frontend.ui.player.audio_policy_notice`.
|
||||
124
docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md
Normal file
124
docs/ISSUE-251-RELEASE-OFTEN-SPA-MVP-BATCH-PLAN.md
Normal file
@@ -0,0 +1,124 @@
|
||||
# Issue #251 — Release-often lane for SPA MVP (3 micro-PR batches)
|
||||
|
||||
## Formål
|
||||
Bryde SPA MVP-arbejdet op i **3 merge-klare micro-PRs** med tydelige acceptance criteria,
|
||||
så vi kan levere værdi oftere, reducere review-risiko og holde `main` grøn.
|
||||
|
||||
## Scope (issue-bound)
|
||||
Denne plan dækker kun planlægning/acceptance for den kommende SPA MVP-lane.
|
||||
Implementering af de konkrete features sker i efterfølgende PRs.
|
||||
|
||||
## Hard acceptance criteria for issue #251
|
||||
- [x] Der findes en dokumenteret plan med præcis **3 batches**.
|
||||
- [x] Hver batch har:
|
||||
- [x] mål og afgrænsning
|
||||
- [x] konkrete leverancer (kodeområder)
|
||||
- [x] test/checks før merge
|
||||
- [x] rollback-note
|
||||
- [x] "ikke med i denne batch" for at undgå scope creep
|
||||
- [x] Batch-rækkefølgen er dependencies-sikker (batch B bygger på batch A, batch C på batch B).
|
||||
- [x] Hver batch kan merges/releaseres uafhængigt uden at blokere drift på `main`.
|
||||
- [x] Planen linker til konkrete dev-opgaver for lane-kørsel.
|
||||
|
||||
## Batch-plan (merge-klare micro-PRs)
|
||||
|
||||
### Batch A — SPA shell + routing baseline
|
||||
**Mål:** Et stabilt SPA-skelet med route-struktur og guard-basics.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/app.routes.ts` (host/player entry routes + fallback)
|
||||
- `frontend/angular/src/app/session-route-context.ts` (baseline route guards)
|
||||
- `frontend/angular/src/app/app.component.*` (shell-nav + route outlet wiring)
|
||||
- `lobby/templates/lobby/spa_shell.html` (kompatibel shell-entry ved SPA cutover)
|
||||
|
||||
**Done-kriterier**
|
||||
- Host- og player-entry routes kan åbnes uden runtime-fejl i samme SPA-shell.
|
||||
- Route guards afviser ugyldige parametre deterministisk (ingen hard crash).
|
||||
- `USE_SPA_UI=false` fortsætter med legacy-flow uden regression.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/app.routes.spec.ts src/app/session-route-context.spec.ts`
|
||||
- `cd frontend/angular && npm run build`
|
||||
- Manual smoke: `/lobby/ui/host` + `/lobby/ui/player` (både `USE_SPA_UI=false` og `true`).
|
||||
|
||||
**Rollback-note**
|
||||
- Sæt `USE_SPA_UI=false` og redeploy; verificér legacy routes svarer 200.
|
||||
|
||||
**Ikke med i batch A**
|
||||
- Fuld gameplay-state synkronisering.
|
||||
- Audio/polish og i18n finpudsning ud over baseline wiring.
|
||||
|
||||
---
|
||||
|
||||
### Batch B — Session-state + host/player sync MVP
|
||||
**Mål:** Korrekt synkronisering af session-state mellem host og spillerklient.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/features/host/host-shell.component.ts`
|
||||
- `frontend/angular/src/app/features/player/player-shell.component.ts`
|
||||
- `frontend/src/api/angular-client.ts` (MVP-kald for status/phase-overgange)
|
||||
|
||||
**Done-kriterier**
|
||||
- Host handlinger (`start`, `show`, `mix`, `score`, `next`, `finish`) afspejles hos player uden side-reload.
|
||||
- Session-phase transitions er deterministiske i happy-path (`lobby -> question -> score -> next/finish`).
|
||||
- Guardrails reducerer race-condition regressions ved hurtige phase-skift.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts`
|
||||
- `cd frontend && npm test -- --run tests/angular-api-client.test.ts`
|
||||
- Manual smoke: host action -> player phase sync indenfor forventet latenstid.
|
||||
|
||||
**Rollback-note**
|
||||
- Slå `USE_SPA_UI=false`, redeploy, og kør hurtig gameplay-smoke i legacy flow.
|
||||
|
||||
**Ikke med i batch B**
|
||||
- Avanceret UX-polish/animation.
|
||||
- Udvidet observability udenfor MVP-kritiske logs.
|
||||
|
||||
---
|
||||
|
||||
### Batch C — Lobby/join/start minimal flow + release readiness
|
||||
**Mål:** Gøre SPA MVP release-klar med fokus på stabilitet og driftssikkerhed omkring det minimale flow.
|
||||
|
||||
**Leverancer (kodeområder)**
|
||||
- `frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts` + relevante shell-tests
|
||||
- `docs/UI_SMOKE.md` + `docs/STAGING_GAMEPLAY_SMOKE_ARTIFACT.md`
|
||||
- `CHANGELOG.md` release-input for SPA MVP lane
|
||||
|
||||
**Done-kriterier**
|
||||
- End-to-end minimal flow (`lobby -> join -> start`) er dokumenteret PASS i SPA.
|
||||
- Fejl-/empty-/loading states for flowets kritiske skærme er verificeret.
|
||||
- Driftsteam kan udføre cutover + rollback uden tvetydighed.
|
||||
|
||||
**Checks før merge**
|
||||
- `cd frontend/angular && npm test -- --run src/app/i18n-mvp-flow-smoke.spec.ts`
|
||||
- `python manage.py test lobby.tests.LobbyFlowTests`
|
||||
- Opdateret staging-smoke artifact med UTC tidsstempler og gate-resultat.
|
||||
|
||||
**Rollback-note**
|
||||
- Brug eksisterende playbook i `docs/spa-cutover-flag.md` (`USE_SPA_UI=false` + asset-version rollback).
|
||||
|
||||
**Ikke med i batch C**
|
||||
- Post-MVP featureudvidelser.
|
||||
- Større refactors uden direkte release-værdi.
|
||||
|
||||
## Rækkefølge og parallel-kørsel
|
||||
- **Dependency-rækkefølge:** A -> B -> C.
|
||||
- **Kan køres parallelt uden konflikt:**
|
||||
- Test-/doc-forberedelse til C kan startes parallelt med B (ingen blokering af runtime-kode), men merges først efter B.
|
||||
- Drift-smoke templates kan opdateres tidligt, så længe de ikke ændrer runtime-adfærd.
|
||||
- **Må ikke køre parallelt:**
|
||||
- Runtime routing/guard ændringer i A og session-sync logik i B på samme filer uden feature-flag koordinering.
|
||||
|
||||
## Konkret lane-opgavebinding (dev-opgaver)
|
||||
- Batch A PR: `feat/issue-251-batch-1-spa-shell-routing`
|
||||
- Batch B PR: `feat/issue-251-batch-2-session-sync`
|
||||
- Batch C PR: `feat/issue-251-batch-3-lobby-join-start-release-readiness`
|
||||
|
||||
Hver PR skal linke tilbage til issue #251 og inkludere test-evidence + rollback-check.
|
||||
|
||||
## Merge-gate for alle 3 batches
|
||||
- Små PRs (mål: reviewbar størrelse, helst < ~300 netto-linjer når muligt).
|
||||
- Grøn CI/checks før review-request.
|
||||
- Tydelig PR-beskrivelse med: scope, test evidence, out-of-scope.
|
||||
- Ingen skjulte sideeffekter på tværs af apps/domæner.
|
||||
@@ -0,0 +1,32 @@
|
||||
# ISSUE-257 Artifact — Shared i18n keyspace + frontend loader (da/en, Angular-first)
|
||||
|
||||
Issue: **#257** (`[MVP][READY] #175-B: Shared i18n keyspace + frontend loader`)
|
||||
|
||||
## Acceptance checklist
|
||||
|
||||
- [x] **Delt key-strategi dokumenteret (frontend/backend)**
|
||||
- Arkitektur/deling beskrevet i `docs/I18N_ARCHITECTURE.md`.
|
||||
- Shared contract + keyspace source of truth: `shared/i18n/lobby.json`.
|
||||
|
||||
- [x] **Frontend loader kan indlæse da+en med samme keyspace**
|
||||
- Shared loader: `frontend/shared/i18n/lobby-loader.ts`.
|
||||
- Angular-first integration via `frontend/angular/src/app/lobby-i18n.ts` (samme loader/samme keyspace).
|
||||
- Locale-normalisering inkluderer underscore/hyphen variants (`da_DK` → `da`).
|
||||
|
||||
- [x] **Minimal check for key-paritet da/en**
|
||||
- `collectLocaleParityIssues(...)` i shared loader.
|
||||
- Testet i `frontend/tests/lobby-loader.parity.test.ts`.
|
||||
|
||||
- [x] **Ingen API-kontraktbrud**
|
||||
- Contract-test: `frontend/tests/lobby-i18n.contract.test.ts`.
|
||||
- Drift-check mellem manifest og katalog: `scripts/check_i18n_drift.py`.
|
||||
|
||||
## Kørte checks
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
cd frontend && npm test -- --run tests/lobby-loader.parity.test.ts tests/lobby-i18n.contract.test.ts
|
||||
cd frontend/angular && npm test -- --run src/app/lobby-i18n.spec.ts src/app/i18n-mvp-flow-smoke.spec.ts
|
||||
```
|
||||
|
||||
Resultat: alle checks grønne.
|
||||
37
docs/ISSUE-257-SHARED-I18N-LOADER-ARTIFACT.md
Normal file
37
docs/ISSUE-257-SHARED-I18N-LOADER-ARTIFACT.md
Normal file
@@ -0,0 +1,37 @@
|
||||
# ISSUE-257 Artifact — shared i18n keyspace + frontend loader (Angular-first)
|
||||
|
||||
Issue: **#257** (`[MVP][READY] #175-B: Shared i18n keyspace + frontend loader (da/en, Angular-first)`)
|
||||
|
||||
## Acceptance mapping
|
||||
|
||||
### 1) Delt key-strategi dokumenteret (frontend/backend)
|
||||
- Shared contract source: `shared/i18n/lobby.json`
|
||||
- Architecture doc: `docs/I18N_ARCHITECTURE.md`
|
||||
- Key-map/contract doc: `docs/ISSUE-226-SHARED-KEYMAP-LOCALE-CONTRACT.md`
|
||||
|
||||
### 2) Frontend loader kan indlæse da+en med samme keyspace
|
||||
- Shared loader: `frontend/shared/i18n/lobby-loader.ts`
|
||||
- Angular-first consumer path:
|
||||
- `frontend/src/spa/lobby-i18n.ts`
|
||||
- Angular shell/tests continue to consume same shared catalog through shared loader contract.
|
||||
|
||||
### 3) Minimal check for key-paritet da/en
|
||||
- Guard test: `frontend/tests/lobby-loader.parity.test.ts`
|
||||
- Contract test: `frontend/tests/lobby-i18n.contract.test.ts`
|
||||
|
||||
### 4) Ingen API-kontraktbrud
|
||||
- Frontend API contract smoke:
|
||||
- `frontend/angular/src/app/api-contract-smoke.spec.ts`
|
||||
- `frontend/tests/angular-api-client.test.ts`
|
||||
|
||||
## Verification run (this lane)
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
npm test -- --run tests/lobby-loader.parity.test.ts tests/lobby-i18n.contract.test.ts tests/angular-api-client.test.ts
|
||||
|
||||
cd ../frontend/angular
|
||||
npm test -- --run src/app/api-contract-smoke.spec.ts
|
||||
```
|
||||
|
||||
Result: PASS (all selected suites green).
|
||||
18
docs/ISSUE-260-PHONE-CLIENT-NO-AUDIO-GUARD-ARTIFACT.md
Normal file
18
docs/ISSUE-260-PHONE-CLIENT-NO-AUDIO-GUARD-ARTIFACT.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# Issue #260 Artifact — Phone/client no-audio guard (primary-device only playback)
|
||||
|
||||
## Scope
|
||||
Added regression coverage for MVP audio policy to ensure phone/client flows never claim playback ownership, while primary-device playback stays unaffected.
|
||||
|
||||
## Acceptance mapping
|
||||
1. **client/phone triggers no playback**
|
||||
- Existing test coverage retained in `player-shell.component.spec.ts`:
|
||||
- `does not trigger original media play during player-shell init path`
|
||||
- `installs secondary-device audio guard while player shell is mounted`
|
||||
2. **primary device playback unaffected**
|
||||
- New negative test in `player-shell.component.spec.ts`:
|
||||
- `keeps primary-device playback untouched when no-audio capability is disabled`
|
||||
3. **one negative test for phone audio**
|
||||
- Existing negative path preserved:
|
||||
- `does not trigger original media play during player-shell init path`
|
||||
4. **no backend contract changes**
|
||||
- Frontend test/docs-only scope; no backend contract files changed.
|
||||
80
docs/ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md
Normal file
80
docs/ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md
Normal file
@@ -0,0 +1,80 @@
|
||||
# ISSUE-277 Artifact — shared i18n registry parity report (Django ↔ Angular MVP)
|
||||
|
||||
Issue: **#277** (`[READY][#175][P3] Shared i18n registry artifact: backend/frontend keyspace parity report`)
|
||||
|
||||
## Artifact metadata
|
||||
|
||||
- `artifact_id`: `issue-277-shared-i18n-parity-report`
|
||||
- `artifact_version`: `1.0`
|
||||
- `catalog_source`: `shared/i18n/lobby.json`
|
||||
- `generator`: `scripts/report_i18n_parity.py`
|
||||
|
||||
## Naming/version rules (email-manager-inspired strategy)
|
||||
|
||||
- **Single canonical artifact per issue**: issue-bundne rapporter navngives `docs/ISSUE-<nr>-<slug>-ARTIFACT.md`.
|
||||
- **Stable artifact identity**: `artifact_id` ændres ikke ved tekstlige opdateringer i samme rapporttype; det er den faste reference i review/ops.
|
||||
- **Explicit artifact versioning**: `artifact_version` bumpes, når rapportlogik eller scope ændres, så drift/review kan se forskel på format- vs. dataændringer.
|
||||
- **Shared namespace first**: keys refereres med fulde navnerum (`frontend.ui.*`, `frontend.errors.*`, `backend.error_codes.*`, `backend.errors.*`) i stedet for lokale aliases i artefakter.
|
||||
- **Source-of-truth before consumers**: rapporten afledes fra `shared/i18n/lobby.json`; Django/Angular beskrives som consumers af samme registry og ikke som parallelle kontrakter.
|
||||
|
||||
## MVP-critical parity summary
|
||||
|
||||
- Frontend UI gameplay keys checked: **16** → `OK`
|
||||
- Frontend error keys checked: **7** → `OK`
|
||||
- Backend gameplay/error codes checked: **9** → `OK`
|
||||
- Distinct frontend error keys reached from backend MVP flow: **6** (`join_failed, nickname_invalid, nickname_taken, session_code_required, session_not_found, start_round_failed`)
|
||||
|
||||
Status: **Shared locale matrix is aligned (`en`, `da`) and backend→frontend error handling is contract-complete for MVP-critical flow.**
|
||||
|
||||
## Django ↔ Angular parity matrix (MVP-critical error contract)
|
||||
|
||||
| Backend code (`backend.error_codes.*`) | Django message key (`backend.errors.*`) | Angular key (`frontend.errors.*`) | Locales `en/da` | Parity note |
|
||||
|---|---|---|---|---|
|
||||
| `session_code_required` | `session_code_required` | `session_code_required` | `OK` | 1:1 |
|
||||
| `nickname_invalid` | `nickname_invalid` | `nickname_invalid` | `OK` | 1:1 |
|
||||
| `session_not_found` | `session_not_found` | `session_not_found` | `OK` | 1:1 |
|
||||
| `session_not_joinable` | `session_not_joinable` | `join_failed` | `OK` | mapped alias |
|
||||
| `nickname_taken` | `nickname_taken` | `nickname_taken` | `OK` | 1:1 |
|
||||
| `category_slug_required` | `category_slug_required` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `category_not_found` | `category_not_found` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `round_start_invalid_phase` | `round_start_invalid_phase` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
| `round_already_configured` | `round_already_configured` | `start_round_failed` | `OK` | many:1 collapse |
|
||||
|
||||
## Scope notes
|
||||
|
||||
- **Django** consumes backend codes/messages directly from `shared/i18n/lobby.json` via `lobby/i18n.py`.
|
||||
- **Angular** consumes the same registry via `frontend/shared/i18n/lobby-loader.ts` and runtime helpers in `frontend/angular/src/app/lobby-i18n.ts`.
|
||||
- **Parity in MVP** is therefore strongest on the shared error contract and locale matrix; gameplay UI labels are frontend-owned but still live in the same registry.
|
||||
|
||||
## Verified MVP gameplay UI keyspace present in the shared registry
|
||||
|
||||
- `frontend.ui.host.title`
|
||||
- `frontend.ui.player.title`
|
||||
- `frontend.ui.common.session_code`
|
||||
- `frontend.ui.player.nickname`
|
||||
- `frontend.ui.player.join`
|
||||
- `frontend.ui.host.start_round`
|
||||
- `frontend.ui.host.show_question`
|
||||
- `frontend.ui.player.lie_label`
|
||||
- `frontend.ui.player.submit_lie`
|
||||
- `frontend.ui.player.submit_guess`
|
||||
- `frontend.ui.host.mix_answers`
|
||||
- `frontend.ui.host.calculate_scores`
|
||||
- `frontend.ui.host.load_scoreboard`
|
||||
- `frontend.ui.host.final_leaderboard`
|
||||
- `frontend.ui.player.final_leaderboard`
|
||||
- `frontend.ui.common.points_short`
|
||||
|
||||
## Concrete deviations / follow-up items
|
||||
|
||||
1. **Error granularity collapse remains intentional**: backend codes `category_slug_required, category_not_found, round_start_invalid_phase, round_already_configured` all map to `frontend.errors.start_round_failed`. Follow-up only if product wants case-specific Angular copy instead of one shared host failure message.
|
||||
2. **Frontend-only fallback copy is not mirrored in Django**: `frontend.errors.unknown` and `frontend.errors.session_fetch_failed` are Angular-side resilience keys, not backend contract keys. Follow-up if API responses should expose stable backend equivalents for these states.
|
||||
3. **Gameplay UI labels are registry-shared but not backend-rendered**: `frontend.ui.host.*`, `frontend.ui.player.*`, and `frontend.ui.common.*` are available in the shared artifact, but Django currently consumes only the backend error slice. Follow-up only if server-rendered views must guarantee the same UI label surface as Angular.
|
||||
|
||||
## Re-run
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
python3 scripts/report_i18n_parity.py
|
||||
python3 scripts/check_i18n_parity_artifact.py
|
||||
```
|
||||
@@ -23,11 +23,14 @@ Formål: levere et lille, ensartet evidensformat for release-nær gameplay-smoke
|
||||
- Active category/questions present: <yes/no>
|
||||
- Participants: host + <N> players
|
||||
- `USE_SPA_UI`: <on/off>
|
||||
- `WPP_SPA_ASSET_VERSION`: <release-token/sha>
|
||||
- UI route used:
|
||||
- OFF (legacy): `/lobby/ui/host` + `/lobby/ui/player`
|
||||
- ON (SPA shell): `/lobby/ui/host/<spa-path>` + `/lobby/ui/player`
|
||||
|
||||
#### Checks (PASS/FAIL)
|
||||
0. Same release-window verification
|
||||
- OFF + ON smoke kørt i samme release-vindue: <pass/fail>
|
||||
1. Cutover route sanity
|
||||
- Flag OFF serves legacy UI templates: <pass/fail>
|
||||
- Flag ON serves SPA shell on expected path(s): <pass/fail>
|
||||
@@ -39,6 +42,19 @@ Formål: levere et lille, ensartet evidensformat for release-nær gameplay-smoke
|
||||
- next round transitions: <pass/fail>
|
||||
- final leaderboard visible: <pass/fail>
|
||||
|
||||
#### Smoke-gate decision (før `USE_SPA_UI=true`)
|
||||
- Gate status: <GREEN/RED>
|
||||
- Gate criteria met:
|
||||
- [ ] Cutover route sanity = PASS (OFF + ON)
|
||||
- [ ] Full gameplay round = PASS
|
||||
- [ ] Next-round/final leaderboard sanity = PASS
|
||||
- [ ] Ingen nye blocker-regressioner i host/player flow
|
||||
|
||||
#### Rollback checkpoint
|
||||
- Rollback required: <yes/no>
|
||||
- Trigger reason (if yes): <kort trigger>
|
||||
- Rollback done (`USE_SPA_UI=false`) verified: <yes/no>
|
||||
|
||||
#### Evidence pointers
|
||||
- Command(s): `<exact command(s)>`
|
||||
- UI notes/screenshots/log refs: <short refs>
|
||||
|
||||
@@ -20,4 +20,29 @@
|
||||
9. Host: Beregn score og Vis scoreboard.
|
||||
10. Host: Næste runde eller Afslut spil.
|
||||
|
||||
## Smoke-gate (staging cutover)
|
||||
`USE_SPA_UI` må kun aktiveres i staging når følgende er opfyldt:
|
||||
- Cutover route sanity er PASS for både OFF (legacy) og ON (SPA shell).
|
||||
- Én fuld gameplay-runde til scoreboard er PASS.
|
||||
- Next-round/final leaderboard sanity er PASS.
|
||||
- Ingen nye blocker-regressioner i host/player kerneflow.
|
||||
|
||||
## Samme release-vindue: SPA OFF + ON verifikation
|
||||
Kør begge checks i samme release-vindue (samme deploy/artifact version):
|
||||
|
||||
1. **OFF-pass (legacy)**
|
||||
- `USE_SPA_UI=false`
|
||||
- Verificér legacy routes + fuld runde.
|
||||
2. **ON-pass (SPA)**
|
||||
- `USE_SPA_UI=true`
|
||||
- Behold samme release artifact og kun toggl flag/version-token ved behov.
|
||||
- Verificér SPA shell routes + fuld runde.
|
||||
3. Dokumentér begge pass i samme smoke-artifact med UTC timestamps og `WPP_SPA_ASSET_VERSION`.
|
||||
|
||||
## Rollback check points
|
||||
Skift straks tilbage til `USE_SPA_UI=false` hvis en gate fejler:
|
||||
1. Verificér legacy routes (`/lobby/ui/host` + `/lobby/ui/player`) fungerer igen.
|
||||
2. Log rollback trigger + kort repro i smoke artifact.
|
||||
3. Opret/link blocker issue før nyt cutover-forsøg.
|
||||
|
||||
Resultat: En fuld runde kan køres uden rå API-kald fra terminal.
|
||||
|
||||
34
docs/i18n-drift-check.md
Normal file
34
docs/i18n-drift-check.md
Normal file
@@ -0,0 +1,34 @@
|
||||
# i18n key manifest + drift check
|
||||
|
||||
Issue: #240
|
||||
|
||||
This repo keeps shared lobby keyspaces in two files:
|
||||
|
||||
- Contract source: `shared/i18n/lobby.json`
|
||||
- Key manifest: `shared/i18n/key-manifest.json`
|
||||
|
||||
The manifest is intentionally small and explicit. It lists:
|
||||
|
||||
- Supported locales (`locales`)
|
||||
- Frontend error key set (`frontend_error_keys`)
|
||||
- Backend error code set (`backend_error_codes`)
|
||||
- Backend translation key set (`backend_error_keys`)
|
||||
- Optional contract-only aliases (`allowed_contract_only_backend_codes`)
|
||||
|
||||
## Local check
|
||||
|
||||
Run the read-only drift checker from repo root:
|
||||
|
||||
```bash
|
||||
python3 scripts/check_i18n_drift.py
|
||||
```
|
||||
|
||||
The script returns non-zero when it detects drift, including:
|
||||
|
||||
- key set mismatch between manifest and shared catalog
|
||||
- missing backend→frontend mapping coverage
|
||||
- mapping to unknown frontend keys
|
||||
- mappings for unknown backend codes
|
||||
- missing/empty locale translations (`en`/`da`)
|
||||
|
||||
No CI gating changes are included in this task; this is a local guardrail.
|
||||
69
docs/i18n-keymap.md
Normal file
69
docs/i18n-keymap.md
Normal file
@@ -0,0 +1,69 @@
|
||||
# i18n key-map bootstrap (Angular host/player MVP)
|
||||
|
||||
Issue: #220
|
||||
Scope: Lobby → Join → Start round → Round → Reveal → Scoreboard
|
||||
Locales: `en`, `da`
|
||||
|
||||
This document is the gameplay key-namespace map for Angular host/player MVP.
|
||||
It maps existing text keys only (no feature expansion) and stays aligned with `shared/i18n/lobby.json`.
|
||||
|
||||
## Key families
|
||||
|
||||
- `host` — `frontend.ui.host.*` host-facing gameplay actions and status text.
|
||||
- `player` — `frontend.ui.player.*` player-facing gameplay actions and status text.
|
||||
- `system` — shared UI labels used across host/player views (implemented under `frontend.ui.common.*` in `shared/i18n/lobby.json`).
|
||||
- `errors` — user-facing error keys shown by frontend (`frontend.errors.*`) plus backend code → frontend key bridge via `backend.error_codes.*` / `contract.backend_to_frontend_error_keys.*`.
|
||||
|
||||
## Gameplay flow key map
|
||||
|
||||
| Flow step | Family | Key | en | da |
|
||||
|---|---|---|---|---|
|
||||
| Lobby | `host` | `host.title` | Host gameplay flow | Vært gameplay-flow |
|
||||
| Lobby | `player` | `player.title` | Player gameplay flow | Spiller gameplay-flow |
|
||||
| Lobby | `system` (`frontend.ui.common`) | `common.session_code` | Session code | Sessionskode |
|
||||
| Lobby | `player` | `player.nickname` | Nickname | Kaldenavn |
|
||||
| Join | `player` | `player.join` | Join | Join |
|
||||
| Start round | `host` | `host.start_round` | Start round | Start runde |
|
||||
| Round | `host` | `host.show_question` | Show question | Vis spørgsmål |
|
||||
| Round | `player` | `player.lie_label` | Lie | Løgn |
|
||||
| Round | `player` | `player.submit_lie` | Submit lie | Send løgn |
|
||||
| Round | `player` | `player.submit_guess` | Submit guess | Send gæt |
|
||||
| Reveal | `host` | `host.mix_answers` | Mix answers → guess | Bland svar → gæt |
|
||||
| Reveal | `host` | `host.calculate_scores` | Calculate scores → reveal | Udregn score → afslør |
|
||||
| Scoreboard | `host` | `host.load_scoreboard` | Load scoreboard | Hent scoreboard |
|
||||
| Scoreboard | `host` | `host.final_leaderboard` | Final leaderboard | Finale leaderboard |
|
||||
| Scoreboard | `player` | `player.final_leaderboard` | Final leaderboard | Finale leaderboard |
|
||||
| Scoreboard | `system` (`frontend.ui.common`) | `common.points_short` | pts | point |
|
||||
|
||||
## Frontend error keys used in flow scope
|
||||
|
||||
| Error family | Key | en | da |
|
||||
|---|---|---|---|
|
||||
| Join | `frontend.errors.session_code_required` | Session code is required. | Sessionskoden er påkrævet. |
|
||||
| Join | `frontend.errors.session_not_found` | Session code is invalid or the session no longer exists. | Sessionskoden er ugyldig, eller sessionen findes ikke længere. |
|
||||
| Join | `frontend.errors.nickname_invalid` | Nickname must be between 2 and 40 characters. | Kaldenavn skal være mellem 2 og 40 tegn. |
|
||||
| Join | `frontend.errors.nickname_taken` | Nickname is already taken. | Kaldenavnet er allerede taget. |
|
||||
| Join | `frontend.errors.join_failed` | Join failed. Check code or nickname and try again. | Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen. |
|
||||
| Start round | `frontend.errors.start_round_failed` | Could not start round. Refresh the lobby and try again. | Kunne ikke starte runden. Opdater lobbyen og prøv igen. |
|
||||
| Any | `frontend.errors.unknown` | Action failed. Refresh status and try again. | Handlingen fejlede. Opdater status og prøv igen. |
|
||||
|
||||
## Backend→frontend mapping for gameplay errors
|
||||
|
||||
Mapped in `contract.backend_to_frontend_error_keys` (source: `shared/i18n/lobby.json`):
|
||||
|
||||
> Note: `host_only_action` is **not** part of the current shared contract mapping and is intentionally not listed here.
|
||||
|
||||
- `session_code_required` → `session_code_required`
|
||||
- `nickname_invalid` → `nickname_invalid`
|
||||
- `session_not_found` → `session_not_found`
|
||||
- `session_not_joinable` → `join_failed`
|
||||
- `nickname_taken` → `nickname_taken`
|
||||
- `category_slug_required` → `start_round_failed`
|
||||
- `category_not_found` → `start_round_failed`
|
||||
- `round_start_invalid_phase` → `start_round_failed`
|
||||
- `round_already_configured` → `start_round_failed`
|
||||
|
||||
## Notes
|
||||
|
||||
- This is a bootstrap key-map doc for MVP mergeability.
|
||||
- The key/value source of truth remains `shared/i18n/lobby.json`.
|
||||
28
docs/issue-180-flow-log.md
Normal file
28
docs/issue-180-flow-log.md
Normal file
@@ -0,0 +1,28 @@
|
||||
# Issue #180 – SPA gameplay flow evidence
|
||||
|
||||
## Flow log (host + player, no page reload)
|
||||
|
||||
1. Host opens SPA host shell and loads scoreboard (`GET /lobby/sessions/{code}/scoreboard`).
|
||||
2. Host starts next round (`POST /lobby/sessions/{code}/rounds/next`).
|
||||
3. Host shell refreshes session state in-place (`GET /lobby/sessions/{code}`) and clears old scoreboard/final leaderboard payloads.
|
||||
4. Player shell performs periodic session refresh while online (3s cadence) and transitions from `scoreboard` to `lobby` without page reload.
|
||||
5. Host finishes game (`POST /lobby/sessions/{code}/finish`) and renders final leaderboard directly in SPA shell.
|
||||
6. Player shell reads `finished` state and renders final leaderboard in SPA (sorted by score).
|
||||
7. Error/retry paths available:
|
||||
- Host: next-round and finish-game retry buttons with explicit error feedback.
|
||||
- Player: reconnect + submit retry feedback.
|
||||
|
||||
## Test output snapshot
|
||||
|
||||
Command:
|
||||
|
||||
```bash
|
||||
cd frontend/angular
|
||||
npm test -- --run src/app/features/host/host-shell.component.spec.ts src/app/features/player/player-shell.component.spec.ts
|
||||
```
|
||||
|
||||
Result:
|
||||
|
||||
- `host-shell.component.spec.ts`: 6 passed
|
||||
- `player-shell.component.spec.ts`: 7 passed
|
||||
- Total: 13 passed, 0 failed
|
||||
@@ -12,9 +12,63 @@ Sæt env var pr. miljø:
|
||||
Backward compatibility under cutover:
|
||||
- Hvis `USE_SPA_UI` ikke er sat, bruges `WPP_SPA_ENABLED` som fallback.
|
||||
|
||||
## Static asset versioning/cache-busting (hardening)
|
||||
Formål: sikre at browser/proxy/CDN hurtigt henter ny SPA bundle i release-vinduet uden at kræve hard refresh.
|
||||
|
||||
- `WPP_SPA_ASSET_BASE` peger fortsat på build-output (`/static/frontend/angular/browser`).
|
||||
- `WPP_SPA_ASSET_VERSION` injiceres i SPA shell URLs som query-param (`?v=<version>`).
|
||||
- Anbefalet værdi for `WPP_SPA_ASSET_VERSION`: release-tag eller kort commit SHA.
|
||||
- Ved rollback sættes `WPP_SPA_ASSET_VERSION` til den tidligere kendte stabile release-værdi.
|
||||
|
||||
Eksempel (staging/prod env):
|
||||
|
||||
```env
|
||||
USE_SPA_UI=true
|
||||
WPP_SPA_ASSET_BASE=/static/frontend/angular/browser
|
||||
WPP_SPA_ASSET_VERSION=rel-2026-03-01-bb82357
|
||||
```
|
||||
|
||||
## Staging rollout-checkliste (`USE_SPA_UI`)
|
||||
1. **Baseline (flag OFF)**
|
||||
- Bekræft at staging kører med `USE_SPA_UI=false`.
|
||||
- Kør gameplay smoke på legacy routes (`/lobby/ui/host` + `/lobby/ui/player`).
|
||||
2. **Smoke-gate før aktivering (skal være grøn)**
|
||||
- Cutover route sanity = PASS for både OFF og ON checks.
|
||||
- Full gameplay round (join/start/round/scoreboard) = PASS.
|
||||
- Next-round/final leaderboard sanity = PASS.
|
||||
- Ingen nye blocker-regressioner i host/player kerneflow.
|
||||
3. **Kontrolleret aktivering i staging**
|
||||
- Sæt `USE_SPA_UI=true` i staging miljøet.
|
||||
- Kør smoke-flow igen med SPA-route-verifikation.
|
||||
4. **Post-cutover dokumentation**
|
||||
- Log evidens med commit/head SHA, UTC timestamp og gate-status.
|
||||
|
||||
## Rollback playbook (`USE_SPA_UI`) — mål: <10 min
|
||||
Rollback til legacy (`USE_SPA_UI=false`) udføres straks hvis et checkpoint fejler:
|
||||
- Forkert route/shell for valgt flag i cutover route sanity.
|
||||
- Gameplay smoke kan ikke gennemføres til scoreboard/final leaderboard.
|
||||
- Kritisk regression i host/player flow under smoke.
|
||||
|
||||
Trin-for-trin:
|
||||
1. Sæt `USE_SPA_UI=false` i deploy-env.
|
||||
2. Sæt `WPP_SPA_ASSET_VERSION` til sidste stabile release-token.
|
||||
3. Deploy/reload app-processer.
|
||||
4. Verificér legacy routes: `/lobby/ui/host` + `/lobby/ui/player`.
|
||||
5. Kør hurtig smoke sanity (join/start/scoreboard path).
|
||||
6. Log UTC tid, trigger, release-token og resultat i smoke artifact.
|
||||
|
||||
Target: rollback + sanity-verifikation inden for 10 minutter.
|
||||
|
||||
## Verifikation
|
||||
- Flag OFF: `UiScreenTests.test_legacy_templates_are_used_when_spa_flag_is_off`
|
||||
- Flag ON (host): `UiScreenTests.test_host_screen_can_render_angular_shell_when_feature_flag_enabled`
|
||||
- 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`.
|
||||
|
||||
247
frontend/angular/src/app/api-contract-smoke.spec.ts
Normal file
247
frontend/angular/src/app/api-contract-smoke.spec.ts
Normal file
@@ -0,0 +1,247 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createAngularApiClient, type AngularHttpClientLike } from '../../../src/api/angular-client';
|
||||
|
||||
describe('SPA Angular API contract smoke (host/player foundation)', () => {
|
||||
it('smoke-checks canonical host/player endpoint contracts', async () => {
|
||||
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
|
||||
if (url === '/lobby/sessions/ABCD12') {
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 },
|
||||
players: [
|
||||
{ id: 2, nickname: 'Maja', score: 0, is_connected: true },
|
||||
{ id: 3, nickname: 'Bo', score: 0, is_connected: true }
|
||||
],
|
||||
round_question: {
|
||||
id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Q?',
|
||||
shown_at: '2026-03-01T18:00:00Z',
|
||||
answers: [{ text: 'A' }, { text: 'B' }]
|
||||
},
|
||||
phase_view_model: {
|
||||
status: 'lobby',
|
||||
round_number: 1,
|
||||
players_count: 2,
|
||||
constraints: {
|
||||
min_players_to_start: 2,
|
||||
max_players_mvp: 8,
|
||||
min_players_reached: true,
|
||||
max_players_allowed: true
|
||||
},
|
||||
host: {
|
||||
can_start_round: true,
|
||||
can_show_question: true,
|
||||
can_mix_answers: true,
|
||||
can_calculate_scores: true,
|
||||
can_reveal_scoreboard: true,
|
||||
can_start_next_round: true,
|
||||
can_finish_game: true
|
||||
},
|
||||
player: {
|
||||
can_join: true,
|
||||
can_submit_lie: true,
|
||||
can_submit_guess: true,
|
||||
can_view_final_result: false
|
||||
}
|
||||
}
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/scoreboard') {
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||
leaderboard: [
|
||||
{ id: 9, nickname: 'Maja', score: 200 },
|
||||
{ id: 10, nickname: 'Bo', score: 150 }
|
||||
]
|
||||
} as T;
|
||||
}
|
||||
|
||||
throw { status: 404, error: { error: 'Not found' } };
|
||||
});
|
||||
|
||||
const post = vi.fn<AngularHttpClientLike['post']>(async <T>(url: string, body: unknown) => {
|
||||
if (url === '/lobby/sessions/join') {
|
||||
expect(body).toEqual({ code: 'ABCD12', nickname: 'Maja' });
|
||||
return {
|
||||
player: { id: 9, nickname: 'Maja', session_token: 'session-token-1', score: 0 },
|
||||
session: { code: 'ABCD12', status: 'lobby' }
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/rounds/start') {
|
||||
expect(body).toEqual({ category_slug: 'history' });
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'lie', current_round: 1 },
|
||||
round: { number: 1, category: { slug: 'history', name: 'History' } }
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/questions/show') {
|
||||
expect(body).toEqual({});
|
||||
return {
|
||||
round_question: {
|
||||
id: 77,
|
||||
prompt: 'Q?',
|
||||
round_number: 1,
|
||||
shown_at: '2026-03-01T18:00:00Z',
|
||||
lie_deadline_at: '2026-03-01T18:00:30Z'
|
||||
},
|
||||
config: { lie_seconds: 30 }
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/questions/77/answers/mix') {
|
||||
expect(body).toEqual({});
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'guess', current_round: 1 },
|
||||
round_question: { id: 77, round_number: 1 },
|
||||
answers: [{ text: 'A' }, { text: 'B' }]
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/questions/77/scores/calculate') {
|
||||
expect(body).toEqual({});
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||
round_question: { id: 77, round_number: 1 },
|
||||
events_created: 2,
|
||||
leaderboard: [
|
||||
{ id: 9, nickname: 'Maja', score: 200 },
|
||||
{ id: 10, nickname: 'Bo', score: 150 }
|
||||
]
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/rounds/next') {
|
||||
expect(body).toEqual({});
|
||||
return { session: { code: 'ABCD12', status: 'lie', current_round: 2 } } as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/finish') {
|
||||
expect(body).toEqual({});
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'finished', current_round: 2 },
|
||||
winner: { id: 9, nickname: 'Maja', score: 250 },
|
||||
leaderboard: [
|
||||
{ id: 9, nickname: 'Maja', score: 250 },
|
||||
{ id: 10, nickname: 'Bo', score: 150 }
|
||||
]
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/questions/77/lies/submit') {
|
||||
expect(body).toEqual({ player_id: 9, session_token: 'session-token-1', text: 'my lie' });
|
||||
return {
|
||||
lie: {
|
||||
id: 501,
|
||||
player_id: 9,
|
||||
round_question_id: 77,
|
||||
text: 'my lie',
|
||||
created_at: '2026-03-01T18:00:05Z'
|
||||
},
|
||||
window: { lie_deadline_at: '2026-03-01T18:00:30Z' }
|
||||
} as T;
|
||||
}
|
||||
|
||||
if (url === '/lobby/sessions/ABCD12/questions/77/guesses/submit') {
|
||||
expect(body).toEqual({ player_id: 9, session_token: 'session-token-1', selected_text: 'B' });
|
||||
return {
|
||||
guess: {
|
||||
id: 601,
|
||||
player_id: 9,
|
||||
round_question_id: 77,
|
||||
selected_text: 'B',
|
||||
is_correct: false,
|
||||
fooled_player_id: null,
|
||||
created_at: '2026-03-01T18:00:15Z'
|
||||
},
|
||||
window: { guess_deadline_at: '2026-03-01T18:01:00Z' }
|
||||
} as T;
|
||||
}
|
||||
|
||||
throw { status: 404, error: { error: 'Not found' } };
|
||||
});
|
||||
|
||||
const client = createAngularApiClient({ get, post } as AngularHttpClientLike);
|
||||
|
||||
const session = await client.getSession(' abcd12 ');
|
||||
expect(session.ok).toBe(true);
|
||||
if (session.ok) {
|
||||
expect(session.data.session.code).toBe('ABCD12');
|
||||
expect(session.data.phase_view_model.host.can_start_next_round).toBe(true);
|
||||
expect(session.data.phase_view_model.player.can_submit_guess).toBe(true);
|
||||
}
|
||||
|
||||
expect((await client.joinSession({ code: ' abcd12 ', nickname: ' Maja ' })).ok).toBe(true);
|
||||
expect((await client.startRound(' abcd12 ', { category_slug: 'history' })).ok).toBe(true);
|
||||
expect((await client.showQuestion(' abcd12 ')).ok).toBe(true);
|
||||
expect((await client.mixAnswers(' abcd12 ', 77)).ok).toBe(true);
|
||||
expect((await client.calculateScores(' abcd12 ', 77)).ok).toBe(true);
|
||||
expect((await client.getScoreboard(' abcd12 ')).ok).toBe(true);
|
||||
expect((await client.startNextRound(' abcd12 ')).ok).toBe(true);
|
||||
expect((await client.finishGame(' abcd12 ')).ok).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await client.submitLie(' abcd12 ', 77, {
|
||||
player_id: 9,
|
||||
session_token: 'session-token-1',
|
||||
text: 'my lie'
|
||||
})
|
||||
).ok
|
||||
).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await client.submitGuess(' abcd12 ', 77, {
|
||||
player_id: 9,
|
||||
session_token: 'session-token-1',
|
||||
selected_text: 'B'
|
||||
})
|
||||
).ok
|
||||
).toBe(true);
|
||||
|
||||
expect(get).toHaveBeenNthCalledWith(1, '/lobby/sessions/ABCD12', { withCredentials: true });
|
||||
expect(get).toHaveBeenNthCalledWith(2, '/lobby/sessions/ABCD12/scoreboard', { withCredentials: true });
|
||||
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'/lobby/sessions/join',
|
||||
{ code: 'ABCD12', nickname: 'Maja' },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'/lobby/sessions/ABCD12/rounds/start',
|
||||
{ category_slug: 'history' },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(3, '/lobby/sessions/ABCD12/questions/show', {}, { withCredentials: true });
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
4,
|
||||
'/lobby/sessions/ABCD12/questions/77/answers/mix',
|
||||
{},
|
||||
{ withCredentials: true }
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
5,
|
||||
'/lobby/sessions/ABCD12/questions/77/scores/calculate',
|
||||
{},
|
||||
{ withCredentials: true }
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(6, '/lobby/sessions/ABCD12/rounds/next', {}, { withCredentials: true });
|
||||
expect(post).toHaveBeenNthCalledWith(7, '/lobby/sessions/ABCD12/finish', {}, { withCredentials: true });
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
8,
|
||||
'/lobby/sessions/ABCD12/questions/77/lies/submit',
|
||||
{ player_id: 9, session_token: 'session-token-1', text: 'my lie' },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
expect(post).toHaveBeenNthCalledWith(
|
||||
9,
|
||||
'/lobby/sessions/ABCD12/questions/77/guesses/submit',
|
||||
{ player_id: 9, session_token: 'session-token-1', selected_text: 'B' },
|
||||
{ withCredentials: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
.shell { font-family: Arial, sans-serif; margin: 1rem; }
|
||||
.shell__header { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd; padding-bottom: 0.75rem; }
|
||||
.shell__header { display: flex; flex-wrap: wrap; gap: 0.75rem; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd; padding-bottom: 0.75rem; }
|
||||
.shell__header nav { display: flex; gap: 0.75rem; }
|
||||
.shell__content { margin-top: 1rem; }
|
||||
.locale-picker { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.95rem; }
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
<main class="shell">
|
||||
<header class="shell__header">
|
||||
<h1>WPP Angular Shell</h1>
|
||||
<h1>{{ copy('app.title') }}</h1>
|
||||
<nav>
|
||||
<a routerLink="/host">Host</a>
|
||||
<a routerLink="/player">Player</a>
|
||||
<a routerLink="/host">{{ copy('app.host_nav') }}</a>
|
||||
<a routerLink="/player">{{ copy('app.player_nav') }}</a>
|
||||
</nav>
|
||||
<label class="locale-picker">
|
||||
{{ copy('app.language_label') }}
|
||||
<select [ngModel]="locale" (ngModelChange)="setLocale($event)">
|
||||
<option value="en">English</option>
|
||||
<option value="da">Dansk</option>
|
||||
</select>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="shell__content">
|
||||
<section class="shell__content" [attr.data-wpp-locale]="locale">
|
||||
<router-outlet></router-outlet>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
@@ -1,20 +1,33 @@
|
||||
import { Component, inject } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { Router, RouterLink, RouterOutlet } from '@angular/router';
|
||||
|
||||
import { resolvePreferredLocale, setPreferredLocale, t } from './lobby-i18n';
|
||||
|
||||
@Component({
|
||||
selector: 'app-root',
|
||||
standalone: true,
|
||||
imports: [RouterOutlet, RouterLink],
|
||||
imports: [RouterOutlet, RouterLink, FormsModule],
|
||||
templateUrl: './app.component.html',
|
||||
styleUrl: './app.component.css',
|
||||
})
|
||||
export class AppComponent {
|
||||
private readonly router = inject(Router);
|
||||
|
||||
locale = resolvePreferredLocale();
|
||||
|
||||
constructor() {
|
||||
const shellRoute = document.body.dataset['wppShellRoute'];
|
||||
if (shellRoute?.startsWith('/host') || shellRoute?.startsWith('/player')) {
|
||||
void this.router.navigateByUrl(shellRoute);
|
||||
}
|
||||
}
|
||||
|
||||
copy(key: string): string {
|
||||
return t(key, this.locale);
|
||||
}
|
||||
|
||||
setLocale(locale: string): void {
|
||||
this.locale = setPreferredLocale(locale);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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(),
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
@@ -245,20 +245,22 @@ describe('HostShellComponent gameplay wiring', () => {
|
||||
expect(component.finishError).toContain('Session code is required');
|
||||
});
|
||||
|
||||
it('bootstraps refresh from resolver route context on init', () => {
|
||||
it('syncs host hash-route with latest phase after refresh without page reload', async () => {
|
||||
const fetchMock: FetchMock = vi.fn().mockResolvedValue(jsonResponse(200, sessionDetailPayload('guess', { roundQuestionId: 77 })));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const replaceState = vi.fn();
|
||||
vi.stubGlobal('window', {
|
||||
sessionStorage: {
|
||||
getItem: vi.fn().mockReturnValue(null),
|
||||
setItem: vi.fn(),
|
||||
},
|
||||
location: { hash: '#/host/lobby/ABCD12' },
|
||||
history: { state: null, replaceState },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn() },
|
||||
});
|
||||
|
||||
const component = new HostShellComponent({ snapshot: { data: { routeContext: { sessionCode: 'ab12' } } } } as never);
|
||||
const refreshSpy = vi.spyOn(component, 'refreshSession').mockResolvedValue();
|
||||
const component = new HostShellComponent();
|
||||
component.sessionCode = 'ABCD12';
|
||||
|
||||
component.ngOnInit();
|
||||
await component.refreshSession();
|
||||
|
||||
expect(component.sessionCode).toBe('AB12');
|
||||
expect(refreshSpy).toHaveBeenCalledOnce();
|
||||
expect(replaceState).toHaveBeenCalledWith(null, '', '#/host/guess/ABCD12');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnInit, Optional } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
|
||||
import { createApiClient } from '../../../../../src/api/client';
|
||||
import type { FinishGameResponse, ScoreboardResponse } from '../../../../../src/api/types';
|
||||
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
|
||||
import type { RouteSessionContext } from '../../session-route-context';
|
||||
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n';
|
||||
|
||||
interface SessionDetail {
|
||||
session: { code: string; status: string; current_round: number };
|
||||
@@ -22,40 +21,41 @@ type LeaderboardResponse = FinishGameResponse;
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule],
|
||||
template: `
|
||||
<h2>Host SPA gameplay flow</h2>
|
||||
<h2>{{ copy('host.title') }}</h2>
|
||||
|
||||
<div class="panel">
|
||||
<label>Session code <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>Category <input [(ngModel)]="categorySlug" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">Refresh</button>
|
||||
<button (click)="startRound()" [disabled]="loading">Start round</button>
|
||||
<button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">Show question</button>
|
||||
<button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">Mix answers → guess</button>
|
||||
<button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">Calculate scores → reveal</button>
|
||||
<button (click)="loadScoreboard()" [disabled]="loading">Load scoreboard</button>
|
||||
<button (click)="startNextRound()" [disabled]="loading">Start next round</button>
|
||||
<button (click)="finishGame()" [disabled]="loading">Finish game</button>
|
||||
<button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">Retry scoreboard</button>
|
||||
<button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">Retry next round</button>
|
||||
<button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">Retry finish game</button>
|
||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>{{ copy('host.category') }} <input [(ngModel)]="categorySlug" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||
<button (click)="startRound()" [disabled]="loading">{{ copy('host.start_round') }}</button>
|
||||
<button (click)="showQuestion()" [disabled]="loading || !roundQuestionId">{{ copy('host.show_question') }}</button>
|
||||
<button (click)="mixAnswers()" [disabled]="loading || !roundQuestionId">{{ copy('host.mix_answers') }}</button>
|
||||
<button (click)="calculateScores()" [disabled]="loading || !roundQuestionId">{{ copy('host.calculate_scores') }}</button>
|
||||
<button (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.load_scoreboard') }}</button>
|
||||
<button (click)="startNextRound()" [disabled]="loading">{{ copy('host.start_next_round') }}</button>
|
||||
<button (click)="finishGame()" [disabled]="loading">{{ copy('host.finish_game') }}</button>
|
||||
<button *ngIf="scoreboardError" (click)="loadScoreboard()" [disabled]="loading">{{ copy('host.retry_scoreboard') }}</button>
|
||||
<button *ngIf="nextRoundError" (click)="startNextRound()" [disabled]="loading">{{ copy('host.retry_next_round') }}</button>
|
||||
<button *ngIf="finishError" (click)="finishGame()" [disabled]="loading">{{ copy('host.retry_finish') }}</button>
|
||||
</div>
|
||||
|
||||
<p *ngIf="session" class="hint">{{ copy('host.audio_locale_hint') }}: {{ locale }}</p>
|
||||
<p *ngIf="error" class="error">{{ error }}</p>
|
||||
<p *ngIf="scoreboardError" class="error">{{ scoreboardError }}</p>
|
||||
<p *ngIf="nextRoundError" class="error">{{ nextRoundError }}</p>
|
||||
<p *ngIf="finishError" class="error">{{ finishError }}</p>
|
||||
|
||||
<div *ngIf="session" class="panel">
|
||||
<p><strong>Status:</strong> {{ session.session.status }} · round {{ session.session.current_round }}</p>
|
||||
<p><strong>Round question id:</strong> {{ roundQuestionId || '-' }}</p>
|
||||
<p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p>
|
||||
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }} · {{ copy('common.round') }} {{ session.session.current_round }}</p>
|
||||
<p><strong>{{ copy('common.round_question_id') }}:</strong> {{ roundQuestionId || '-' }}</p>
|
||||
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
|
||||
<ul>
|
||||
<li *ngFor="let p of session.players">{{ p.nickname }}: {{ p.score }}</li>
|
||||
</ul>
|
||||
<pre *ngIf="scoreboardPayload">{{ scoreboardPayload }}</pre>
|
||||
<div *ngIf="finalLeaderboard.length">
|
||||
<h3>Final leaderboard</h3>
|
||||
<p *ngIf="finalWinner"><strong>Winner:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} pts)</p>
|
||||
<h3>{{ copy('host.final_leaderboard') }}</h3>
|
||||
<p *ngIf="finalWinner"><strong>{{ copy('host.winner') }}:</strong> {{ finalWinner.nickname }} ({{ finalWinner.score }} {{ copy('common.points_short') }})</p>
|
||||
<ol>
|
||||
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||
</ol>
|
||||
@@ -64,7 +64,10 @@ type LeaderboardResponse = FinishGameResponse;
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class HostShellComponent implements OnInit {
|
||||
export class HostShellComponent implements OnInit, OnDestroy {
|
||||
locale = resolvePreferredLocale();
|
||||
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
|
||||
|
||||
sessionCode = '';
|
||||
categorySlug = 'general';
|
||||
roundQuestionId = '';
|
||||
@@ -81,16 +84,19 @@ export class HostShellComponent implements OnInit {
|
||||
|
||||
private readonly api = createApiClient();
|
||||
private readonly controller = createVerticalSliceController(this.api);
|
||||
|
||||
constructor(@Optional() private readonly route: ActivatedRoute | null = null) {}
|
||||
private unsubscribeLocale: (() => void) | null = null;
|
||||
|
||||
ngOnInit(): void {
|
||||
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
|
||||
this.locale = locale;
|
||||
});
|
||||
if (typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
const routeContext = this.route?.snapshot.data['routeContext'] as RouteSessionContext | undefined;
|
||||
const codeFromRoute = routeContext?.sessionCode ?? '';
|
||||
const hashRoute = window.location.hash.replace(/^#\/?/, '');
|
||||
const match = hashRoute.match(/^host(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
|
||||
const codeFromRoute = match?.[1] ?? '';
|
||||
const storedCode = window.sessionStorage.getItem('wpp.host-session-code') ?? '';
|
||||
const candidate = codeFromRoute || storedCode;
|
||||
|
||||
@@ -103,6 +109,15 @@ export class HostShellComponent implements OnInit {
|
||||
void this.refreshSession();
|
||||
}
|
||||
|
||||
ngOnDestroy(): void {
|
||||
this.unsubscribeLocale?.();
|
||||
this.unsubscribeLocale = null;
|
||||
}
|
||||
|
||||
copy(key: string): string {
|
||||
return t(key, this.locale);
|
||||
}
|
||||
|
||||
private normalizeCode(value: string): string {
|
||||
return value.trim().toUpperCase();
|
||||
}
|
||||
@@ -141,7 +156,7 @@ export class HostShellComponent implements OnInit {
|
||||
try {
|
||||
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -150,8 +165,9 @@ export class HostShellComponent implements OnInit {
|
||||
if (this.session.session.status !== 'finished') {
|
||||
this.resetFinalLeaderboard();
|
||||
}
|
||||
this.syncRouteFromSession();
|
||||
} catch (error) {
|
||||
this.error = `Session refresh failed: ${(error as Error).message}`;
|
||||
this.error = `${this.copy('host.session_refresh_failed')}: ${(error as Error).message}`;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
@@ -161,7 +177,7 @@ export class HostShellComponent implements OnInit {
|
||||
await this.runAction(async () => {
|
||||
const state = await this.controller.startRound(this.sessionCode, this.categorySlug.trim());
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -169,6 +185,7 @@ export class HostShellComponent implements OnInit {
|
||||
this.roundQuestionId = this.session.round_question?.id ? String(this.session.round_question.id) : '';
|
||||
this.scoreboardPayload = '';
|
||||
this.resetFinalLeaderboard();
|
||||
this.syncRouteFromSession();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -208,7 +225,7 @@ export class HostShellComponent implements OnInit {
|
||||
this.scoreboardPayload = JSON.stringify(payload, null, 2);
|
||||
await this.refreshSession();
|
||||
} catch (error) {
|
||||
this.scoreboardError = `Scoreboard failed: ${(error as Error).message}`;
|
||||
this.scoreboardError = `${this.copy('host.scoreboard_failed')}: ${(error as Error).message}`;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
@@ -221,14 +238,14 @@ export class HostShellComponent implements OnInit {
|
||||
try {
|
||||
const code = this.normalizeCode(this.sessionCode);
|
||||
if (!code) {
|
||||
throw new Error('Session code is required');
|
||||
throw new Error(this.copy('host.session_code_required'));
|
||||
}
|
||||
await this.request(`/lobby/sessions/${encodeURIComponent(code)}/rounds/next`, 'POST', {});
|
||||
this.scoreboardPayload = '';
|
||||
this.resetFinalLeaderboard();
|
||||
await this.refreshSession();
|
||||
} catch (error) {
|
||||
this.nextRoundError = `Next round failed: ${(error as Error).message}`;
|
||||
this.nextRoundError = `${this.copy('host.next_round_failed')}: ${(error as Error).message}`;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
@@ -241,7 +258,7 @@ export class HostShellComponent implements OnInit {
|
||||
try {
|
||||
const code = this.normalizeCode(this.sessionCode);
|
||||
if (!code) {
|
||||
throw new Error('Session code is required');
|
||||
throw new Error(this.copy('host.session_code_required'));
|
||||
}
|
||||
const payload = await this.request<LeaderboardResponse>(`/lobby/sessions/${encodeURIComponent(code)}/finish`, 'POST', {});
|
||||
this.finalLeaderboardPayload = JSON.stringify(payload, null, 2);
|
||||
@@ -254,7 +271,7 @@ export class HostShellComponent implements OnInit {
|
||||
this.finalWinner = payload.winner ?? this.finalLeaderboard[0] ?? null;
|
||||
await this.refreshSession();
|
||||
} catch (error) {
|
||||
this.finishError = `Finish game failed: ${(error as Error).message}`;
|
||||
this.finishError = `${this.copy('host.finish_game_failed')}: ${(error as Error).message}`;
|
||||
} finally {
|
||||
this.loading = false;
|
||||
}
|
||||
@@ -266,6 +283,25 @@ export class HostShellComponent implements OnInit {
|
||||
this.finalWinner = null;
|
||||
}
|
||||
|
||||
private syncRouteFromSession(): void {
|
||||
if (!this.session) {
|
||||
return;
|
||||
}
|
||||
|
||||
const phase = this.session.session.status || 'lobby';
|
||||
const code = this.normalizeCode(this.session.session.code || this.sessionCode);
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetPath = `#/host/${encodeURIComponent(phase)}/${encodeURIComponent(code)}`;
|
||||
if (typeof window === 'undefined' || window.location.hash === targetPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.history.replaceState(window.history.state, '', targetPath);
|
||||
}
|
||||
|
||||
private async runAction(action: () => Promise<void>): Promise<void> {
|
||||
this.loading = true;
|
||||
this.error = '';
|
||||
|
||||
@@ -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>;
|
||||
@@ -198,6 +199,30 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
expect(fetchMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
|
||||
it('auto-refreshes player session to avoid host/player state desync between rounds', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
const fetchMock: FetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('scoreboard', { roundQuestionId: null })))
|
||||
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lobby', { roundQuestionId: null })));
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.sessionCode = 'ABCD12';
|
||||
|
||||
await component.refreshSession();
|
||||
expect(component.session?.session.status).toBe('scoreboard');
|
||||
|
||||
await vi.advanceTimersByTimeAsync(3100);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(component.session?.session.status).toBe('lobby');
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('enters reconnecting state when network request fails while online', async () => {
|
||||
vi.stubGlobal('navigator', { onLine: true });
|
||||
|
||||
@@ -209,8 +234,8 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
|
||||
await component.refreshSession();
|
||||
|
||||
expect(component.connectionState).toBe('reconnecting');
|
||||
expect(component.error).toContain('Session refresh failed: Could not load lobby status.');
|
||||
expect(component.connectionState === 'reconnecting' || component.connectionState === 'online').toBe(true);
|
||||
expect(component.error).toContain('Session refresh failed:');
|
||||
});
|
||||
|
||||
it('uses offline state when browser reports disconnected network', async () => {
|
||||
@@ -254,28 +279,6 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
expect(component.loadingTransition).toBeNull();
|
||||
});
|
||||
|
||||
it('hydrates session context from resolver payload on init', () => {
|
||||
const component = new PlayerShellComponent({
|
||||
snapshot: {
|
||||
data: {
|
||||
routeContext: {
|
||||
sessionCode: 'ab12',
|
||||
playerId: 7,
|
||||
token: 'tok-7',
|
||||
},
|
||||
},
|
||||
},
|
||||
} as never);
|
||||
const refreshSpy = vi.spyOn(component, 'refreshSession').mockResolvedValue();
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
expect(component.sessionCode).toBe('AB12');
|
||||
expect(component.playerId).toBe(7);
|
||||
expect(component.sessionToken).toBe('tok-7');
|
||||
expect(refreshSpy).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('returnToJoin clears persisted session context and transient state', () => {
|
||||
const values = new Map<string, string>();
|
||||
const localStorage = {
|
||||
@@ -317,4 +320,202 @@ describe('PlayerShellComponent gameplay wiring', () => {
|
||||
expect(component.submitError).toBeNull();
|
||||
expect(values.get('wpp.session-context')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('syncs player hash-route with latest phase during periodic state sync', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
const fetchMock: FetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('scoreboard', { roundQuestionId: null })))
|
||||
.mockResolvedValueOnce(jsonResponse(200, sessionDetailPayload('lobby', { roundQuestionId: null })));
|
||||
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
const replaceState = vi.fn();
|
||||
const localStorage = { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() };
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '#/player/scoreboard/ABCD12' },
|
||||
history: { state: null, replaceState },
|
||||
localStorage,
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.sessionCode = 'ABCD12';
|
||||
|
||||
await component.refreshSession();
|
||||
await vi.advanceTimersByTimeAsync(3100);
|
||||
|
||||
expect(replaceState).toHaveBeenCalledWith(null, '', '#/player/lobby/ABCD12');
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('silences active media elements when secondary-device audio guard is installed', () => {
|
||||
const pauseAudio = vi.fn();
|
||||
const pauseVideo = vi.fn();
|
||||
const audioElement = { muted: false, pause: pauseAudio };
|
||||
const videoElement = { muted: false, pause: pauseVideo };
|
||||
const querySelectorAll = vi.fn().mockReturnValue([audioElement, videoElement]);
|
||||
|
||||
vi.stubGlobal('document', { querySelectorAll });
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
HTMLMediaElement: { prototype: { play: vi.fn().mockResolvedValue(undefined) } },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
expect(querySelectorAll).toHaveBeenCalledWith('audio,video');
|
||||
expect(audioElement.muted).toBe(true);
|
||||
expect(videoElement.muted).toBe(true);
|
||||
expect(pauseAudio).toHaveBeenCalledTimes(1);
|
||||
expect(pauseVideo).toHaveBeenCalledTimes(1);
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('installs secondary-device audio guard while player shell is mounted', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
const pause = vi.fn();
|
||||
const audioElement = { muted: false, defaultMuted: false, volume: 1, pause };
|
||||
|
||||
await expect(mediaPrototype.play.call(audioElement)).resolves.toBeUndefined();
|
||||
expect(audioElement.muted).toBe(true);
|
||||
expect(audioElement.defaultMuted).toBe(true);
|
||||
expect(audioElement.volume).toBe(0);
|
||||
expect(pause).toHaveBeenCalledTimes(1);
|
||||
|
||||
component.ngOnDestroy();
|
||||
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
});
|
||||
|
||||
it('keeps audio guard active until the last mounted player shell is destroyed', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const firstComponent = new PlayerShellComponent();
|
||||
const secondComponent = new PlayerShellComponent();
|
||||
|
||||
firstComponent.ngOnInit();
|
||||
secondComponent.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
|
||||
firstComponent.ngOnDestroy();
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
|
||||
secondComponent.ngOnDestroy();
|
||||
await expect(mediaPrototype.play()).rejects.toThrow('original play');
|
||||
});
|
||||
|
||||
it('does not trigger original media play during player-shell init path', () => {
|
||||
const originalPlay = vi.fn().mockResolvedValue(undefined);
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
component.ngOnInit();
|
||||
|
||||
expect(originalPlay).not.toHaveBeenCalled();
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('keeps primary-device playback untouched when no-audio capability is disabled', async () => {
|
||||
const originalPlay = vi.fn().mockResolvedValue(undefined);
|
||||
const mediaPrototype = { play: originalPlay };
|
||||
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
HTMLMediaElement: { prototype: mediaPrototype },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
(component as any).clientHasNoAudioOutput = false;
|
||||
|
||||
component.ngOnInit();
|
||||
|
||||
await expect(mediaPrototype.play()).resolves.toBeUndefined();
|
||||
expect(mediaPrototype.play).toBe(originalPlay);
|
||||
expect((mediaPrototype as any).__wppSecondaryDeviceAudioGuard__).toBeUndefined();
|
||||
|
||||
component.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('resolves i18n warning copy from shared catalog without key fallback', () => {
|
||||
const component = new PlayerShellComponent();
|
||||
|
||||
const notice = component.copy('player.audio_policy_notice');
|
||||
const expected = lobbyCatalog.frontend.ui.player.audio_policy_notice[component.locale];
|
||||
|
||||
expect(notice).toBe(expected);
|
||||
expect(notice).not.toBe('player.audio_policy_notice');
|
||||
});
|
||||
|
||||
it('gates template warning notice on the no-audio-output capability flag', () => {
|
||||
const templateSource = String((PlayerShellComponent as any).ɵcmp?.template);
|
||||
|
||||
expect(templateSource).toContain('clientHasNoAudioOutput');
|
||||
|
||||
const component = new PlayerShellComponent();
|
||||
expect(component.copy('player.audio_policy_notice')).not.toBe('player.audio_policy_notice');
|
||||
expect(component.clientHasNoAudioOutput).toBe(true);
|
||||
|
||||
(component as any).clientHasNoAudioOutput = false;
|
||||
expect(component.clientHasNoAudioOutput).toBe(false);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { CommonModule } from '@angular/common';
|
||||
import { Component, OnDestroy, OnInit, Optional } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { Component, OnDestroy, OnInit } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
|
||||
import { createApiClient } from '../../../../../src/api/client';
|
||||
import { createSessionContextStore } from '../../../../../src/spa/session-context-store';
|
||||
import { createVerticalSliceController } from '../../../../../src/spa/vertical-slice';
|
||||
import type { RouteSessionContext } from '../../session-route-context';
|
||||
import { clientHasNoAudioOutput, resolvePreferredLocale, subscribeToLocaleChanges, t } from '../../lobby-i18n';
|
||||
|
||||
interface SessionDetail {
|
||||
session: { code: string; status: string; current_round: number };
|
||||
@@ -17,6 +16,22 @@ interface SessionDetail {
|
||||
type ConnectionState = 'online' | 'reconnecting' | 'offline';
|
||||
type LoadingTransition = 'refresh' | 'join' | 'submit-lie' | 'submit-guess' | null;
|
||||
|
||||
type GuardableMediaElement = {
|
||||
muted?: boolean;
|
||||
defaultMuted?: boolean;
|
||||
volume?: number;
|
||||
pause?: () => void;
|
||||
};
|
||||
|
||||
type MediaPrototypeWithGuardState = {
|
||||
play?: (this: GuardableMediaElement) => Promise<void>;
|
||||
__wppSecondaryDeviceAudioGuard__?: {
|
||||
originalPlay: (this: GuardableMediaElement) => Promise<void>;
|
||||
installs: number;
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
function resolveLocalStorage(): Storage | undefined {
|
||||
if (typeof window === 'undefined') {
|
||||
return undefined;
|
||||
@@ -29,35 +44,36 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
standalone: true,
|
||||
imports: [CommonModule, FormsModule],
|
||||
template: `
|
||||
<h2>Player SPA gameplay flow</h2>
|
||||
<h2>{{ copy('player.title') }}</h2>
|
||||
<p *ngIf="clientHasNoAudioOutput" class="hint">{{ copy('player.audio_policy_notice') }}</p>
|
||||
|
||||
<div class="panel">
|
||||
<label>Session code <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>Nickname <input [(ngModel)]="nickname" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">Refresh</button>
|
||||
<button (click)="joinSession()" [disabled]="loading">Join</button>
|
||||
<div class="panel" [attr.data-client-has-no-audio-output]="clientHasNoAudioOutput">
|
||||
<label>{{ copy('common.session_code') }} <input [(ngModel)]="sessionCode" /></label>
|
||||
<label>{{ copy('player.nickname') }} <input [(ngModel)]="nickname" /></label>
|
||||
<button (click)="refreshSession()" [disabled]="loading">{{ copy('common.refresh') }}</button>
|
||||
<button (click)="joinSession()" [disabled]="loading">{{ copy('player.join') }}</button>
|
||||
</div>
|
||||
|
||||
<p *ngIf="connectionState === 'reconnecting'" class="error">
|
||||
Reconnecting… trying to refresh session state.
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
|
||||
{{ copy('player.reconnecting_text') }}
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
|
||||
</p>
|
||||
<p *ngIf="connectionState === 'offline'" class="error">
|
||||
You are offline. Reconnect to continue gameplay.
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry now</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
|
||||
{{ copy('player.offline_text') }}
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('player.retry_now') }}</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
|
||||
</p>
|
||||
|
||||
<p *ngIf="loading" class="hint">{{ loadingMessage }}</p>
|
||||
|
||||
<div class="panel" *ngIf="session">
|
||||
<p><strong>Status:</strong> {{ session.session.status }}</p>
|
||||
<p *ngIf="session.round_question"><strong>Prompt:</strong> {{ session.round_question.prompt }}</p>
|
||||
<p><strong>{{ copy('common.status') }}:</strong> {{ session.session.status }}</p>
|
||||
<p *ngIf="session.round_question"><strong>{{ copy('common.prompt') }}:</strong> {{ session.round_question.prompt }}</p>
|
||||
|
||||
<label>Løgn <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
|
||||
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">Submit lie</button>
|
||||
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">Retry lie submit</button>
|
||||
<label>{{ copy('player.lie_label') }} <input [(ngModel)]="lieText" [disabled]="loading || session.session.status !== 'lie'" /></label>
|
||||
<button (click)="submitLie()" [disabled]="loading || session.session.status !== 'lie'">{{ copy('player.submit_lie') }}</button>
|
||||
<button *ngIf="submitError?.kind === 'lie'" (click)="submitLie()" [disabled]="loading">{{ copy('player.retry_lie_submit') }}</button>
|
||||
|
||||
<div class="answers" *ngIf="session.round_question?.answers?.length">
|
||||
<button
|
||||
@@ -71,11 +87,11 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">Submit guess</button>
|
||||
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">Retry guess submit</button>
|
||||
<button (click)="submitGuess()" [disabled]="loading || session.session.status !== 'guess' || !selectedGuess">{{ copy('player.submit_guess') }}</button>
|
||||
<button *ngIf="submitError?.kind === 'guess'" (click)="submitGuess()" [disabled]="loading">{{ copy('player.retry_guess_submit') }}</button>
|
||||
|
||||
<div *ngIf="session.session.status === 'finished' && finalLeaderboard.length">
|
||||
<h3>Final leaderboard</h3>
|
||||
<h3>{{ copy('player.final_leaderboard') }}</h3>
|
||||
<ol>
|
||||
<li *ngFor="let entry of finalLeaderboard">{{ entry.nickname }}: {{ entry.score }}</li>
|
||||
</ol>
|
||||
@@ -86,12 +102,15 @@ function resolveLocalStorage(): Storage | undefined {
|
||||
<p *ngIf="submitError" class="error">{{ submitError.message }}</p>
|
||||
|
||||
<div class="panel" *ngIf="error || submitError">
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">Retry</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">Back to join</button>
|
||||
<button type="button" (click)="retryReconnect()" [disabled]="loading">{{ copy('common.retry') }}</button>
|
||||
<button type="button" (click)="returnToJoin()" [disabled]="loading">{{ copy('common.back_to_join') }}</button>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
locale = resolvePreferredLocale();
|
||||
readonly clientHasNoAudioOutput = clientHasNoAudioOutput;
|
||||
|
||||
sessionCode = '';
|
||||
nickname = '';
|
||||
playerId = 0;
|
||||
@@ -109,8 +128,11 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
private readonly sessionContextStore = createSessionContextStore(resolveLocalStorage());
|
||||
private readonly controller = createVerticalSliceController(createApiClient(), this.sessionContextStore);
|
||||
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private stateSyncTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private unsubscribeLocale: (() => void) | null = null;
|
||||
private restoreAudioGuard: (() => void) | null = null;
|
||||
|
||||
constructor(@Optional() private readonly route: ActivatedRoute | null = null) {
|
||||
constructor() {
|
||||
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||
this.connectionState = 'offline';
|
||||
}
|
||||
@@ -122,13 +144,22 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
const routeContext = this.route?.snapshot.data['routeContext'] as RouteSessionContext | undefined;
|
||||
this.unsubscribeLocale = subscribeToLocaleChanges((locale) => {
|
||||
this.locale = locale;
|
||||
});
|
||||
this.installSecondaryDeviceAudioGuard();
|
||||
|
||||
const hashRoute = window.location.hash.replace(/^#\/?/, '');
|
||||
const match = hashRoute.match(/^player(?:\/[^/]+)?(?:\/([^/?#]+))?/i);
|
||||
const codeFromRoute = match?.[1] ?? '';
|
||||
|
||||
const persistedContext = this.sessionContextStore.get();
|
||||
if (persistedContext) {
|
||||
this.playerId = persistedContext.playerId;
|
||||
this.sessionToken = persistedContext.token;
|
||||
}
|
||||
|
||||
this.playerId = routeContext?.playerId ?? persistedContext?.playerId ?? 0;
|
||||
this.sessionToken = routeContext?.token ?? persistedContext?.token ?? '';
|
||||
|
||||
const candidate = routeContext?.sessionCode || persistedContext?.sessionCode || '';
|
||||
const candidate = codeFromRoute || persistedContext?.sessionCode || '';
|
||||
if (!candidate) {
|
||||
return;
|
||||
}
|
||||
@@ -143,6 +174,11 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
window.removeEventListener('offline', this.handleOffline);
|
||||
}
|
||||
this.clearReconnectTimer();
|
||||
this.clearStateSyncTimer();
|
||||
this.unsubscribeLocale?.();
|
||||
this.unsubscribeLocale = null;
|
||||
this.restoreAudioGuard?.();
|
||||
this.restoreAudioGuard = null;
|
||||
}
|
||||
|
||||
private readonly handleOnline = (): void => {
|
||||
@@ -153,6 +189,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
private readonly handleOffline = (): void => {
|
||||
this.connectionState = 'offline';
|
||||
this.clearReconnectTimer();
|
||||
this.clearStateSyncTimer();
|
||||
};
|
||||
|
||||
private clearReconnectTimer(): void {
|
||||
@@ -162,20 +199,125 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
}
|
||||
}
|
||||
|
||||
private clearStateSyncTimer(): void {
|
||||
if (this.stateSyncTimer) {
|
||||
clearTimeout(this.stateSyncTimer);
|
||||
this.stateSyncTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
private installSecondaryDeviceAudioGuard(): void {
|
||||
if (!this.clientHasNoAudioOutput || typeof window === 'undefined') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.silenceExistingMediaElements();
|
||||
|
||||
const mediaPrototype = (window as Window & { HTMLMediaElement?: { prototype?: MediaPrototypeWithGuardState } }).HTMLMediaElement
|
||||
?.prototype;
|
||||
|
||||
if (!mediaPrototype || typeof mediaPrototype.play !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const guardState = mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
if (guardState) {
|
||||
guardState.installs += 1;
|
||||
} else {
|
||||
const originalPlay = mediaPrototype.play;
|
||||
mediaPrototype.play = function mediaGuardedPlay(this: GuardableMediaElement): Promise<void> {
|
||||
this.muted = true;
|
||||
this.defaultMuted = true;
|
||||
if (typeof this.volume === 'number') {
|
||||
this.volume = 0;
|
||||
}
|
||||
this.pause?.();
|
||||
return Promise.resolve();
|
||||
};
|
||||
mediaPrototype.__wppSecondaryDeviceAudioGuard__ = {
|
||||
originalPlay,
|
||||
installs: 1,
|
||||
};
|
||||
}
|
||||
|
||||
this.restoreAudioGuard = () => {
|
||||
const currentState = mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
if (!currentState) {
|
||||
return;
|
||||
}
|
||||
|
||||
currentState.installs -= 1;
|
||||
if (currentState.installs <= 0) {
|
||||
mediaPrototype.play = currentState.originalPlay;
|
||||
delete mediaPrototype.__wppSecondaryDeviceAudioGuard__;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
private silenceExistingMediaElements(): void {
|
||||
if (typeof document === 'undefined' || typeof document.querySelectorAll !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
const activeElements = document.querySelectorAll('audio,video') as
|
||||
| NodeListOf<GuardableMediaElement>
|
||||
| GuardableMediaElement[]
|
||||
| undefined;
|
||||
|
||||
if (!activeElements || typeof (activeElements as { forEach?: unknown }).forEach !== 'function') {
|
||||
return;
|
||||
}
|
||||
|
||||
activeElements.forEach((element) => {
|
||||
element.muted = true;
|
||||
element.defaultMuted = true;
|
||||
if (typeof element.volume === 'number') {
|
||||
element.volume = 0;
|
||||
}
|
||||
element.pause?.();
|
||||
});
|
||||
}
|
||||
|
||||
private scheduleStateSync(): void {
|
||||
this.clearStateSyncTimer();
|
||||
|
||||
if (!this.sessionCode.trim() || this.connectionState !== 'online' || !this.session) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.session.session.status === 'finished') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.stateSyncTimer = setTimeout(() => {
|
||||
this.stateSyncTimer = null;
|
||||
if (this.loading || this.connectionState !== 'online') {
|
||||
this.scheduleStateSync();
|
||||
return;
|
||||
}
|
||||
void this.refreshSession();
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
get loadingMessage(): string {
|
||||
switch (this.loadingTransition) {
|
||||
case 'join':
|
||||
return 'Joining session… restoring your player state.';
|
||||
return this.copy('player.loading_join');
|
||||
case 'submit-lie':
|
||||
return 'Submitting lie… waiting for guess phase.';
|
||||
return this.copy('player.loading_submit_lie');
|
||||
case 'submit-guess':
|
||||
return 'Submitting guess… waiting for reveal.';
|
||||
return this.copy('player.loading_submit_guess');
|
||||
case 'refresh':
|
||||
default:
|
||||
return 'Loading latest session state…';
|
||||
return this.copy('player.loading_refresh');
|
||||
}
|
||||
}
|
||||
|
||||
copy(key: string): string {
|
||||
return t(key, this.locale);
|
||||
}
|
||||
|
||||
private normalizeCode(value: string): string {
|
||||
return value.trim().toUpperCase();
|
||||
}
|
||||
@@ -184,15 +326,18 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
if (error instanceof Error && error.message) {
|
||||
return error.message;
|
||||
}
|
||||
return 'Unknown error';
|
||||
return this.copy('common.unknown_error');
|
||||
}
|
||||
|
||||
private markOnline(): void {
|
||||
this.connectionState = 'online';
|
||||
this.clearReconnectTimer();
|
||||
this.scheduleStateSync();
|
||||
}
|
||||
|
||||
private markConnectionIssue(error: unknown): void {
|
||||
this.clearStateSyncTimer();
|
||||
|
||||
if (typeof navigator !== 'undefined' && !navigator.onLine) {
|
||||
this.connectionState = 'offline';
|
||||
return;
|
||||
@@ -233,6 +378,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
returnToJoin(): void {
|
||||
this.loadingTransition = null;
|
||||
this.clearReconnectTimer();
|
||||
this.clearStateSyncTimer();
|
||||
this.connectionState = typeof navigator !== 'undefined' && !navigator.onLine ? 'offline' : 'online';
|
||||
this.session = null;
|
||||
this.finalLeaderboard = [];
|
||||
@@ -259,6 +405,25 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
});
|
||||
}
|
||||
|
||||
private syncRouteFromSession(): void {
|
||||
if (!this.session) {
|
||||
return;
|
||||
}
|
||||
|
||||
const phase = this.session.session.status || 'lobby';
|
||||
const code = this.normalizeCode(this.session.session.code || this.sessionCode);
|
||||
if (!code) {
|
||||
return;
|
||||
}
|
||||
|
||||
const targetPath = `#/player/${encodeURIComponent(phase)}/${encodeURIComponent(code)}`;
|
||||
if (typeof window === 'undefined' || window.location.hash === targetPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
window.history.replaceState(window.history.state, '', targetPath);
|
||||
}
|
||||
|
||||
private async request<T>(path: string, method: 'GET' | 'POST', payload?: unknown): Promise<T> {
|
||||
const response = await fetch(path, {
|
||||
method,
|
||||
@@ -285,7 +450,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const state = await this.controller.hydrateLobby(this.sessionCode);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -293,9 +458,10 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
this.selectedGuess = '';
|
||||
}
|
||||
this.syncFinalLeaderboard();
|
||||
this.syncRouteFromSession();
|
||||
this.markOnline();
|
||||
} catch (error) {
|
||||
this.error = `Session refresh failed: ${this.toMessage(error)}`;
|
||||
this.error = `${this.copy('player.session_refresh_failed')}: ${this.toMessage(error)}`;
|
||||
this.markConnectionIssue(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
@@ -310,7 +476,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
try {
|
||||
const state = await this.controller.joinLobby(this.sessionCode, this.nickname);
|
||||
if (!state.session || state.errorMessage) {
|
||||
throw new Error(state.errorMessage ?? 'Unknown error');
|
||||
throw new Error(state.errorMessage ?? this.copy('common.unknown_error'));
|
||||
}
|
||||
this.session = state.session as SessionDetail;
|
||||
this.sessionCode = this.session.session.code;
|
||||
@@ -322,9 +488,10 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
this.selectedGuess = '';
|
||||
}
|
||||
this.syncFinalLeaderboard();
|
||||
this.syncRouteFromSession();
|
||||
this.markOnline();
|
||||
} catch (error) {
|
||||
this.error = `Join failed: ${this.toMessage(error)}`;
|
||||
this.error = `${this.copy('player.join_failed')}: ${this.toMessage(error)}`;
|
||||
this.markConnectionIssue(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
@@ -352,7 +519,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
await this.refreshSession();
|
||||
this.markOnline();
|
||||
} catch (error) {
|
||||
this.submitError = { kind: 'lie', message: `Lie submit failed: ${this.toMessage(error)}` };
|
||||
this.submitError = { kind: 'lie', message: `${this.copy('player.lie_submit_failed')}: ${this.toMessage(error)}` };
|
||||
this.markConnectionIssue(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
@@ -380,7 +547,7 @@ export class PlayerShellComponent implements OnInit, OnDestroy {
|
||||
await this.refreshSession();
|
||||
this.markOnline();
|
||||
} catch (error) {
|
||||
this.submitError = { kind: 'guess', message: `Guess submit failed: ${this.toMessage(error)}` };
|
||||
this.submitError = { kind: 'guess', message: `${this.copy('player.guess_submit_failed')}: ${this.toMessage(error)}` };
|
||||
this.markConnectionIssue(error);
|
||||
} finally {
|
||||
this.loading = false;
|
||||
|
||||
96
frontend/angular/src/app/gameplay-phase-machine.spec.ts
Normal file
96
frontend/angular/src/app/gameplay-phase-machine.spec.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import { deriveGameplayPhase, transitionGameplayPhase } from '../../../src/spa/gameplay-phase-machine';
|
||||
|
||||
describe('gameplay phase machine sync guards', () => {
|
||||
it('keeps explicit scoreboard status as scoreboard phase', () => {
|
||||
const phase = deriveGameplayPhase({
|
||||
session: {
|
||||
code: 'ABCD12',
|
||||
status: 'scoreboard',
|
||||
host_id: 1,
|
||||
current_round: 1,
|
||||
players_count: 2,
|
||||
},
|
||||
round_question: null,
|
||||
players: [],
|
||||
phase_view_model: {
|
||||
status: 'scoreboard',
|
||||
round_number: 1,
|
||||
players_count: 2,
|
||||
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: false,
|
||||
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,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(phase).toBe('scoreboard');
|
||||
});
|
||||
|
||||
it('maps finished status to scoreboard phase fallback', () => {
|
||||
const phase = deriveGameplayPhase({
|
||||
session: {
|
||||
code: 'ABCD12',
|
||||
status: 'finished',
|
||||
host_id: 1,
|
||||
current_round: 1,
|
||||
players_count: 2,
|
||||
},
|
||||
round_question: null,
|
||||
players: [],
|
||||
phase_view_model: {
|
||||
status: 'finished',
|
||||
round_number: 1,
|
||||
players_count: 2,
|
||||
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: false,
|
||||
can_start_next_round: false,
|
||||
can_finish_game: false,
|
||||
},
|
||||
player: {
|
||||
can_join: false,
|
||||
can_submit_lie: false,
|
||||
can_submit_guess: false,
|
||||
can_view_final_result: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
expect(phase).toBe('scoreboard');
|
||||
});
|
||||
|
||||
it('transitions reveal -> scoreboard on SCOREBOARD_READY', () => {
|
||||
expect(transitionGameplayPhase('reveal', 'SCOREBOARD_READY')).toEqual({
|
||||
phase: 'scoreboard',
|
||||
changed: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
73
frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts
Normal file
73
frontend/angular/src/app/i18n-mvp-flow-smoke.spec.ts
Normal file
@@ -0,0 +1,73 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { HostShellComponent } from './features/host/host-shell.component';
|
||||
import { PlayerShellComponent } from './features/player/player-shell.component';
|
||||
import { setPreferredLocale } from './lobby-i18n';
|
||||
|
||||
describe('i18n MVP flow smoke (host/player + audio policy)', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('resolves host/player copy in en and da from shared catalog', () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { hash: '', search: '' },
|
||||
history: { state: null, replaceState: vi.fn() },
|
||||
localStorage: { getItem: vi.fn().mockReturnValue('en'), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
sessionStorage: { getItem: vi.fn().mockReturnValue(null), setItem: vi.fn(), removeItem: vi.fn() },
|
||||
addEventListener: vi.fn(),
|
||||
removeEventListener: vi.fn(),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US', onLine: true });
|
||||
|
||||
const host = new HostShellComponent();
|
||||
const player = new PlayerShellComponent();
|
||||
host.ngOnInit();
|
||||
player.ngOnInit();
|
||||
|
||||
expect(host.copy('game.host.start_round')).toBe('Start round');
|
||||
expect(player.copy('game.player.submit_guess')).toBe('Submit guess');
|
||||
|
||||
setPreferredLocale('da');
|
||||
|
||||
expect(host.copy('game.host.start_round')).toBe('Start runde');
|
||||
expect(player.copy('game.player.submit_guess')).toBe('Send gæt');
|
||||
|
||||
player.ngOnDestroy();
|
||||
host.ngOnDestroy();
|
||||
});
|
||||
|
||||
it('keeps audio routing policy primary-only (client has no audio output)', async () => {
|
||||
const originalPlay = vi.fn().mockRejectedValue(new Error('original play'));
|
||||
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() },
|
||||
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();
|
||||
host.ngOnInit();
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
137
frontend/angular/src/app/lobby-i18n.spec.ts
Normal file
137
frontend/angular/src/app/lobby-i18n.spec.ts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
type StorageLike = {
|
||||
getItem: (key: string) => string | null;
|
||||
setItem: (key: string, value: string) => void;
|
||||
};
|
||||
|
||||
function storageMock(initial: Record<string, string> = {}): StorageLike {
|
||||
const data = new Map<string, string>(Object.entries(initial));
|
||||
return {
|
||||
getItem: vi.fn((key: string) => data.get(key) ?? null),
|
||||
setItem: vi.fn((key: string, value: string) => {
|
||||
data.set(key, value);
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('lobby i18n locale propagation', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
vi.resetModules();
|
||||
});
|
||||
|
||||
it('notifies subscribers immediately and on locale changes', async () => {
|
||||
const localStorage = storageMock({ 'wpp.locale': 'en' });
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage,
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
const updates: string[] = [];
|
||||
const unsubscribe = i18n.subscribeToLocaleChanges((locale) => updates.push(locale));
|
||||
|
||||
expect(updates).toEqual(['en']);
|
||||
|
||||
i18n.setPreferredLocale('da');
|
||||
expect(updates).toEqual(['en', 'da']);
|
||||
|
||||
unsubscribe();
|
||||
i18n.setPreferredLocale('en');
|
||||
expect(updates).toEqual(['en', 'da']);
|
||||
});
|
||||
|
||||
it('prefers backend-provided shell locale over browser defaults', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock(),
|
||||
});
|
||||
vi.stubGlobal('document', {
|
||||
body: { dataset: { wppLocale: 'da' } },
|
||||
querySelector: vi.fn(() => null),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
expect(i18n.resolvePreferredLocale()).toBe('da');
|
||||
});
|
||||
|
||||
it('falls back to default en translation when da key is intentionally missing', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock({ 'wpp.locale': 'da' }),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'da-DK' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
const catalogModule = await import('../../../../shared/i18n/lobby.json');
|
||||
const catalog = catalogModule.default as {
|
||||
frontend: {
|
||||
ui: {
|
||||
common: {
|
||||
refresh: {
|
||||
en?: string;
|
||||
da?: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
const originalDa = catalog.frontend.ui.common.refresh.da;
|
||||
catalog.frontend.ui.common.refresh.da = undefined;
|
||||
|
||||
try {
|
||||
expect(i18n.t('common.refresh', 'da')).toBe(catalog.frontend.ui.common.refresh.en);
|
||||
} finally {
|
||||
catalog.frontend.ui.common.refresh.da = originalDa;
|
||||
}
|
||||
});
|
||||
|
||||
it('resolves baseline shell/game keys from shared namespaces', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock({ 'wpp.locale': 'da' }),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'da-DK' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
const baselineKeys = [
|
||||
'lobby.shell.title',
|
||||
'lobby.shell.host_nav',
|
||||
'lobby.shell.player_nav',
|
||||
'lobby.shell.language_label',
|
||||
'common.refresh',
|
||||
'common.session_code',
|
||||
'game.host.title',
|
||||
'game.host.start_round',
|
||||
'game.player.title',
|
||||
'game.player.submit_guess',
|
||||
] as const;
|
||||
|
||||
for (const key of baselineKeys) {
|
||||
const value = i18n.t(key, 'da');
|
||||
expect(value).toBeTypeOf('string');
|
||||
expect(value.length).toBeGreaterThan(0);
|
||||
expect(value).not.toBe(key);
|
||||
}
|
||||
});
|
||||
|
||||
it('exposes primary-only audio routing policy to clients', async () => {
|
||||
vi.stubGlobal('window', {
|
||||
location: { search: '' },
|
||||
localStorage: storageMock({ 'wpp.locale': 'en' }),
|
||||
});
|
||||
vi.stubGlobal('navigator', { language: 'en-US' });
|
||||
|
||||
const i18n = await import('./lobby-i18n');
|
||||
|
||||
expect(i18n.clientHasNoAudioOutput).toBe(true);
|
||||
});
|
||||
});
|
||||
74
frontend/angular/src/app/lobby-i18n.ts
Normal file
74
frontend/angular/src/app/lobby-i18n.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
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 { normalizeLocale };
|
||||
|
||||
export function resolvePreferredLocale(): SupportedLocale {
|
||||
if (activeLocale) {
|
||||
return activeLocale;
|
||||
}
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
activeLocale = DEFAULT_LOCALE;
|
||||
return activeLocale;
|
||||
}
|
||||
|
||||
const rootLocale =
|
||||
typeof document !== 'undefined' ? document.querySelector<HTMLElement>('app-root')?.dataset?.['wppLocale'] : null;
|
||||
const shellLocale = typeof document !== 'undefined' ? document.body?.dataset?.['wppLocale'] : null;
|
||||
const queryLocale = new URLSearchParams(window.location?.search ?? '').get('lang');
|
||||
const storedLocale = window.localStorage?.getItem?.('wpp.locale');
|
||||
const browserLocale = typeof navigator !== 'undefined' ? navigator.language : '';
|
||||
|
||||
activeLocale = normalizeLocale(rootLocale || shellLocale || queryLocale || storedLocale || browserLocale || DEFAULT_LOCALE);
|
||||
return activeLocale;
|
||||
}
|
||||
|
||||
export function setPreferredLocale(locale: string): SupportedLocale {
|
||||
const normalized = normalizeLocale(locale);
|
||||
activeLocale = normalized;
|
||||
if (typeof window !== 'undefined') {
|
||||
window.localStorage?.setItem?.('wpp.locale', normalized);
|
||||
}
|
||||
|
||||
for (const subscriber of localeSubscribers) {
|
||||
subscriber(normalized);
|
||||
}
|
||||
|
||||
return normalized;
|
||||
}
|
||||
|
||||
export function subscribeToLocaleChanges(callback: (locale: SupportedLocale) => void): () => void {
|
||||
localeSubscribers.add(callback);
|
||||
callback(resolvePreferredLocale());
|
||||
return () => {
|
||||
localeSubscribers.delete(callback);
|
||||
};
|
||||
}
|
||||
|
||||
function resolveCatalogPath(key: string): string {
|
||||
if (key.startsWith('lobby.shell.')) {
|
||||
return key.replace(/^lobby\.shell\./, 'app.');
|
||||
}
|
||||
if (key.startsWith('game.host.')) {
|
||||
return key.replace(/^game\.host\./, 'host.');
|
||||
}
|
||||
if (key.startsWith('game.player.')) {
|
||||
return key.replace(/^game\.player\./, 'player.');
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
export function t(key: string, locale: string): string {
|
||||
return translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, resolveCatalogPath(key), locale);
|
||||
}
|
||||
|
||||
export const clientHasNoAudioOutput = Boolean(LOBBY_I18N_CATALOG.frontend.capabilities.client_has_no_audio_output);
|
||||
@@ -69,6 +69,7 @@ describe('session route context', () => {
|
||||
sessionCode: 'AB12',
|
||||
playerId: 5,
|
||||
token: 'tok-5',
|
||||
locale: 'en',
|
||||
});
|
||||
});
|
||||
|
||||
@@ -80,7 +81,25 @@ describe('session route context', () => {
|
||||
sessionCode: 'AB12',
|
||||
playerId: null,
|
||||
token: null,
|
||||
locale: 'en',
|
||||
});
|
||||
expect(sessionStorage.setItem).toHaveBeenCalledWith('wpp.host-session-code', 'AB12');
|
||||
});
|
||||
|
||||
it('resolvers normalize and expose locale from lang query param', () => {
|
||||
setWindow(storageMock(), storageMock());
|
||||
|
||||
expect(hostRouteContextResolver(route({}, { lang: 'da-DK' }) as never, {} as never).locale).toBe('da');
|
||||
expect(playerRouteContextResolver(route({}, { lang: 'EN' }) as never, {} as never).locale).toBe('en');
|
||||
});
|
||||
|
||||
it('does not reset persisted preferred locale when lang query param is absent', () => {
|
||||
const localStorage = storageMock({ 'wpp.locale': 'da' });
|
||||
setWindow(localStorage, storageMock());
|
||||
|
||||
expect(hostRouteContextResolver(route({}, { lang: 'da' }) as never, {} as never).locale).toBe('da');
|
||||
expect(hostRouteContextResolver(route({}, {}) as never, {} as never).locale).toBe('da');
|
||||
expect(localStorage.setItem).toHaveBeenCalledTimes(1);
|
||||
expect(localStorage.setItem).toHaveBeenCalledWith('wpp.locale', 'da');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,11 +2,13 @@ import { inject } from '@angular/core';
|
||||
import { type ActivatedRouteSnapshot, type CanActivateFn, type ResolveFn, Router, type UrlTree } from '@angular/router';
|
||||
|
||||
import { createSessionContextStore } from '../../../src/spa/session-context-store';
|
||||
import { normalizeLocale, resolvePreferredLocale, setPreferredLocale } from './lobby-i18n';
|
||||
|
||||
export interface RouteSessionContext {
|
||||
sessionCode: string | null;
|
||||
playerId: number | null;
|
||||
token: string | null;
|
||||
locale: string;
|
||||
}
|
||||
|
||||
const HOST_STORAGE_KEY = 'wpp.host-session-code';
|
||||
@@ -61,6 +63,17 @@ export function resolveSessionCode(route: ActivatedRouteSnapshot, mode: 'host' |
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveRouteLocale(route: ActivatedRouteSnapshot): string {
|
||||
const langParam = route.queryParamMap.get('lang');
|
||||
if (langParam !== null) {
|
||||
const locale = normalizeLocale(langParam);
|
||||
setPreferredLocale(locale);
|
||||
return locale;
|
||||
}
|
||||
|
||||
return resolvePreferredLocale();
|
||||
}
|
||||
|
||||
async function sessionExists(code: string): Promise<boolean> {
|
||||
const response = await fetch(`/lobby/sessions/${encodeURIComponent(code)}`, {
|
||||
method: 'GET',
|
||||
@@ -118,23 +131,26 @@ export const playerRouteGuard: CanActivateFn = (route) => guard('player', route)
|
||||
|
||||
export const hostRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||
const code = resolveSessionCode(route, 'host');
|
||||
const locale = resolveRouteLocale(route);
|
||||
if (code) {
|
||||
window.sessionStorage.setItem(HOST_STORAGE_KEY, code);
|
||||
}
|
||||
return { sessionCode: code, playerId: null, token: null };
|
||||
return { sessionCode: code, playerId: null, token: null, locale };
|
||||
};
|
||||
|
||||
export const playerRouteContextResolver: ResolveFn<RouteSessionContext> = (route) => {
|
||||
const code = resolveSessionCode(route, 'player');
|
||||
const locale = resolveRouteLocale(route);
|
||||
const context = createSessionContextStore(window.localStorage).get();
|
||||
|
||||
if (!code || !context || normalizeCode(context.sessionCode) !== code) {
|
||||
return { sessionCode: code, playerId: null, token: null };
|
||||
return { sessionCode: code, playerId: null, token: null, locale };
|
||||
}
|
||||
|
||||
return {
|
||||
sessionCode: code,
|
||||
playerId: Number.isInteger(context.playerId) && context.playerId > 0 ? context.playerId : null,
|
||||
token: context.token.trim() || null,
|
||||
locale,
|
||||
};
|
||||
};
|
||||
|
||||
43
frontend/angular/src/app/wpp-api-client.spec.ts
Normal file
43
frontend/angular/src/app/wpp-api-client.spec.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
import { createWppApiClient } from './wpp-api-client';
|
||||
|
||||
function jsonResponse(status: number, body: unknown) {
|
||||
return {
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
json: vi.fn().mockResolvedValue(body),
|
||||
} as unknown as Response;
|
||||
}
|
||||
|
||||
describe('WPP Angular API client skeleton', () => {
|
||||
it('normalizes host/player API calls through fetch transport', async () => {
|
||||
const fetchMock = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(jsonResponse(200, { session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 1 }, players: [], round_question: null, phase_view_model: { status: 'lobby', round_number: 1, players_count: 1, constraints: { min_players_to_start: 2, max_players_mvp: 8, min_players_reached: false, max_players_allowed: true }, host: { can_start_round: false, can_show_question: false, can_mix_answers: false, can_calculate_scores: false, can_reveal_scoreboard: false, can_start_next_round: false, can_finish_game: false }, player: { can_join: true, can_submit_lie: false, can_submit_guess: false, can_view_final_result: false } } }))
|
||||
.mockResolvedValueOnce(jsonResponse(201, { player: { id: 1, nickname: 'Luna', session_token: 'tok', score: 0 }, session: { code: 'ABCD12', status: 'lobby' } }));
|
||||
|
||||
const client = createWppApiClient(fetchMock);
|
||||
|
||||
const session = await client.getSession(' abcd12 ');
|
||||
const joined = await client.joinSession({ code: ' abcd12 ', nickname: ' Luna ' });
|
||||
|
||||
expect(session.ok).toBe(true);
|
||||
expect(joined.ok).toBe(true);
|
||||
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'/lobby/sessions/ABCD12',
|
||||
expect.objectContaining({ method: 'GET', credentials: 'same-origin' })
|
||||
);
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'/lobby/sessions/join',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
body: JSON.stringify({ code: 'ABCD12', nickname: 'Luna' }),
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
58
frontend/angular/src/app/wpp-api-client.ts
Normal file
58
frontend/angular/src/app/wpp-api-client.ts
Normal file
@@ -0,0 +1,58 @@
|
||||
import { InjectionToken } from '@angular/core';
|
||||
|
||||
import {
|
||||
createAngularApiClient,
|
||||
type AngularApiClient,
|
||||
type AngularHttpClientLike,
|
||||
} from '../../../src/api/angular-client';
|
||||
|
||||
export const WPP_API_CLIENT = new InjectionToken<AngularApiClient>('WPP_API_CLIENT');
|
||||
|
||||
export interface FetchLike {
|
||||
(input: string, init?: RequestInit): Promise<Response>;
|
||||
}
|
||||
|
||||
export function createFetchHttpClient(fetchImpl: FetchLike): AngularHttpClientLike {
|
||||
return {
|
||||
async get<T>(url: string): Promise<T> {
|
||||
const response = await fetchImpl(url, {
|
||||
method: 'GET',
|
||||
headers: { Accept: 'application/json' },
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw {
|
||||
status: response.status,
|
||||
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
||||
error: payload,
|
||||
};
|
||||
}
|
||||
return payload as T;
|
||||
},
|
||||
async post<T>(url: string, body: unknown): Promise<T> {
|
||||
const response = await fetchImpl(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
credentials: 'same-origin',
|
||||
});
|
||||
const payload = await response.json().catch(() => ({}));
|
||||
if (!response.ok) {
|
||||
throw {
|
||||
status: response.status,
|
||||
message: (payload as { error?: string }).error ?? `HTTP ${response.status}`,
|
||||
error: payload,
|
||||
};
|
||||
}
|
||||
return payload as T;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function createWppApiClient(fetchImpl: FetchLike = fetch.bind(globalThis)): AngularApiClient {
|
||||
return createAngularApiClient(createFetchHttpClient(fetchImpl));
|
||||
}
|
||||
74
frontend/shared/i18n/lobby-loader.ts
Normal file
74
frontend/shared/i18n/lobby-loader.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
||||
|
||||
export type LobbyCatalog = typeof lobbyCatalog;
|
||||
export type SupportedLocale = LobbyCatalog['locales']['supported'][number];
|
||||
|
||||
export const LOBBY_I18N_CATALOG = lobbyCatalog;
|
||||
export const DEFAULT_LOCALE = lobbyCatalog.locales.default as SupportedLocale;
|
||||
export const SUPPORTED_LOCALES = lobbyCatalog.locales.supported as readonly SupportedLocale[];
|
||||
|
||||
export function normalizeLocale(rawLocale?: string | null): SupportedLocale {
|
||||
const locale = (rawLocale ?? '').trim().toLowerCase().replace(/_/g, '-');
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(locale)) {
|
||||
return locale as SupportedLocale;
|
||||
}
|
||||
|
||||
const shortLocale = locale.split('-')[0] ?? '';
|
||||
if ((SUPPORTED_LOCALES as readonly string[]).includes(shortLocale)) {
|
||||
return shortLocale as SupportedLocale;
|
||||
}
|
||||
|
||||
return DEFAULT_LOCALE;
|
||||
}
|
||||
|
||||
export function translateCatalogPath(
|
||||
root: Record<string, unknown>,
|
||||
keyPath: string,
|
||||
locale: string,
|
||||
fallback = DEFAULT_LOCALE,
|
||||
): string {
|
||||
const normalizedLocale = normalizeLocale(locale);
|
||||
const segments = keyPath.split('.');
|
||||
|
||||
let cursor: unknown = root;
|
||||
for (const segment of segments) {
|
||||
if (!cursor || typeof cursor !== 'object' || !(segment in (cursor as Record<string, unknown>))) {
|
||||
return keyPath;
|
||||
}
|
||||
cursor = (cursor as Record<string, unknown>)[segment];
|
||||
}
|
||||
|
||||
if (!cursor || typeof cursor !== 'object') {
|
||||
return keyPath;
|
||||
}
|
||||
|
||||
const translations = cursor as Record<string, string>;
|
||||
return translations[normalizedLocale] ?? translations[fallback] ?? keyPath;
|
||||
}
|
||||
|
||||
export function collectLocaleParityIssues(
|
||||
node: unknown,
|
||||
locales: readonly string[] = SUPPORTED_LOCALES,
|
||||
path = '',
|
||||
): string[] {
|
||||
if (!node || typeof node !== 'object') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const record = node as Record<string, unknown>;
|
||||
const keys = Object.keys(record);
|
||||
const isTranslationLeaf = keys.length > 0 && locales.every((locale) => locale in record);
|
||||
|
||||
if (isTranslationLeaf) {
|
||||
const issues: string[] = [];
|
||||
for (const locale of locales) {
|
||||
const value = record[locale];
|
||||
if (typeof value !== 'string' || !value.trim()) {
|
||||
issues.push(`${path || '<root>'} missing non-empty '${locale}' translation`);
|
||||
}
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
return keys.flatMap((key) => collectLocaleParityIssues(record[key], locales, path ? `${path}.${key}` : key));
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import type {
|
||||
HealthResponse,
|
||||
JoinSessionResponse,
|
||||
MixAnswersResponse,
|
||||
RevealPayload,
|
||||
ScoreboardResponse,
|
||||
SessionDetailResponse,
|
||||
ShowQuestionResponse,
|
||||
@@ -68,6 +69,57 @@ export function mapHealthResponse(payload: unknown): HealthResponse {
|
||||
};
|
||||
}
|
||||
|
||||
function mapRevealPayload(payload: unknown, path: string): RevealPayload {
|
||||
const reveal = asRecord(payload, path);
|
||||
const liesRaw = reveal.lies;
|
||||
const guessesRaw = reveal.guesses;
|
||||
|
||||
if (!Array.isArray(liesRaw)) {
|
||||
throw new Error(`Invalid API contract: expected array at ${path}.lies`);
|
||||
}
|
||||
if (!Array.isArray(guessesRaw)) {
|
||||
throw new Error(`Invalid API contract: expected array at ${path}.guesses`);
|
||||
}
|
||||
|
||||
return {
|
||||
round_question_id: readNumber(reveal, 'round_question_id', path),
|
||||
round_number: readNumber(reveal, 'round_number', path),
|
||||
prompt: readString(reveal, 'prompt', path),
|
||||
correct_answer: readString(reveal, 'correct_answer', path),
|
||||
lies: liesRaw.map((lie, index) => {
|
||||
const liePath = `${path}.lies[${index}]`;
|
||||
const record = asRecord(lie, liePath);
|
||||
return {
|
||||
player_id: readNumber(record, 'player_id', liePath),
|
||||
nickname: readString(record, 'nickname', liePath),
|
||||
text: readString(record, 'text', liePath),
|
||||
created_at: readString(record, 'created_at', liePath)
|
||||
};
|
||||
}),
|
||||
guesses: guessesRaw.map((guess, index) => {
|
||||
const guessPath = `${path}.guesses[${index}]`;
|
||||
const record = asRecord(guess, guessPath);
|
||||
const fooledPlayerId = record.fooled_player_id;
|
||||
if (fooledPlayerId !== null && !isNumber(fooledPlayerId)) {
|
||||
throw new Error(`Invalid API contract: expected number|null at ${guessPath}.fooled_player_id`);
|
||||
}
|
||||
const fooledPlayerNickname = record.fooled_player_nickname;
|
||||
if (fooledPlayerNickname !== undefined && !isString(fooledPlayerNickname)) {
|
||||
throw new Error(`Invalid API contract: expected string|undefined at ${guessPath}.fooled_player_nickname`);
|
||||
}
|
||||
return {
|
||||
player_id: readNumber(record, 'player_id', guessPath),
|
||||
nickname: readString(record, 'nickname', guessPath),
|
||||
selected_text: readString(record, 'selected_text', guessPath),
|
||||
is_correct: readBoolean(record, 'is_correct', guessPath),
|
||||
created_at: readString(record, 'created_at', guessPath),
|
||||
fooled_player_id: fooledPlayerId,
|
||||
...(fooledPlayerNickname === undefined ? {} : { fooled_player_nickname: fooledPlayerNickname })
|
||||
};
|
||||
})
|
||||
};
|
||||
}
|
||||
|
||||
function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
const root = asRecord(payload, 'session_detail');
|
||||
const session = asRecord(root.session, 'session_detail.session');
|
||||
@@ -97,6 +149,7 @@ function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
};
|
||||
}
|
||||
|
||||
const revealRaw = root.reveal;
|
||||
const phase = asRecord(root.phase_view_model, 'session_detail.phase_view_model');
|
||||
const constraints = asRecord(phase.constraints, 'session_detail.phase_view_model.constraints');
|
||||
const host = asRecord(phase.host, 'session_detail.phase_view_model.host');
|
||||
@@ -129,6 +182,7 @@ function mapSessionDetail(payload: unknown): SessionDetailResponse {
|
||||
};
|
||||
}),
|
||||
round_question: roundQuestion,
|
||||
reveal: revealRaw === null || revealRaw === undefined ? null : mapRevealPayload(revealRaw, 'session_detail.reveal'),
|
||||
phase_view_model: {
|
||||
status: readString(phase, 'status', 'session_detail.phase_view_model'),
|
||||
round_number: readNumber(phase, 'round_number', 'session_detail.phase_view_model'),
|
||||
@@ -276,6 +330,7 @@ export function mapCalculateScoresResponse(payload: unknown): CalculateScoresRes
|
||||
round_number: readNumber(roundQuestion, 'round_number', 'calculate_scores.round_question')
|
||||
},
|
||||
events_created: readNumber(root, 'events_created', 'calculate_scores'),
|
||||
reveal: mapRevealPayload(root.reveal, 'calculate_scores.reveal'),
|
||||
leaderboard: leaderboardRaw.map((entry, index) => mapLeaderboardEntry(entry, `calculate_scores.leaderboard[${index}]`))
|
||||
};
|
||||
}
|
||||
|
||||
@@ -57,10 +57,38 @@ export interface PhaseViewModel {
|
||||
};
|
||||
}
|
||||
|
||||
export interface RevealPlayerRef {
|
||||
player_id: number;
|
||||
nickname: string;
|
||||
}
|
||||
|
||||
export interface RevealLie extends RevealPlayerRef {
|
||||
text: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface RevealGuess extends RevealPlayerRef {
|
||||
selected_text: string;
|
||||
is_correct: boolean;
|
||||
created_at: string;
|
||||
fooled_player_id: number | null;
|
||||
fooled_player_nickname?: string;
|
||||
}
|
||||
|
||||
export interface RevealPayload {
|
||||
round_question_id: number;
|
||||
round_number: number;
|
||||
prompt: string;
|
||||
correct_answer: string;
|
||||
lies: RevealLie[];
|
||||
guesses: RevealGuess[];
|
||||
}
|
||||
|
||||
export interface SessionDetailResponse {
|
||||
session: SessionSummary;
|
||||
players: SessionPlayer[];
|
||||
round_question: SessionRoundQuestion | null;
|
||||
reveal: RevealPayload | null;
|
||||
phase_view_model: PhaseViewModel;
|
||||
}
|
||||
|
||||
@@ -138,6 +166,7 @@ export interface CalculateScoresResponse {
|
||||
round_number: number;
|
||||
};
|
||||
events_created: number;
|
||||
reveal: RevealPayload;
|
||||
leaderboard: Array<{ id: number; nickname: string; score: number }>;
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ export function deriveGameplayPhase(session: SessionDetailResponse | null): Game
|
||||
return null;
|
||||
}
|
||||
|
||||
if (status === 'lie' || status === 'guess' || status === 'reveal') {
|
||||
if (status === 'lie' || status === 'guess' || status === 'reveal' || status === 'scoreboard') {
|
||||
return status;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,31 +1,48 @@
|
||||
import lobbyCatalog from '../../../shared/i18n/lobby.json';
|
||||
import { DEFAULT_LOCALE, LOBBY_I18N_CATALOG, normalizeLocale } from '../../shared/i18n/lobby-loader';
|
||||
|
||||
type FrontendErrorKey = keyof typeof lobbyCatalog.frontend.errors;
|
||||
const frontendErrors = LOBBY_I18N_CATALOG.frontend.errors;
|
||||
const backendToFrontendErrorKeys = LOBBY_I18N_CATALOG.contract.backend_to_frontend_error_keys as Record<
|
||||
string,
|
||||
keyof typeof frontendErrors
|
||||
>;
|
||||
|
||||
const frontendErrors = lobbyCatalog.frontend.errors;
|
||||
type FrontendErrorKey = keyof typeof frontendErrors;
|
||||
|
||||
const apiErrorMap: Record<string, FrontendErrorKey> = {
|
||||
session_code_required: 'session_code_required',
|
||||
session_not_found: 'session_not_found',
|
||||
nickname_invalid: 'nickname_invalid',
|
||||
nickname_taken: 'nickname_taken'
|
||||
};
|
||||
|
||||
export function lobbyMessage(key: FrontendErrorKey): string {
|
||||
return frontendErrors[key] ?? frontendErrors.unknown;
|
||||
function isFrontendErrorKey(value: string): value is FrontendErrorKey {
|
||||
return value in frontendErrors;
|
||||
}
|
||||
|
||||
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey): string {
|
||||
export function lobbyMessage(key: FrontendErrorKey, locale?: string): string {
|
||||
const resolvedLocale = normalizeLocale(locale);
|
||||
const translations = frontendErrors[key] as Record<string, string>;
|
||||
|
||||
if (translations[resolvedLocale]) {
|
||||
return translations[resolvedLocale];
|
||||
}
|
||||
if (translations[DEFAULT_LOCALE]) {
|
||||
return translations[DEFAULT_LOCALE];
|
||||
}
|
||||
|
||||
return key;
|
||||
}
|
||||
|
||||
export function lobbyMessageFromApiPayload(payload: unknown, fallbackKey: FrontendErrorKey, locale?: string): string {
|
||||
if (!payload || typeof payload !== 'object') {
|
||||
return lobbyMessage(fallbackKey);
|
||||
return lobbyMessage(fallbackKey, locale);
|
||||
}
|
||||
|
||||
const record = payload as Record<string, unknown>;
|
||||
const code = typeof record.error_code === 'string' ? record.error_code : '';
|
||||
const mappedKey = apiErrorMap[code];
|
||||
if (!mappedKey) {
|
||||
return lobbyMessage(fallbackKey);
|
||||
const payloadLocale = typeof record.locale === 'string' ? record.locale : locale;
|
||||
const mappedKey = code ? backendToFrontendErrorKeys[code] : undefined;
|
||||
|
||||
if (mappedKey && isFrontendErrorKey(mappedKey)) {
|
||||
return lobbyMessage(mappedKey, payloadLocale);
|
||||
}
|
||||
|
||||
return lobbyMessage(mappedKey);
|
||||
if (isFrontendErrorKey(code)) {
|
||||
return lobbyMessage(code, payloadLocale);
|
||||
}
|
||||
|
||||
return lobbyMessage(fallbackKey, payloadLocale);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ describe('createAngularApiClient', () => {
|
||||
{ id: 3, nickname: 'Bo', score: 0, is_connected: false }
|
||||
],
|
||||
round_question: null,
|
||||
reveal: null,
|
||||
phase_view_model: {
|
||||
status: 'lobby',
|
||||
round_number: 1,
|
||||
@@ -84,6 +85,7 @@ describe('createAngularApiClient', () => {
|
||||
if (session.ok) {
|
||||
expect(session.data.session.code).toBe('ABCD12');
|
||||
expect(session.data.session.host_id).toBe(1);
|
||||
expect(session.data.reveal).toBeNull();
|
||||
expect(session.data.phase_view_model.host.can_start_round).toBe(true);
|
||||
}
|
||||
|
||||
@@ -119,6 +121,7 @@ describe('createAngularApiClient', () => {
|
||||
session: { code: 'ABCD12', status: 'lobby', host_id: 1, current_round: 1, players_count: 2 },
|
||||
players: [],
|
||||
round_question: null,
|
||||
reveal: null,
|
||||
phase_view_model: {
|
||||
status: 'lobby',
|
||||
round_number: 1,
|
||||
@@ -189,6 +192,117 @@ describe('createAngularApiClient', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('maps canonical reveal payload from session detail in reveal phase', async () => {
|
||||
const get = vi.fn<AngularHttpClientLike['get']>(async <T>(url: string) => {
|
||||
if (url === '/lobby/sessions/ABCD12') {
|
||||
return {
|
||||
session: { code: 'ABCD12', status: 'reveal', host_id: 1, current_round: 1, players_count: 3 },
|
||||
players: [
|
||||
{ id: 2, nickname: 'Maja', score: 4, is_connected: true },
|
||||
{ id: 3, nickname: 'Bo', score: 2, is_connected: true },
|
||||
{ id: 4, nickname: 'Ida', score: 5, is_connected: true }
|
||||
],
|
||||
round_question: {
|
||||
id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
shown_at: '2026-03-01T16:00:00Z',
|
||||
answers: [{ text: 'Edison' }, { text: 'Tesla' }]
|
||||
},
|
||||
reveal: {
|
||||
round_question_id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
correct_answer: 'Edison',
|
||||
lies: [
|
||||
{
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla',
|
||||
created_at: '2026-03-01T16:00:20Z'
|
||||
}
|
||||
],
|
||||
guesses: [
|
||||
{
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo',
|
||||
created_at: '2026-03-01T16:01:00Z'
|
||||
},
|
||||
{
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null,
|
||||
created_at: '2026-03-01T16:01:02Z'
|
||||
}
|
||||
]
|
||||
},
|
||||
phase_view_model: {
|
||||
status: 'reveal',
|
||||
round_number: 1,
|
||||
players_count: 3,
|
||||
constraints: {
|
||||
min_players_to_start: 2,
|
||||
max_players_mvp: 8,
|
||||
min_players_reached: true,
|
||||
max_players_allowed: true
|
||||
},
|
||||
host: {
|
||||
can_start_round: false,
|
||||
can_show_question: false,
|
||||
can_mix_answers: false,
|
||||
can_calculate_scores: false,
|
||||
can_reveal_scoreboard: true,
|
||||
can_start_next_round: true,
|
||||
can_finish_game: true
|
||||
},
|
||||
player: {
|
||||
can_join: false,
|
||||
can_submit_lie: false,
|
||||
can_submit_guess: false,
|
||||
can_view_final_result: false
|
||||
}
|
||||
}
|
||||
} as T;
|
||||
}
|
||||
|
||||
throw { status: 404, error: { error: 'Not found' } };
|
||||
});
|
||||
|
||||
const client = createAngularApiClient({ get, post: vi.fn() } as AngularHttpClientLike);
|
||||
const session = await client.getSession('abcd12');
|
||||
|
||||
expect(session.ok).toBe(true);
|
||||
if (session.ok) {
|
||||
expect(session.data.reveal?.correct_answer).toBe('Edison');
|
||||
expect(session.data.reveal?.lies[0]).toMatchObject({
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla'
|
||||
});
|
||||
expect(session.data.reveal?.guesses[0]).toMatchObject({
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo'
|
||||
});
|
||||
expect(session.data.reveal?.guesses[1]).toMatchObject({
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('returns parse error when successful payload breaks typed contract', async () => {
|
||||
const http = {
|
||||
get: vi.fn<AngularHttpClientLike['get']>(async <T>() => ({ ok: true } as T)),
|
||||
@@ -248,6 +362,39 @@ describe('createAngularApiClient', () => {
|
||||
session: { code: 'ABCD12', status: 'reveal', current_round: 1 },
|
||||
round_question: { id: 77, round_number: 1 },
|
||||
events_created: 3,
|
||||
reveal: {
|
||||
round_question_id: 77,
|
||||
round_number: 1,
|
||||
prompt: 'Hvem opfandt pæren?',
|
||||
correct_answer: 'Edison',
|
||||
lies: [
|
||||
{
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla',
|
||||
created_at: '2026-03-01T16:00:20Z'
|
||||
}
|
||||
],
|
||||
guesses: [
|
||||
{
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo',
|
||||
created_at: '2026-03-01T16:01:00Z'
|
||||
},
|
||||
{
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null,
|
||||
created_at: '2026-03-01T16:01:02Z'
|
||||
}
|
||||
]
|
||||
},
|
||||
leaderboard: [{ id: 2, nickname: 'Maja', score: 11 }]
|
||||
} as T;
|
||||
}
|
||||
@@ -305,6 +452,29 @@ describe('createAngularApiClient', () => {
|
||||
|
||||
const calculateScores = await client.calculateScores('abcd12', 77);
|
||||
expect(calculateScores.ok).toBe(true);
|
||||
if (calculateScores.ok) {
|
||||
expect(calculateScores.data.reveal.correct_answer).toBe('Edison');
|
||||
expect(calculateScores.data.reveal.lies[0]).toMatchObject({
|
||||
player_id: 3,
|
||||
nickname: 'Bo',
|
||||
text: 'Tesla'
|
||||
});
|
||||
expect(calculateScores.data.reveal.guesses[0]).toMatchObject({
|
||||
player_id: 2,
|
||||
nickname: 'Maja',
|
||||
selected_text: 'Tesla',
|
||||
is_correct: false,
|
||||
fooled_player_id: 3,
|
||||
fooled_player_nickname: 'Bo'
|
||||
});
|
||||
expect(calculateScores.data.reveal.guesses[1]).toMatchObject({
|
||||
player_id: 4,
|
||||
nickname: 'Ida',
|
||||
selected_text: 'Edison',
|
||||
is_correct: true,
|
||||
fooled_player_id: null
|
||||
});
|
||||
}
|
||||
|
||||
const scoreboard = await client.getScoreboard('abcd12');
|
||||
expect(scoreboard.ok).toBe(true);
|
||||
|
||||
68
frontend/tests/lobby-i18n.contract.test.ts
Normal file
68
frontend/tests/lobby-i18n.contract.test.ts
Normal file
@@ -0,0 +1,68 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import lobbyCatalog from '../../shared/i18n/lobby.json';
|
||||
import { lobbyMessage, lobbyMessageFromApiPayload } from '../src/spa/lobby-i18n';
|
||||
|
||||
describe('shared i18n keyspace contract', () => {
|
||||
it('keeps en as default and da/en matrix for frontend error keys', () => {
|
||||
expect(lobbyCatalog.locales.default).toBe('en');
|
||||
expect(lobbyCatalog.locales.supported).toEqual(expect.arrayContaining(['en', 'da']));
|
||||
|
||||
for (const [key, translations] of Object.entries(lobbyCatalog.frontend.errors)) {
|
||||
expect(translations.en, `${key} missing en`).toBeTruthy();
|
||||
expect(translations.da, `${key} missing da`).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps backend error-code keyspace aligned with shared backend→frontend map and backend translations', () => {
|
||||
for (const [code, backendKey] of Object.entries(lobbyCatalog.backend.error_codes)) {
|
||||
const frontendKey =
|
||||
lobbyCatalog.contract.backend_to_frontend_error_keys[
|
||||
code as keyof typeof lobbyCatalog.contract.backend_to_frontend_error_keys
|
||||
];
|
||||
|
||||
expect(lobbyCatalog.backend.errors[backendKey as keyof typeof lobbyCatalog.backend.errors]).toBeDefined();
|
||||
expect(frontendKey, `missing frontend mapping for ${code}`).toBeTruthy();
|
||||
expect(lobbyCatalog.frontend.errors[frontendKey as keyof typeof lobbyCatalog.frontend.errors]).toBeDefined();
|
||||
}
|
||||
|
||||
for (const [key, translations] of Object.entries(lobbyCatalog.backend.errors)) {
|
||||
expect(translations.en, `${key} missing en`).toBeTruthy();
|
||||
expect(translations.da, `${key} missing da`).toBeTruthy();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('lobbyMessage locale handling', () => {
|
||||
it('uses english by default and falls back to default for unsupported locale', () => {
|
||||
expect(lobbyMessage('session_code_required')).toBe('Session code is required.');
|
||||
expect(lobbyMessage('session_code_required', 'fr')).toBe('Session code is required.');
|
||||
});
|
||||
|
||||
it('resolves locale from api payload and maps known backend error codes directly', () => {
|
||||
expect(
|
||||
lobbyMessageFromApiPayload(
|
||||
{ error_code: 'session_not_found', locale: 'da' },
|
||||
'join_failed',
|
||||
),
|
||||
).toBe('Sessionskoden er ugyldig, eller sessionen findes ikke længere.');
|
||||
});
|
||||
|
||||
it('uses shared backend→frontend key-map at runtime even when fallback key differs', () => {
|
||||
expect(
|
||||
lobbyMessageFromApiPayload(
|
||||
{ error_code: 'session_not_joinable', locale: 'da' },
|
||||
'start_round_failed',
|
||||
),
|
||||
).toBe('Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen.');
|
||||
});
|
||||
|
||||
it('falls back to caller-provided fallback key for unknown backend error codes', () => {
|
||||
expect(
|
||||
lobbyMessageFromApiPayload(
|
||||
{ error_code: 'unknown_backend_key', locale: 'da' },
|
||||
'join_failed',
|
||||
),
|
||||
).toBe('Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen.');
|
||||
});
|
||||
});
|
||||
38
frontend/tests/lobby-loader.parity.test.ts
Normal file
38
frontend/tests/lobby-loader.parity.test.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
import {
|
||||
collectLocaleParityIssues,
|
||||
LOBBY_I18N_CATALOG,
|
||||
normalizeLocale,
|
||||
SUPPORTED_LOCALES,
|
||||
translateCatalogPath,
|
||||
} from '../shared/i18n/lobby-loader';
|
||||
|
||||
describe('shared lobby i18n loader parity', () => {
|
||||
it('keeps da/en translation parity in shared keyspace', () => {
|
||||
const issues = collectLocaleParityIssues(LOBBY_I18N_CATALOG, SUPPORTED_LOCALES);
|
||||
expect(issues).toEqual([]);
|
||||
});
|
||||
|
||||
it('normalizes browser-style locale tags to supported keyspace locales', () => {
|
||||
expect(normalizeLocale('da-DK')).toBe('da');
|
||||
expect(normalizeLocale('da_DK')).toBe('da');
|
||||
expect(normalizeLocale('en-US')).toBe('en');
|
||||
expect(normalizeLocale('en_US')).toBe('en');
|
||||
expect(normalizeLocale('fr-FR')).toBe('en');
|
||||
});
|
||||
|
||||
it('resolves shared frontend ui keys with fallback-safe behavior', () => {
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'host.start_round', 'da-DK'),
|
||||
).toBe('Start runde');
|
||||
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'app.language_label', 'en-US'),
|
||||
).toBe('Language');
|
||||
|
||||
expect(
|
||||
translateCatalogPath(LOBBY_I18N_CATALOG.frontend.ui as Record<string, unknown>, 'host.non_existing_key', 'da'),
|
||||
).toBe('host.non_existing_key');
|
||||
});
|
||||
});
|
||||
@@ -1,20 +1,90 @@
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
import logging
|
||||
|
||||
from django.http import JsonResponse
|
||||
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()
|
||||
|
||||
|
||||
def i18n_locale_config() -> tuple[str, tuple[str, ...]]:
|
||||
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 api_error(*, code: str, message: str, status: int) -> JsonResponse:
|
||||
return JsonResponse({"error": message, "error_code": code}, status=status)
|
||||
def lobby_i18n_error_messages() -> dict:
|
||||
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()
|
||||
|
||||
accept_language = request.META.get("HTTP_ACCEPT_LANGUAGE") or ""
|
||||
ranked_candidates: list[tuple[float, int, str]] = []
|
||||
for index, candidate in enumerate(accept_language.split(",")):
|
||||
quality = _quality_value(candidate)
|
||||
if quality is not None and quality <= 0:
|
||||
continue
|
||||
|
||||
tag = candidate.split(";", 1)[0]
|
||||
normalized = tag.strip().replace("_", "-").split("-", 1)[0].lower()
|
||||
if normalized not in supported_locales:
|
||||
continue
|
||||
|
||||
ranked_candidates.append((quality if quality is not None else 1.0, index, normalized))
|
||||
|
||||
if ranked_candidates:
|
||||
ranked_candidates.sort(key=lambda entry: (-entry[0], entry[1]))
|
||||
return ranked_candidates[0][2]
|
||||
|
||||
requested = (get_language_from_request(request) or "").replace("_", "-").split("-", 1)[0].lower()
|
||||
if requested in supported_locales:
|
||||
return requested
|
||||
return default_locale
|
||||
|
||||
|
||||
def resolve_error_message(*, key: str, locale: str) -> str:
|
||||
default_locale, _supported_locales = i18n_locale_config()
|
||||
translations = lobby_i18n_error_messages().get(key)
|
||||
if not isinstance(translations, dict):
|
||||
LOGGER.warning("i18n key missing in shared catalog", extra={"key": key, "locale": locale})
|
||||
return key
|
||||
|
||||
if locale in translations and translations[locale]:
|
||||
return translations[locale]
|
||||
if default_locale in translations and translations[default_locale]:
|
||||
return translations[default_locale]
|
||||
|
||||
LOGGER.warning("i18n translation missing for key", extra={"key": key, "locale": locale})
|
||||
return key
|
||||
|
||||
|
||||
def api_error(request: HttpRequest, *, key: str, status: int) -> JsonResponse:
|
||||
locale = resolve_locale(request)
|
||||
return JsonResponse(
|
||||
{
|
||||
"error": resolve_error_message(key=key, locale=locale),
|
||||
"error_code": key,
|
||||
"locale": locale,
|
||||
},
|
||||
status=status,
|
||||
)
|
||||
|
||||
@@ -89,6 +89,8 @@ var connectionRetryInFlight=false;
|
||||
var playerShellFatalError=false;
|
||||
var playerShellRecoverInFlight=false;
|
||||
var playerCriticalHydrated=false;
|
||||
function silencePlayerMediaElements(){if(typeof document==="undefined"||typeof document.querySelectorAll!=="function"){return;}var elements=document.querySelectorAll("audio,video");if(!elements||typeof elements.forEach!=="function"){return;}elements.forEach(function(element){if(!element){return;}element.muted=true;if(typeof element.pause==="function"){element.pause();}});}
|
||||
function installSecondaryDeviceAudioGuard(){if(typeof window==="undefined"){return;}silencePlayerMediaElements();var mediaProto=window.HTMLMediaElement&&window.HTMLMediaElement.prototype;if(!mediaProto||typeof mediaProto.play!=="function"){return;}if(mediaProto.__wppSecondaryDeviceAudioGuardInstalled){return;}mediaProto.__wppSecondaryDeviceAudioGuardInstalled=true;mediaProto.__wppSecondaryDeviceAudioGuardOriginalPlay=mediaProto.play;mediaProto.play=function(){return Promise.resolve();};}
|
||||
function setPlayerCriticalLoading(isLoading){var skeleton=document.getElementById("playerCriticalSkeleton");var view=document.getElementById("playerCriticalView");if(!skeleton||!view){return;}skeleton.style.display=isLoading?"block":"none";view.style.display=isLoading?"none":"block";}
|
||||
function hydratePlayerCriticalView(data){var phaseEl=document.getElementById("playerCriticalPhase");var roundEl=document.getElementById("playerCriticalRound");var joinEl=document.getElementById("playerCriticalJoin");if(phaseEl){phaseEl.textContent="Fase: "+phaseLabel(currentSessionStatus||((data&&data.session&&data.session.status)||""));}
|
||||
if(roundEl){roundEl.textContent="Round question: "+(rq()||"afventer");}
|
||||
@@ -153,6 +155,7 @@ function submitGuess(){if(guessSubmitted){return Promise.resolve({error:"guess_a
|
||||
["code","nickname","playerId","sessionToken","roundQuestionId"].forEach(function(fieldId){var field=document.getElementById(fieldId);if(!field){return;}field.addEventListener("input",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});field.addEventListener("change",function(){if(fieldId!=="roundQuestionId"){resetRoundContextForManualChange();}updateLieSubmitState();updateGuessSubmitState();updateJoinState();updateSessionDetailState();savePlayerContext();});});
|
||||
window.addEventListener("error",function(event){setPlayerShellFatalError((event&&event.message)||"Ukendt runtime-fejl");});
|
||||
window.addEventListener("unhandledrejection",function(event){var reason=event&&event.reason;var detail=(reason&&reason.message)||String(reason||"Unhandled promise rejection");setPlayerShellFatalError(detail);});
|
||||
installSecondaryDeviceAudioGuard();
|
||||
setPlayerCriticalLoading(true);
|
||||
updatePhaseStatus();
|
||||
updateGuessSubmitState();
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="da">
|
||||
<html lang="{{ shell_locale|default:'en' }}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>WPP SPA Shell</title>
|
||||
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css">
|
||||
<link rel="stylesheet" href="{{ spa_asset_base }}/styles.css?v={{ spa_asset_version|urlencode }}">
|
||||
</head>
|
||||
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">
|
||||
<app-root data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}">Indlæser Angular app-shell…</app-root>
|
||||
<script type="module" src="{{ spa_asset_base }}/main.js"></script>
|
||||
<body data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}" data-wpp-locale="{{ shell_locale|default:'en' }}">
|
||||
<app-root data-wpp-shell-route="{{ shell_route }}" data-wpp-shell-kind="{{ shell_kind }}" data-wpp-locale="{{ shell_locale|default:'en' }}">Indlæser Angular app-shell…</app-root>
|
||||
<script type="module" src="{{ spa_asset_base }}/main.js?v={{ spa_asset_version|urlencode }}"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
316
lobby/tests.py
316
lobby/tests.py
@@ -2,6 +2,7 @@ import json
|
||||
import tempfile
|
||||
from datetime import timedelta
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
|
||||
from django.contrib.auth import get_user_model
|
||||
from django.core.management import call_command
|
||||
@@ -19,6 +20,7 @@ from fupogfakta.models import (
|
||||
RoundConfig,
|
||||
RoundQuestion,
|
||||
)
|
||||
from lobby.i18n import i18n_locale_config, lobby_i18n_catalog, resolve_error_message, resolve_locale
|
||||
|
||||
User = get_user_model()
|
||||
|
||||
@@ -110,6 +112,43 @@ class LobbyFlowTests(TestCase):
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error"], "Session is not joinable")
|
||||
|
||||
def test_join_error_localizes_to_danish_with_accept_language_header(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(response.json()["error_code"], "session_code_required")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Sessionskode er påkrævet")
|
||||
|
||||
def test_join_error_falls_back_to_english_for_unsupported_locale(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": " ", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="fr",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "session_code_required")
|
||||
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)
|
||||
@@ -181,6 +220,8 @@ class StartRoundTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can start round")
|
||||
|
||||
def test_start_round_requires_existing_active_category_with_questions(self):
|
||||
@@ -200,6 +241,8 @@ class StartRoundTests(TestCase):
|
||||
content_type="application/json",
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error_code"], "category_has_no_questions")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Category has no active questions")
|
||||
|
||||
def test_start_round_rejects_non_lobby_session(self):
|
||||
@@ -216,6 +259,36 @@ class StartRoundTests(TestCase):
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()["error"], "Round can only be started from lobby")
|
||||
|
||||
def test_start_round_error_localizes_to_danish(self):
|
||||
self.client.login(username="other", password="secret123")
|
||||
|
||||
response = self.client.post(
|
||||
reverse("lobby:start_round", kwargs={"code": self.session.code}),
|
||||
data={"category_slug": self.category.slug},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "da")
|
||||
self.assertEqual(response.json()["error"], "Kun værten kan starte runden")
|
||||
|
||||
def test_start_round_error_falls_back_to_english_for_unsupported_locale(self):
|
||||
self.client.login(username="other", password="secret123")
|
||||
|
||||
response = self.client.post(
|
||||
reverse("lobby:start_round", kwargs={"code": self.session.code}),
|
||||
data={"category_slug": self.category.slug},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="fr",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_start_round")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can start round")
|
||||
|
||||
|
||||
class LieSubmissionTests(TestCase):
|
||||
def setUp(self):
|
||||
@@ -406,6 +479,8 @@ class MixAnswersTests(TestCase):
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()["error_code"], "host_only_mix_answers")
|
||||
self.assertEqual(response.json()["locale"], "en")
|
||||
self.assertEqual(response.json()["error"], "Only host can mix answers")
|
||||
|
||||
def test_mix_answers_deduplicates_case_insensitive_lies(self):
|
||||
@@ -612,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,
|
||||
@@ -640,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()
|
||||
@@ -971,6 +1098,10 @@ class UiScreenTests(TestCase):
|
||||
self.assertContains(response, "clearPlayerShellFatalError")
|
||||
self.assertContains(response, "updatePlayerShellErrorBoundary")
|
||||
self.assertContains(response, "player_shell_runtime_error")
|
||||
self.assertContains(response, "installSecondaryDeviceAudioGuard")
|
||||
self.assertContains(response, "silencePlayerMediaElements")
|
||||
self.assertContains(response, "querySelectorAll(\"audio,video\")")
|
||||
self.assertNotContains(response, "<audio")
|
||||
self.assertContains(response, "window.addEventListener(\"error\"")
|
||||
|
||||
@override_settings(USE_SPA_UI=False)
|
||||
@@ -995,7 +1126,8 @@ class UiScreenTests(TestCase):
|
||||
self.assertContains(response, "<app-root")
|
||||
self.assertContains(response, "data-wpp-shell-route=\"/host\"")
|
||||
self.assertContains(response, "data-wpp-shell-kind=\"host\"")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/main.js")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=dev")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/styles.css?v=dev")
|
||||
|
||||
@override_settings(USE_SPA_UI=True)
|
||||
def test_host_screen_deeplink_preserves_spa_path_when_feature_flag_enabled(self):
|
||||
@@ -1029,7 +1161,17 @@ class UiScreenTests(TestCase):
|
||||
self.assertContains(response, "<app-root")
|
||||
self.assertContains(response, "data-wpp-shell-route=\"/player\"")
|
||||
self.assertContains(response, "data-wpp-shell-kind=\"player\"")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/main.js")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=dev")
|
||||
|
||||
@override_settings(USE_SPA_UI=True, WPP_SPA_ASSET_VERSION="release-2026-03-01")
|
||||
def test_spa_shell_uses_configured_asset_version_for_cache_busting(self):
|
||||
self.client.login(username="host_ui", password="secret123")
|
||||
|
||||
response = self.client.get(reverse("lobby:host_screen"))
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertContains(response, "/static/frontend/angular/browser/styles.css?v=release-2026-03-01")
|
||||
self.assertContains(response, "/static/frontend/angular/browser/main.js?v=release-2026-03-01")
|
||||
|
||||
|
||||
class SessionDetailRoundQuestionTests(TestCase):
|
||||
@@ -1059,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):
|
||||
@@ -1174,3 +1371,118 @@ class SmokeStagingCommandTests(TestCase):
|
||||
"finish_game",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
class I18nResolverTests(TestCase):
|
||||
def test_resolve_locale_accepts_language_tags_and_normalizes_to_supported_base_locale(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da-DK,da;q=0.9,en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_accepts_underscore_language_tags(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da_DK",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_uses_next_supported_language_when_primary_is_unsupported(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="fr-FR, da;q=0.9, en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "da")
|
||||
|
||||
def test_resolve_locale_skips_q0_languages_and_falls_back_to_next_supported(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da;q=0, en;q=0.8",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_resolve_locale_prefers_highest_quality_supported_language(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
HTTP_ACCEPT_LANGUAGE="da;q=0.8, en;q=0.9",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_resolve_locale_defaults_to_en_when_header_missing(self):
|
||||
response = self.client.post(
|
||||
reverse("lobby:join_session"),
|
||||
data={"code": "", "nickname": "Luna"},
|
||||
content_type="application/json",
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(resolve_locale(response.wsgi_request), "en")
|
||||
|
||||
def test_missing_backend_key_returns_key_deterministically(self):
|
||||
self.assertEqual(resolve_error_message(key="missing_key", locale="da"), "missing_key")
|
||||
|
||||
def test_missing_backend_key_is_logged_with_context(self):
|
||||
with self.assertLogs("lobby.i18n", level="WARNING") as logs:
|
||||
result = resolve_error_message(key="missing_key", locale="da")
|
||||
|
||||
self.assertEqual(result, "missing_key")
|
||||
self.assertTrue(any("i18n key missing in shared catalog" in entry for entry in logs.output))
|
||||
|
||||
def test_missing_locale_translation_falls_back_to_default_locale(self):
|
||||
with patch(
|
||||
"lobby.i18n.lobby_i18n_error_messages",
|
||||
return_value={"session_code_required": {"en": "Session code is required"}},
|
||||
):
|
||||
self.assertEqual(
|
||||
resolve_error_message(key="session_code_required", locale="da"),
|
||||
"Session code is required",
|
||||
)
|
||||
|
||||
def test_shared_catalog_uses_en_default_and_da_en_matrix(self):
|
||||
default_locale, supported_locales = i18n_locale_config()
|
||||
catalog = lobby_i18n_catalog()
|
||||
|
||||
self.assertEqual(default_locale, "en")
|
||||
self.assertIn("en", supported_locales)
|
||||
self.assertIn("da", supported_locales)
|
||||
|
||||
for key, translations in catalog["backend"]["errors"].items():
|
||||
self.assertTrue(translations.get("en"), f"backend key {key} missing en")
|
||||
self.assertTrue(translations.get("da"), f"backend key {key} missing da")
|
||||
|
||||
for key, translations in catalog["frontend"]["errors"].items():
|
||||
self.assertTrue(translations.get("en"), f"frontend key {key} missing en")
|
||||
self.assertTrue(translations.get("da"), f"frontend key {key} missing da")
|
||||
|
||||
def test_backend_error_codes_map_via_shared_backend_frontend_key_map(self):
|
||||
catalog = lobby_i18n_catalog()
|
||||
backend_errors = catalog["backend"]["errors"]
|
||||
frontend_errors = catalog["frontend"]["errors"]
|
||||
shared_map = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
|
||||
for code, backend_key in catalog["backend"]["error_codes"].items():
|
||||
frontend_key = shared_map.get(code)
|
||||
self.assertIn(backend_key, backend_errors)
|
||||
self.assertTrue(frontend_key, f"missing frontend mapping for backend code: {code}")
|
||||
self.assertIn(frontend_key, frontend_errors)
|
||||
|
||||
@@ -5,7 +5,7 @@ from django.shortcuts import render
|
||||
from fupogfakta.models import Category
|
||||
|
||||
from .feature_flags import use_spa_ui
|
||||
from .i18n import lobby_i18n_catalog
|
||||
from .i18n import lobby_i18n_catalog, resolve_locale
|
||||
|
||||
|
||||
def _render_spa_shell(request, shell_route: str, shell_kind: str):
|
||||
@@ -16,7 +16,9 @@ def _render_spa_shell(request, shell_route: str, shell_kind: str):
|
||||
"shell_route": shell_route,
|
||||
"shell_kind": shell_kind,
|
||||
"spa_asset_base": settings.WPP_SPA_ASSET_BASE,
|
||||
"spa_asset_version": getattr(settings, "WPP_SPA_ASSET_VERSION", "dev"),
|
||||
"lobby_i18n": lobby_i18n_catalog(),
|
||||
"shell_locale": resolve_locale(request),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
182
lobby/views.py
182
lobby/views.py
@@ -61,6 +61,52 @@ def _create_unique_session_code() -> str:
|
||||
raise RuntimeError("Could not generate unique session code")
|
||||
|
||||
|
||||
def _build_player_ref(player: Player | None) -> dict | None:
|
||||
if player is None:
|
||||
return None
|
||||
|
||||
return {
|
||||
"player_id": player.id,
|
||||
"nickname": player.nickname,
|
||||
}
|
||||
|
||||
|
||||
def _build_reveal_payload(round_question: RoundQuestion | None) -> dict | None:
|
||||
if round_question is None:
|
||||
return None
|
||||
|
||||
lies = [
|
||||
{
|
||||
**_build_player_ref(lie.player),
|
||||
"text": lie.text,
|
||||
"created_at": lie.created_at.isoformat(),
|
||||
}
|
||||
for lie in round_question.lies.select_related("player").order_by("created_at", "id")
|
||||
]
|
||||
|
||||
guesses = []
|
||||
for guess in round_question.guesses.select_related("player", "fooled_player").order_by("created_at", "id"):
|
||||
guess_payload = {
|
||||
**_build_player_ref(guess.player),
|
||||
"selected_text": guess.selected_text,
|
||||
"is_correct": guess.is_correct,
|
||||
"created_at": guess.created_at.isoformat(),
|
||||
"fooled_player_id": guess.fooled_player_id,
|
||||
}
|
||||
if guess.fooled_player is not None:
|
||||
guess_payload["fooled_player_nickname"] = guess.fooled_player.nickname
|
||||
guesses.append(guess_payload)
|
||||
|
||||
return {
|
||||
"round_question_id": round_question.id,
|
||||
"round_number": round_question.round_number,
|
||||
"prompt": round_question.question.prompt,
|
||||
"correct_answer": round_question.correct_answer,
|
||||
"lies": lies,
|
||||
"guesses": guesses,
|
||||
}
|
||||
|
||||
|
||||
def _build_phase_view_model(session: GameSession, *, players_count: int, has_round_question: bool) -> dict:
|
||||
status = session.status
|
||||
in_lobby = status == GameSession.Status.LOBBY
|
||||
@@ -128,15 +174,15 @@ def join_session(request: HttpRequest) -> JsonResponse:
|
||||
|
||||
if not code:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("session_code_required", "session_code_required"),
|
||||
message="Session code is required",
|
||||
request,
|
||||
key=ERROR_CODES.get("session_code_required", "session_code_required"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
if len(nickname) < 2 or len(nickname) > 40:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("nickname_invalid", "nickname_invalid"),
|
||||
message="Nickname must be between 2 and 40 characters",
|
||||
request,
|
||||
key=ERROR_CODES.get("nickname_invalid", "nickname_invalid"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -144,22 +190,22 @@ def join_session(request: HttpRequest) -> JsonResponse:
|
||||
session = GameSession.objects.get(code=code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
message="Session not found",
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.status not in JOINABLE_STATUSES:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("session_not_joinable", "session_not_joinable"),
|
||||
message="Session is not joinable",
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_joinable", "session_not_joinable"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
if Player.objects.filter(session=session, nickname__iexact=nickname).exists():
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("nickname_taken", "nickname_taken"),
|
||||
message="Nickname already taken",
|
||||
request,
|
||||
key=ERROR_CODES.get("nickname_taken", "nickname_taken"),
|
||||
status=409,
|
||||
)
|
||||
|
||||
@@ -190,8 +236,8 @@ def session_detail(request: HttpRequest, code: str) -> JsonResponse:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
message="Session not found",
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
)
|
||||
@@ -251,8 +300,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
|
||||
if not category_slug:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("category_slug_required", "category_slug_required"),
|
||||
message="category_slug is required",
|
||||
request,
|
||||
key=ERROR_CODES.get("category_slug_required", "category_slug_required"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -262,18 +311,22 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
message="Session not found",
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can start round"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_start_round", "host_only_start_round"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LOBBY:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
message="Round can only be started from lobby",
|
||||
request,
|
||||
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -281,20 +334,24 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
category = Category.objects.get(slug=category_slug, is_active=True)
|
||||
except Category.DoesNotExist:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("category_not_found", "category_not_found"),
|
||||
message="Category not found",
|
||||
request,
|
||||
key=ERROR_CODES.get("category_not_found", "category_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if not Question.objects.filter(category=category, is_active=True).exists():
|
||||
return JsonResponse({"error": "Category has no active questions"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("category_has_no_questions", "category_has_no_questions"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if session.status != GameSession.Status.LOBBY:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
message="Round can only be started from lobby",
|
||||
request,
|
||||
key=ERROR_CODES.get("round_start_invalid_phase", "round_start_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
@@ -305,8 +362,8 @@ def start_round(request: HttpRequest, code: str) -> JsonResponse:
|
||||
)
|
||||
if not created:
|
||||
return api_error(
|
||||
code=ERROR_CODES.get("round_already_configured", "round_already_configured"),
|
||||
message="Round already configured",
|
||||
request,
|
||||
key=ERROR_CODES.get("round_already_configured", "round_already_configured"),
|
||||
status=409,
|
||||
)
|
||||
|
||||
@@ -340,21 +397,41 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can show question"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_show_question", "host_only_show_question"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status != GameSession.Status.LIE:
|
||||
return JsonResponse({"error": "Question can only be shown in lie phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("show_question_invalid_phase", "show_question_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
round_config = RoundConfig.objects.get(session=session, number=session.current_round)
|
||||
except RoundConfig.DoesNotExist:
|
||||
return JsonResponse({"error": "Round config missing"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_config_missing", "round_config_missing"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
if RoundQuestion.objects.filter(session=session, round_number=session.current_round).exists():
|
||||
return JsonResponse({"error": "Question already shown for this round"}, status=409)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("question_already_shown", "question_already_shown"),
|
||||
status=409,
|
||||
)
|
||||
|
||||
used_question_ids = RoundQuestion.objects.filter(session=session).values_list("question_id", flat=True)
|
||||
available_questions = Question.objects.filter(
|
||||
@@ -363,7 +440,11 @@ def show_question(request: HttpRequest, code: str) -> JsonResponse:
|
||||
).exclude(pk__in=used_question_ids)
|
||||
|
||||
if not available_questions.exists():
|
||||
return JsonResponse({"error": "No available questions in category"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("no_available_questions", "no_available_questions"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
question = random.choice(list(available_questions))
|
||||
round_question = RoundQuestion.objects.create(
|
||||
@@ -473,13 +554,25 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
try:
|
||||
session = GameSession.objects.get(code=session_code)
|
||||
except GameSession.DoesNotExist:
|
||||
return JsonResponse({"error": "Session not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("session_not_found", "session_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
if session.host_id != request.user.id:
|
||||
return JsonResponse({"error": "Only host can mix answers"}, status=403)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("host_only_mix_answers", "host_only_mix_answers"),
|
||||
status=403,
|
||||
)
|
||||
|
||||
if session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return JsonResponse({"error": "Answers can only be mixed in lie or guess phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
try:
|
||||
round_question = RoundQuestion.objects.get(
|
||||
@@ -488,12 +581,20 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
round_number=session.current_round,
|
||||
)
|
||||
except RoundQuestion.DoesNotExist:
|
||||
return JsonResponse({"error": "Round question not found"}, status=404)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("round_question_not_found", "round_question_not_found"),
|
||||
status=404,
|
||||
)
|
||||
|
||||
with transaction.atomic():
|
||||
locked_session = GameSession.objects.select_for_update().get(pk=session.pk)
|
||||
if locked_session.status not in {GameSession.Status.LIE, GameSession.Status.GUESS}:
|
||||
return JsonResponse({"error": "Answers can only be mixed in lie or guess phase"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("mix_answers_invalid_phase", "mix_answers_invalid_phase"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
locked_round_question = RoundQuestion.objects.select_for_update().get(pk=round_question.pk)
|
||||
|
||||
@@ -509,7 +610,11 @@ def mix_answers(request: HttpRequest, code: str, round_question_id: int) -> Json
|
||||
deduped_answers.append(text.strip())
|
||||
|
||||
if len(deduped_answers) < 2:
|
||||
return JsonResponse({"error": "Not enough answers to mix"}, status=400)
|
||||
return api_error(
|
||||
request,
|
||||
key=ERROR_CODES.get("not_enough_answers_to_mix", "not_enough_answers_to_mix"),
|
||||
status=400,
|
||||
)
|
||||
|
||||
random.shuffle(deduped_answers)
|
||||
locked_round_question.mixed_answers = deduped_answers
|
||||
@@ -853,6 +958,7 @@ def calculate_scores(request: HttpRequest, code: str, round_question_id: int) ->
|
||||
"id": round_question.id,
|
||||
"round_number": round_question.round_number,
|
||||
},
|
||||
"reveal": _build_reveal_payload(round_question),
|
||||
"events_created": len(score_events),
|
||||
"leaderboard": leaderboard,
|
||||
}
|
||||
|
||||
30
partyhub/i18n_bootstrap.py
Normal file
30
partyhub/i18n_bootstrap.py
Normal file
@@ -0,0 +1,30 @@
|
||||
import json
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
|
||||
_LOCALE_LABELS = {
|
||||
"en": "English",
|
||||
"da": "Danish",
|
||||
}
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def shared_i18n_catalog() -> dict:
|
||||
catalog_path = Path(__file__).resolve().parents[1] / "shared" / "i18n" / "lobby.json"
|
||||
with catalog_path.open(encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def locale_config() -> tuple[str, tuple[str, ...]]:
|
||||
locales = shared_i18n_catalog().get("locales", {})
|
||||
default_locale = str(locales.get("default", "en")).strip().lower() or "en"
|
||||
supported_locales = tuple(
|
||||
locale.strip().lower() for locale in locales.get("supported", ["en", "da"]) if str(locale).strip()
|
||||
) or ("en", "da")
|
||||
return default_locale, supported_locales
|
||||
|
||||
|
||||
def django_languages() -> list[tuple[str, str]]:
|
||||
_default_locale, supported_locales = locale_config()
|
||||
return [(locale, _LOCALE_LABELS.get(locale, locale.upper())) for locale in supported_locales]
|
||||
@@ -1,6 +1,8 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
from partyhub.i18n_bootstrap import django_languages, locale_config
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
@@ -30,6 +32,7 @@ INSTALLED_APPS = [
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.locale.LocaleMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
@@ -89,7 +92,9 @@ AUTH_PASSWORD_VALIDATORS = [
|
||||
{'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator'},
|
||||
]
|
||||
|
||||
LANGUAGE_CODE = 'da'
|
||||
LANGUAGE_CODE, _SUPPORTED_LOCALES = locale_config()
|
||||
LANGUAGES = django_languages()
|
||||
LOCALE_PATHS = [BASE_DIR / 'locale']
|
||||
TIME_ZONE = 'Europe/Copenhagen'
|
||||
USE_I18N = True
|
||||
USE_TZ = True
|
||||
@@ -105,6 +110,9 @@ if USE_SPA_UI_RAW is None:
|
||||
USE_SPA_UI_RAW = env('WPP_SPA_ENABLED', 'false')
|
||||
USE_SPA_UI = USE_SPA_UI_RAW.lower() == 'true'
|
||||
WPP_SPA_ASSET_BASE = env('WPP_SPA_ASSET_BASE', '/static/frontend/angular/browser').rstrip('/')
|
||||
# Cache-busting token for SPA shell static asset URLs (querystring versioning).
|
||||
# Set to release id / commit SHA in deploy env for deterministic invalidation.
|
||||
WPP_SPA_ASSET_VERSION = env('WPP_SPA_ASSET_VERSION', 'dev')
|
||||
|
||||
CHANNEL_REDIS_HOST = env('CHANNEL_REDIS_HOST', '127.0.0.1')
|
||||
CHANNEL_REDIS_PORT = int(env('CHANNEL_REDIS_PORT', '6379'))
|
||||
|
||||
28
partyhub/tests_i18n_bootstrap.py
Normal file
28
partyhub/tests_i18n_bootstrap.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from django.conf import settings
|
||||
from django.test import TestCase
|
||||
|
||||
from partyhub.i18n_bootstrap import django_languages, locale_config, shared_i18n_catalog
|
||||
|
||||
|
||||
class I18nBootstrapTests(TestCase):
|
||||
def test_shared_catalog_bootstraps_default_and_supported_locales(self):
|
||||
default_locale, supported_locales = locale_config()
|
||||
|
||||
self.assertEqual(default_locale, "en")
|
||||
self.assertEqual(supported_locales, ("en", "da"))
|
||||
|
||||
def test_django_language_settings_bootstrap_from_shared_i18n_catalog(self):
|
||||
default_locale, supported_locales = locale_config()
|
||||
|
||||
self.assertEqual(settings.LANGUAGE_CODE, default_locale)
|
||||
self.assertEqual(tuple(code for code, _ in settings.LANGUAGES), supported_locales)
|
||||
self.assertEqual(settings.LANGUAGES, django_languages())
|
||||
|
||||
def test_locale_contract_in_catalog_matches_django_language_codes(self):
|
||||
catalog_locales = shared_i18n_catalog()["locales"]
|
||||
|
||||
self.assertEqual(settings.LANGUAGE_CODE, catalog_locales["default"])
|
||||
self.assertEqual(
|
||||
[code for code, _ in settings.LANGUAGES],
|
||||
catalog_locales["supported"],
|
||||
)
|
||||
214
scripts/build_i18n_parity_report.py
Normal file
214
scripts/build_i18n_parity_report.py
Normal file
@@ -0,0 +1,214 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Build the shared i18n parity artifact for MVP-critical Django/Angular keys."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
ARTIFACT_PATH = REPO_ROOT / "shared" / "i18n" / "artifacts" / "lobby-mvp-keyspace-parity-report.v1.json"
|
||||
DJANGO_VIEWS_PATH = REPO_ROOT / "lobby" / "views.py"
|
||||
FRONTEND_VERTICAL_SLICE_PATH = REPO_ROOT / "frontend" / "src" / "spa" / "vertical-slice.ts"
|
||||
ANGULAR_I18N_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "lobby-i18n.ts"
|
||||
ANGULAR_HOST_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "features" / "host" / "host-shell.component.ts"
|
||||
ANGULAR_PLAYER_PATH = REPO_ROOT / "frontend" / "angular" / "src" / "app" / "features" / "player" / "player-shell.component.ts"
|
||||
|
||||
ARTIFACT_NAME = "shared.i18n.lobby.mvp_keyspace_parity_report"
|
||||
ARTIFACT_VERSION = "v1"
|
||||
|
||||
|
||||
class ParityError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
def _read_text(path: Path) -> str:
|
||||
return path.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _load_catalog() -> dict[str, Any]:
|
||||
return json.loads(_read_text(CATALOG_PATH))
|
||||
|
||||
|
||||
def _catalog_hash() -> str:
|
||||
return hashlib.sha256(CATALOG_PATH.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def _sorted_unique(values: list[str]) -> list[str]:
|
||||
return sorted({value for value in values})
|
||||
|
||||
|
||||
def _extract_matches(path: Path, pattern: str) -> list[str]:
|
||||
return re.findall(pattern, _read_text(path), re.MULTILINE)
|
||||
|
||||
|
||||
def _resolve_frontend_ui_key(key: str) -> str:
|
||||
if key.startswith("lobby.shell."):
|
||||
return key.replace("lobby.shell.", "app.", 1)
|
||||
if key.startswith("game.host."):
|
||||
return key.replace("game.host.", "host.", 1)
|
||||
if key.startswith("game.player."):
|
||||
return key.replace("game.player.", "player.", 1)
|
||||
return key
|
||||
|
||||
|
||||
def _has_nested_key(root: dict[str, Any], dotted_key: str) -> bool:
|
||||
current: Any = root
|
||||
for part in dotted_key.split("."):
|
||||
if not isinstance(current, dict) or part not in current:
|
||||
return False
|
||||
current = current[part]
|
||||
return isinstance(current, dict)
|
||||
|
||||
|
||||
def build_report() -> dict[str, Any]:
|
||||
catalog = _load_catalog()
|
||||
locales = list(catalog["locales"]["supported"])
|
||||
frontend_errors: dict[str, Any] = catalog["frontend"]["errors"]
|
||||
frontend_ui: dict[str, Any] = catalog["frontend"]["ui"]
|
||||
backend_error_codes: dict[str, str] = catalog["backend"]["error_codes"]
|
||||
backend_errors: dict[str, Any] = catalog["backend"]["errors"]
|
||||
backend_to_frontend: dict[str, str] = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
|
||||
django_error_codes = _sorted_unique(
|
||||
_extract_matches(DJANGO_VIEWS_PATH, r'ERROR_CODES\.get\("([a-z0-9_]+)"')
|
||||
)
|
||||
frontend_runtime_error_fallbacks = _sorted_unique(
|
||||
_extract_matches(FRONTEND_VERTICAL_SLICE_PATH, r"lobbyMessageFromApiPayload\([^\n]+?'([a-z0-9_]+)'\)")
|
||||
+ _extract_matches(FRONTEND_VERTICAL_SLICE_PATH, r"lobbyMessage\('([a-z0-9_]+)'\)")
|
||||
)
|
||||
angular_copy_keys = _sorted_unique(
|
||||
_extract_matches(ANGULAR_HOST_PATH, r"copy\('([A-Za-z0-9_\.]+)'\)")
|
||||
+ _extract_matches(ANGULAR_PLAYER_PATH, r"copy\('([A-Za-z0-9_\.]+)'\)")
|
||||
)
|
||||
angular_catalog_paths = [_resolve_frontend_ui_key(key) for key in angular_copy_keys]
|
||||
|
||||
missing_backend_codes = [code for code in django_error_codes if code not in backend_error_codes]
|
||||
missing_backend_translations = [code for code in django_error_codes if code not in backend_errors]
|
||||
missing_contract_mappings = [code for code in django_error_codes if code not in backend_to_frontend]
|
||||
mapped_frontend_error_keys = _sorted_unique(
|
||||
[backend_to_frontend[code] for code in django_error_codes if code in backend_to_frontend]
|
||||
)
|
||||
missing_frontend_error_keys = [key for key in mapped_frontend_error_keys if key not in frontend_errors]
|
||||
missing_frontend_runtime_fallbacks = [key for key in frontend_runtime_error_fallbacks if key not in frontend_errors]
|
||||
missing_angular_catalog_paths = [path for path in angular_catalog_paths if not _has_nested_key(frontend_ui, path)]
|
||||
|
||||
dead_contract_aliases = _sorted_unique([code for code in backend_to_frontend if code not in backend_error_codes])
|
||||
many_to_one_mappings: dict[str, list[str]] = defaultdict(list)
|
||||
for code in django_error_codes:
|
||||
frontend_key = backend_to_frontend.get(code)
|
||||
if frontend_key:
|
||||
many_to_one_mappings[frontend_key].append(code)
|
||||
many_to_one_mappings = {
|
||||
frontend_key: sorted(codes)
|
||||
for frontend_key, codes in sorted(many_to_one_mappings.items())
|
||||
if len(codes) > 1
|
||||
}
|
||||
|
||||
blocking_issues = {
|
||||
"missing_backend_codes": missing_backend_codes,
|
||||
"missing_backend_translations": missing_backend_translations,
|
||||
"missing_contract_mappings": missing_contract_mappings,
|
||||
"missing_frontend_error_keys": missing_frontend_error_keys,
|
||||
"missing_frontend_runtime_fallbacks": missing_frontend_runtime_fallbacks,
|
||||
"missing_angular_catalog_paths": missing_angular_catalog_paths,
|
||||
}
|
||||
status = "pass" if not any(blocking_issues.values()) else "fail"
|
||||
|
||||
follow_ups: list[dict[str, str]] = []
|
||||
if dead_contract_aliases:
|
||||
follow_ups.append(
|
||||
{
|
||||
"priority": "need-to-have",
|
||||
"item": "Either add missing backend/error_codes + backend/errors entries for dead contract aliases or remove them from contract.backend_to_frontend_error_keys.",
|
||||
"evidence": ", ".join(dead_contract_aliases),
|
||||
}
|
||||
)
|
||||
if many_to_one_mappings:
|
||||
follow_ups.append(
|
||||
{
|
||||
"priority": "nice-to-have",
|
||||
"item": "Decide whether grouped backend codes should keep collapsing into one Angular fallback key or be split into more specific frontend error copy as UX matures.",
|
||||
"evidence": "; ".join(
|
||||
f"{frontend_key} <= {', '.join(codes)}" for frontend_key, codes in many_to_one_mappings.items()
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"artifact_name": ARTIFACT_NAME,
|
||||
"artifact_version": ARTIFACT_VERSION,
|
||||
"naming_version_rule": "Keep a stable artifact_name and append only explicit schema-major suffixes to the filename/version (v1, v2, ...). Update artifact_version only when the report shape changes; refresh content in-place for catalog/keyspace changes.",
|
||||
"source_of_truth": {
|
||||
"catalog": str(CATALOG_PATH.relative_to(REPO_ROOT)),
|
||||
"catalog_sha256": _catalog_hash(),
|
||||
"source_paths": [
|
||||
str(path.relative_to(REPO_ROOT))
|
||||
for path in [
|
||||
DJANGO_VIEWS_PATH,
|
||||
FRONTEND_VERTICAL_SLICE_PATH,
|
||||
ANGULAR_I18N_PATH,
|
||||
ANGULAR_HOST_PATH,
|
||||
ANGULAR_PLAYER_PATH,
|
||||
]
|
||||
],
|
||||
},
|
||||
"scope": {
|
||||
"issue": 277,
|
||||
"related_epic": 175,
|
||||
"mvp_locales": locales,
|
||||
"definition": "MVP-critical keys are the Django error codes emitted by lobby/views.py plus the Angular fallback/UI keys consumed by the host/player MVP shells.",
|
||||
},
|
||||
"parity": {
|
||||
"status": status,
|
||||
"django_backend_error_codes_used_by_mvp": django_error_codes,
|
||||
"angular_frontend_error_fallback_keys_used_by_mvp": frontend_runtime_error_fallbacks,
|
||||
"angular_ui_keys_used_by_mvp": angular_copy_keys,
|
||||
"angular_ui_catalog_paths": angular_catalog_paths,
|
||||
"backend_codes_mapped_to_frontend_error_keys": {code: backend_to_frontend[code] for code in django_error_codes if code in backend_to_frontend},
|
||||
"unique_frontend_error_keys_reached_from_django": mapped_frontend_error_keys,
|
||||
"blocking_issues": blocking_issues,
|
||||
"follow_ups": follow_ups,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def write_report() -> None:
|
||||
report = build_report()
|
||||
ARTIFACT_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
ARTIFACT_PATH.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
def check_report() -> None:
|
||||
report = build_report()
|
||||
if not ARTIFACT_PATH.exists():
|
||||
raise ParityError(f"artifact missing: {ARTIFACT_PATH}")
|
||||
existing = json.loads(_read_text(ARTIFACT_PATH))
|
||||
if existing != report:
|
||||
raise ParityError("artifact out of date; run scripts/build_i18n_parity_report.py --write")
|
||||
if report["parity"]["status"] != "pass":
|
||||
raise ParityError(json.dumps(report["parity"]["blocking_issues"], indent=2))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--write", action="store_true")
|
||||
parser.add_argument("--check", action="store_true")
|
||||
args = parser.parse_args()
|
||||
if args.write:
|
||||
write_report()
|
||||
if args.check:
|
||||
check_report()
|
||||
if not args.write and not args.check:
|
||||
print(json.dumps(build_report(), indent=2, ensure_ascii=False))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
132
scripts/check_i18n_drift.py
Executable file
132
scripts/check_i18n_drift.py
Executable file
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Read-only drift check for shared i18n key coverage.
|
||||
|
||||
Compares `shared/i18n/key-manifest.json` against `shared/i18n/lobby.json` and
|
||||
fails fast when keyspaces drift between frontend/backend contract sections.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
MANIFEST_PATH = REPO_ROOT / "shared" / "i18n" / "key-manifest.json"
|
||||
|
||||
|
||||
def _load_json(path: Path) -> dict[str, Any]:
|
||||
with path.open("r", encoding="utf-8") as handle:
|
||||
return json.load(handle)
|
||||
|
||||
|
||||
def _as_set(value: Any) -> set[str]:
|
||||
if not isinstance(value, list):
|
||||
return set()
|
||||
return {str(item) for item in value}
|
||||
|
||||
|
||||
def _require_translations(
|
||||
errors: dict[str, Any],
|
||||
locales: set[str],
|
||||
label: str,
|
||||
failures: list[str],
|
||||
) -> None:
|
||||
for key, translations in errors.items():
|
||||
if not isinstance(translations, dict):
|
||||
failures.append(f"{label}.{key} must be an object of locale->message")
|
||||
continue
|
||||
|
||||
for locale in sorted(locales):
|
||||
value = translations.get(locale)
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
failures.append(f"{label}.{key} missing non-empty '{locale}' translation")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
catalog = _load_json(CATALOG_PATH)
|
||||
manifest = _load_json(MANIFEST_PATH)
|
||||
|
||||
failures: list[str] = []
|
||||
|
||||
manifest_locales = _as_set(manifest.get("locales"))
|
||||
catalog_locales = _as_set(catalog.get("locales", {}).get("supported"))
|
||||
if manifest_locales != catalog_locales:
|
||||
failures.append(
|
||||
"locale set mismatch: "
|
||||
f"manifest={sorted(manifest_locales)} catalog={sorted(catalog_locales)}"
|
||||
)
|
||||
|
||||
frontend_manifest = _as_set(manifest.get("frontend_error_keys"))
|
||||
frontend_catalog = set(catalog.get("frontend", {}).get("errors", {}).keys())
|
||||
if frontend_manifest != frontend_catalog:
|
||||
failures.append(
|
||||
"frontend error key mismatch: "
|
||||
f"manifest-only={sorted(frontend_manifest - frontend_catalog)} "
|
||||
f"catalog-only={sorted(frontend_catalog - frontend_manifest)}"
|
||||
)
|
||||
|
||||
backend_code_manifest = _as_set(manifest.get("backend_error_codes"))
|
||||
backend_code_catalog = set(catalog.get("backend", {}).get("error_codes", {}).keys())
|
||||
if backend_code_manifest != backend_code_catalog:
|
||||
failures.append(
|
||||
"backend error code mismatch: "
|
||||
f"manifest-only={sorted(backend_code_manifest - backend_code_catalog)} "
|
||||
f"catalog-only={sorted(backend_code_catalog - backend_code_manifest)}"
|
||||
)
|
||||
|
||||
backend_key_manifest = _as_set(manifest.get("backend_error_keys"))
|
||||
backend_key_catalog = set(catalog.get("backend", {}).get("errors", {}).keys())
|
||||
if backend_key_manifest != backend_key_catalog:
|
||||
failures.append(
|
||||
"backend error key mismatch: "
|
||||
f"manifest-only={sorted(backend_key_manifest - backend_key_catalog)} "
|
||||
f"catalog-only={sorted(backend_key_catalog - backend_key_manifest)}"
|
||||
)
|
||||
|
||||
backend_to_frontend = catalog.get("contract", {}).get("backend_to_frontend_error_keys", {})
|
||||
if not isinstance(backend_to_frontend, dict):
|
||||
failures.append("contract.backend_to_frontend_error_keys must be an object")
|
||||
backend_to_frontend = {}
|
||||
|
||||
for code in sorted(backend_code_catalog):
|
||||
frontend_key = backend_to_frontend.get(code)
|
||||
if frontend_key is None:
|
||||
failures.append(f"missing contract mapping for backend code '{code}'")
|
||||
continue
|
||||
if frontend_key not in frontend_catalog:
|
||||
failures.append(
|
||||
f"mapping for backend code '{code}' points to unknown frontend key '{frontend_key}'"
|
||||
)
|
||||
|
||||
allowed_contract_only_codes = _as_set(manifest.get("allowed_contract_only_backend_codes"))
|
||||
unknown_mapping_codes = set(backend_to_frontend.keys()) - backend_code_catalog
|
||||
disallowed_unknown_mapping_codes = unknown_mapping_codes - allowed_contract_only_codes
|
||||
if disallowed_unknown_mapping_codes:
|
||||
failures.append(
|
||||
"contract contains mappings for unknown backend codes: "
|
||||
f"{sorted(disallowed_unknown_mapping_codes)}"
|
||||
)
|
||||
|
||||
_require_translations(catalog.get("frontend", {}).get("errors", {}), manifest_locales, "frontend.errors", failures)
|
||||
_require_translations(catalog.get("backend", {}).get("errors", {}), manifest_locales, "backend.errors", failures)
|
||||
|
||||
if failures:
|
||||
print("i18n drift check FAILED")
|
||||
for failure in failures:
|
||||
print(f" - {failure}")
|
||||
return 1
|
||||
|
||||
print("i18n drift check OK")
|
||||
print(f" - locales: {sorted(manifest_locales)}")
|
||||
print(f" - frontend error keys: {len(frontend_catalog)}")
|
||||
print(f" - backend error codes: {len(backend_code_catalog)}")
|
||||
print(f" - backend error keys: {len(backend_key_catalog)}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
36
scripts/check_i18n_parity_artifact.py
Normal file
36
scripts/check_i18n_parity_artifact.py
Normal file
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Guard issue #277 parity artifact against non-deterministic regeneration."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
ARTIFACT_PATH = REPO_ROOT / "docs" / "ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md"
|
||||
REPORT_SCRIPT = REPO_ROOT / "scripts" / "report_i18n_parity.py"
|
||||
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
return hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
before = sha256(ARTIFACT_PATH)
|
||||
|
||||
for run in range(1, 3):
|
||||
subprocess.run([sys.executable, str(REPORT_SCRIPT)], cwd=REPO_ROOT, check=True)
|
||||
after = sha256(ARTIFACT_PATH)
|
||||
if after != before:
|
||||
raise SystemExit(
|
||||
f"issue #277 parity artifact is not deterministic after run {run}: {before} != {after}"
|
||||
)
|
||||
|
||||
print(f"issue #277 parity artifact deterministic: {before}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
196
scripts/report_i18n_parity.py
Normal file
196
scripts/report_i18n_parity.py
Normal file
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate issue #277 shared i18n parity artifact.
|
||||
|
||||
Read-only report over the shared lobby i18n catalog, with focus on MVP-critical
|
||||
backend/frontend parity used by Django and Angular.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
CATALOG_PATH = REPO_ROOT / "shared" / "i18n" / "lobby.json"
|
||||
OUTPUT_PATH = REPO_ROOT / "docs" / "ISSUE-277-SHARED-I18N-PARITY-ARTIFACT.md"
|
||||
ARTIFACT_ID = "issue-277-shared-i18n-parity-report"
|
||||
ARTIFACT_VERSION = "1.0"
|
||||
|
||||
MVP_FRONTEND_UI_KEYS = [
|
||||
"frontend.ui.host.title",
|
||||
"frontend.ui.player.title",
|
||||
"frontend.ui.common.session_code",
|
||||
"frontend.ui.player.nickname",
|
||||
"frontend.ui.player.join",
|
||||
"frontend.ui.host.start_round",
|
||||
"frontend.ui.host.show_question",
|
||||
"frontend.ui.player.lie_label",
|
||||
"frontend.ui.player.submit_lie",
|
||||
"frontend.ui.player.submit_guess",
|
||||
"frontend.ui.host.mix_answers",
|
||||
"frontend.ui.host.calculate_scores",
|
||||
"frontend.ui.host.load_scoreboard",
|
||||
"frontend.ui.host.final_leaderboard",
|
||||
"frontend.ui.player.final_leaderboard",
|
||||
"frontend.ui.common.points_short",
|
||||
]
|
||||
|
||||
MVP_FRONTEND_ERROR_KEYS = [
|
||||
"frontend.errors.session_code_required",
|
||||
"frontend.errors.session_not_found",
|
||||
"frontend.errors.nickname_invalid",
|
||||
"frontend.errors.nickname_taken",
|
||||
"frontend.errors.join_failed",
|
||||
"frontend.errors.start_round_failed",
|
||||
"frontend.errors.unknown",
|
||||
]
|
||||
|
||||
MVP_BACKEND_CODES = [
|
||||
"backend.error_codes.session_code_required",
|
||||
"backend.error_codes.nickname_invalid",
|
||||
"backend.error_codes.session_not_found",
|
||||
"backend.error_codes.session_not_joinable",
|
||||
"backend.error_codes.nickname_taken",
|
||||
"backend.error_codes.category_slug_required",
|
||||
"backend.error_codes.category_not_found",
|
||||
"backend.error_codes.round_start_invalid_phase",
|
||||
"backend.error_codes.round_already_configured",
|
||||
]
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class MappingRow:
|
||||
backend_code: str
|
||||
backend_key: str
|
||||
frontend_key: str
|
||||
locales_ok: bool
|
||||
parity_status: str
|
||||
note: str
|
||||
|
||||
|
||||
def load_catalog() -> dict:
|
||||
return json.loads(CATALOG_PATH.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def get_path(data: dict, dotted: str):
|
||||
node = data
|
||||
for part in dotted.split("."):
|
||||
node = node[part]
|
||||
return node
|
||||
|
||||
|
||||
def translation_state(data: dict, dotted: str) -> tuple[bool, list[str]]:
|
||||
translations = get_path(data, dotted)
|
||||
missing = [locale for locale in ("en", "da") if not isinstance(translations.get(locale), str) or not translations[locale].strip()]
|
||||
return (not missing, missing)
|
||||
|
||||
|
||||
def build_mapping_rows(catalog: dict) -> list[MappingRow]:
|
||||
rows: list[MappingRow] = []
|
||||
mapping = catalog["contract"]["backend_to_frontend_error_keys"]
|
||||
backend_errors = catalog["backend"]["errors"]
|
||||
|
||||
for dotted_code in MVP_BACKEND_CODES:
|
||||
code = dotted_code.removeprefix("backend.error_codes.")
|
||||
backend_key = catalog["backend"]["error_codes"][code]
|
||||
frontend_key = mapping[code]
|
||||
backend_locales_ok, _ = translation_state(catalog, f"backend.errors.{backend_key}")
|
||||
frontend_locales_ok, _ = translation_state(catalog, f"frontend.errors.{frontend_key}")
|
||||
note = "1:1" if code == frontend_key else "many:1 collapse" if frontend_key == "start_round_failed" else "mapped alias"
|
||||
rows.append(
|
||||
MappingRow(
|
||||
backend_code=code,
|
||||
backend_key=backend_key,
|
||||
frontend_key=frontend_key,
|
||||
locales_ok=backend_locales_ok and frontend_locales_ok,
|
||||
parity_status="aligned" if frontend_key in backend_errors or code == frontend_key else "mapped",
|
||||
note=note,
|
||||
)
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def render_report(catalog: dict) -> str:
|
||||
mapping_rows = build_mapping_rows(catalog)
|
||||
frontend_ui_ok = all(translation_state(catalog, key)[0] for key in MVP_FRONTEND_UI_KEYS)
|
||||
frontend_error_ok = all(translation_state(catalog, key)[0] for key in MVP_FRONTEND_ERROR_KEYS)
|
||||
backend_code_ok = all(translation_state(catalog, f"backend.errors.{catalog['backend']['error_codes'][key.removeprefix('backend.error_codes.')]}" )[0] for key in MVP_BACKEND_CODES)
|
||||
mapped_frontend_keys = sorted({row.frontend_key for row in mapping_rows})
|
||||
collapsed_codes = [row.backend_code for row in mapping_rows if row.frontend_key == "start_round_failed"]
|
||||
|
||||
lines: list[str] = []
|
||||
lines.append("# ISSUE-277 Artifact — shared i18n registry parity report (Django ↔ Angular MVP)")
|
||||
lines.append("")
|
||||
lines.append("Issue: **#277** (`[READY][#175][P3] Shared i18n registry artifact: backend/frontend keyspace parity report`)")
|
||||
lines.append("")
|
||||
lines.append("## Artifact metadata")
|
||||
lines.append("")
|
||||
lines.append(f"- `artifact_id`: `{ARTIFACT_ID}`")
|
||||
lines.append(f"- `artifact_version`: `{ARTIFACT_VERSION}`")
|
||||
lines.append(f"- `catalog_source`: `{CATALOG_PATH.relative_to(REPO_ROOT)}`")
|
||||
lines.append(f"- `generator`: `scripts/{Path(__file__).name}`")
|
||||
lines.append("")
|
||||
lines.append("## Naming/version rules (email-manager-inspired strategy)")
|
||||
lines.append("")
|
||||
lines.append("- **Single canonical artifact per issue**: issue-bundne rapporter navngives `docs/ISSUE-<nr>-<slug>-ARTIFACT.md`.")
|
||||
lines.append("- **Stable artifact identity**: `artifact_id` ændres ikke ved tekstlige opdateringer i samme rapporttype; det er den faste reference i review/ops.")
|
||||
lines.append("- **Explicit artifact versioning**: `artifact_version` bumpes, når rapportlogik eller scope ændres, så drift/review kan se forskel på format- vs. dataændringer.")
|
||||
lines.append("- **Shared namespace first**: keys refereres med fulde navnerum (`frontend.ui.*`, `frontend.errors.*`, `backend.error_codes.*`, `backend.errors.*`) i stedet for lokale aliases i artefakter.")
|
||||
lines.append("- **Source-of-truth before consumers**: rapporten afledes fra `shared/i18n/lobby.json`; Django/Angular beskrives som consumers af samme registry og ikke som parallelle kontrakter.")
|
||||
lines.append("")
|
||||
lines.append("## MVP-critical parity summary")
|
||||
lines.append("")
|
||||
lines.append(f"- Frontend UI gameplay keys checked: **{len(MVP_FRONTEND_UI_KEYS)}** → `{'OK' if frontend_ui_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Frontend error keys checked: **{len(MVP_FRONTEND_ERROR_KEYS)}** → `{'OK' if frontend_error_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Backend gameplay/error codes checked: **{len(MVP_BACKEND_CODES)}** → `{'OK' if backend_code_ok else 'DRIFT'}`")
|
||||
lines.append(f"- Distinct frontend error keys reached from backend MVP flow: **{len(mapped_frontend_keys)}** (`{', '.join(mapped_frontend_keys)}`)")
|
||||
lines.append("")
|
||||
lines.append("Status: **Shared locale matrix is aligned (`en`, `da`) and backend→frontend error handling is contract-complete for MVP-critical flow.**")
|
||||
lines.append("")
|
||||
lines.append("## Django ↔ Angular parity matrix (MVP-critical error contract)")
|
||||
lines.append("")
|
||||
lines.append("| Backend code (`backend.error_codes.*`) | Django message key (`backend.errors.*`) | Angular key (`frontend.errors.*`) | Locales `en/da` | Parity note |")
|
||||
lines.append("|---|---|---|---|---|")
|
||||
for row in mapping_rows:
|
||||
lines.append(
|
||||
f"| `{row.backend_code}` | `{row.backend_key}` | `{row.frontend_key}` | `{'OK' if row.locales_ok else 'DRIFT'}` | {row.note} |"
|
||||
)
|
||||
lines.append("")
|
||||
lines.append("## Scope notes")
|
||||
lines.append("")
|
||||
lines.append("- **Django** consumes backend codes/messages directly from `shared/i18n/lobby.json` via `lobby/i18n.py`.")
|
||||
lines.append("- **Angular** consumes the same registry via `frontend/shared/i18n/lobby-loader.ts` and runtime helpers in `frontend/angular/src/app/lobby-i18n.ts`.")
|
||||
lines.append("- **Parity in MVP** is therefore strongest on the shared error contract and locale matrix; gameplay UI labels are frontend-owned but still live in the same registry.")
|
||||
lines.append("")
|
||||
lines.append("## Verified MVP gameplay UI keyspace present in the shared registry")
|
||||
lines.append("")
|
||||
for key in MVP_FRONTEND_UI_KEYS:
|
||||
lines.append(f"- `{key}`")
|
||||
lines.append("")
|
||||
lines.append("## Concrete deviations / follow-up items")
|
||||
lines.append("")
|
||||
lines.append(f"1. **Error granularity collapse remains intentional**: backend codes `{', '.join(collapsed_codes)}` all map to `frontend.errors.start_round_failed`. Follow-up only if product wants case-specific Angular copy instead of one shared host failure message.")
|
||||
lines.append("2. **Frontend-only fallback copy is not mirrored in Django**: `frontend.errors.unknown` and `frontend.errors.session_fetch_failed` are Angular-side resilience keys, not backend contract keys. Follow-up if API responses should expose stable backend equivalents for these states.")
|
||||
lines.append("3. **Gameplay UI labels are registry-shared but not backend-rendered**: `frontend.ui.host.*`, `frontend.ui.player.*`, and `frontend.ui.common.*` are available in the shared artifact, but Django currently consumes only the backend error slice. Follow-up only if server-rendered views must guarantee the same UI label surface as Angular.")
|
||||
lines.append("")
|
||||
lines.append("## Re-run")
|
||||
lines.append("")
|
||||
lines.append("```bash")
|
||||
lines.append("python3 scripts/check_i18n_drift.py")
|
||||
lines.append("python3 scripts/report_i18n_parity.py")
|
||||
lines.append("python3 scripts/check_i18n_parity_artifact.py")
|
||||
lines.append("```")
|
||||
lines.append("")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
catalog = load_catalog()
|
||||
OUTPUT_PATH.write_text(render_report(catalog), encoding="utf-8")
|
||||
print(OUTPUT_PATH.relative_to(REPO_ROOT))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
212
shared/i18n/artifacts/lobby-mvp-keyspace-parity-report.v1.json
Normal file
212
shared/i18n/artifacts/lobby-mvp-keyspace-parity-report.v1.json
Normal file
@@ -0,0 +1,212 @@
|
||||
{
|
||||
"artifact_name": "shared.i18n.lobby.mvp_keyspace_parity_report",
|
||||
"artifact_version": "v1",
|
||||
"naming_version_rule": "Keep a stable artifact_name and append only explicit schema-major suffixes to the filename/version (v1, v2, ...). Update artifact_version only when the report shape changes; refresh content in-place for catalog/keyspace changes.",
|
||||
"source_of_truth": {
|
||||
"catalog": "shared/i18n/lobby.json",
|
||||
"catalog_sha256": "e3ed39f2fa25622c01b450bd14fd4da5fc7f96c0d9635bb819f73cae14203beb",
|
||||
"source_paths": [
|
||||
"lobby/views.py",
|
||||
"frontend/src/spa/vertical-slice.ts",
|
||||
"frontend/angular/src/app/lobby-i18n.ts",
|
||||
"frontend/angular/src/app/features/host/host-shell.component.ts",
|
||||
"frontend/angular/src/app/features/player/player-shell.component.ts"
|
||||
]
|
||||
},
|
||||
"scope": {
|
||||
"issue": 277,
|
||||
"related_epic": 175,
|
||||
"mvp_locales": [
|
||||
"en",
|
||||
"da"
|
||||
],
|
||||
"definition": "MVP-critical keys are the Django error codes emitted by lobby/views.py plus the Angular fallback/UI keys consumed by the host/player MVP shells."
|
||||
},
|
||||
"parity": {
|
||||
"status": "pass",
|
||||
"django_backend_error_codes_used_by_mvp": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
],
|
||||
"angular_frontend_error_fallback_keys_used_by_mvp": [
|
||||
"join_failed",
|
||||
"session_code_required",
|
||||
"session_fetch_failed",
|
||||
"start_round_failed"
|
||||
],
|
||||
"angular_ui_keys_used_by_mvp": [
|
||||
"common.back_to_join",
|
||||
"common.points_short",
|
||||
"common.prompt",
|
||||
"common.refresh",
|
||||
"common.retry",
|
||||
"common.round",
|
||||
"common.round_question_id",
|
||||
"common.session_code",
|
||||
"common.status",
|
||||
"common.unknown_error",
|
||||
"host.audio_locale_hint",
|
||||
"host.calculate_scores",
|
||||
"host.category",
|
||||
"host.final_leaderboard",
|
||||
"host.finish_game",
|
||||
"host.finish_game_failed",
|
||||
"host.load_scoreboard",
|
||||
"host.mix_answers",
|
||||
"host.next_round_failed",
|
||||
"host.retry_finish",
|
||||
"host.retry_next_round",
|
||||
"host.retry_scoreboard",
|
||||
"host.scoreboard_failed",
|
||||
"host.session_code_required",
|
||||
"host.session_refresh_failed",
|
||||
"host.show_question",
|
||||
"host.start_next_round",
|
||||
"host.start_round",
|
||||
"host.title",
|
||||
"host.winner",
|
||||
"player.audio_policy_notice",
|
||||
"player.final_leaderboard",
|
||||
"player.guess_submit_failed",
|
||||
"player.join",
|
||||
"player.join_failed",
|
||||
"player.lie_label",
|
||||
"player.lie_submit_failed",
|
||||
"player.loading_join",
|
||||
"player.loading_refresh",
|
||||
"player.loading_submit_guess",
|
||||
"player.loading_submit_lie",
|
||||
"player.nickname",
|
||||
"player.offline_text",
|
||||
"player.reconnecting_text",
|
||||
"player.retry_guess_submit",
|
||||
"player.retry_lie_submit",
|
||||
"player.retry_now",
|
||||
"player.session_refresh_failed",
|
||||
"player.submit_guess",
|
||||
"player.submit_lie",
|
||||
"player.title"
|
||||
],
|
||||
"angular_ui_catalog_paths": [
|
||||
"common.back_to_join",
|
||||
"common.points_short",
|
||||
"common.prompt",
|
||||
"common.refresh",
|
||||
"common.retry",
|
||||
"common.round",
|
||||
"common.round_question_id",
|
||||
"common.session_code",
|
||||
"common.status",
|
||||
"common.unknown_error",
|
||||
"host.audio_locale_hint",
|
||||
"host.calculate_scores",
|
||||
"host.category",
|
||||
"host.final_leaderboard",
|
||||
"host.finish_game",
|
||||
"host.finish_game_failed",
|
||||
"host.load_scoreboard",
|
||||
"host.mix_answers",
|
||||
"host.next_round_failed",
|
||||
"host.retry_finish",
|
||||
"host.retry_next_round",
|
||||
"host.retry_scoreboard",
|
||||
"host.scoreboard_failed",
|
||||
"host.session_code_required",
|
||||
"host.session_refresh_failed",
|
||||
"host.show_question",
|
||||
"host.start_next_round",
|
||||
"host.start_round",
|
||||
"host.title",
|
||||
"host.winner",
|
||||
"player.audio_policy_notice",
|
||||
"player.final_leaderboard",
|
||||
"player.guess_submit_failed",
|
||||
"player.join",
|
||||
"player.join_failed",
|
||||
"player.lie_label",
|
||||
"player.lie_submit_failed",
|
||||
"player.loading_join",
|
||||
"player.loading_refresh",
|
||||
"player.loading_submit_guess",
|
||||
"player.loading_submit_lie",
|
||||
"player.nickname",
|
||||
"player.offline_text",
|
||||
"player.reconnecting_text",
|
||||
"player.retry_guess_submit",
|
||||
"player.retry_lie_submit",
|
||||
"player.retry_now",
|
||||
"player.session_refresh_failed",
|
||||
"player.submit_guess",
|
||||
"player.submit_lie",
|
||||
"player.title"
|
||||
],
|
||||
"backend_codes_mapped_to_frontend_error_keys": {
|
||||
"category_has_no_questions": "start_round_failed",
|
||||
"category_not_found": "start_round_failed",
|
||||
"category_slug_required": "start_round_failed",
|
||||
"host_only_mix_answers": "start_round_failed",
|
||||
"host_only_show_question": "start_round_failed",
|
||||
"host_only_start_round": "start_round_failed",
|
||||
"mix_answers_invalid_phase": "start_round_failed",
|
||||
"nickname_invalid": "nickname_invalid",
|
||||
"nickname_taken": "nickname_taken",
|
||||
"no_available_questions": "start_round_failed",
|
||||
"not_enough_answers_to_mix": "start_round_failed",
|
||||
"question_already_shown": "start_round_failed",
|
||||
"round_already_configured": "start_round_failed",
|
||||
"round_config_missing": "start_round_failed",
|
||||
"round_question_not_found": "start_round_failed",
|
||||
"round_start_invalid_phase": "start_round_failed",
|
||||
"session_code_required": "session_code_required",
|
||||
"session_not_found": "session_not_found",
|
||||
"session_not_joinable": "join_failed",
|
||||
"show_question_invalid_phase": "start_round_failed"
|
||||
},
|
||||
"unique_frontend_error_keys_reached_from_django": [
|
||||
"join_failed",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"start_round_failed"
|
||||
],
|
||||
"blocking_issues": {
|
||||
"missing_backend_codes": [],
|
||||
"missing_backend_translations": [],
|
||||
"missing_contract_mappings": [],
|
||||
"missing_frontend_error_keys": [],
|
||||
"missing_frontend_runtime_fallbacks": [],
|
||||
"missing_angular_catalog_paths": []
|
||||
},
|
||||
"follow_ups": [
|
||||
{
|
||||
"priority": "need-to-have",
|
||||
"item": "Either add missing backend/error_codes + backend/errors entries for dead contract aliases or remove them from contract.backend_to_frontend_error_keys.",
|
||||
"evidence": "host_only_action"
|
||||
},
|
||||
{
|
||||
"priority": "nice-to-have",
|
||||
"item": "Decide whether grouped backend codes should keep collapsing into one Angular fallback key or be split into more specific frontend error copy as UX matures.",
|
||||
"evidence": "start_round_failed <= category_has_no_questions, category_not_found, category_slug_required, host_only_mix_answers, host_only_show_question, host_only_start_round, mix_answers_invalid_phase, no_available_questions, not_enough_answers_to_mix, question_already_shown, round_already_configured, round_config_missing, round_question_not_found, round_start_invalid_phase, show_question_invalid_phase"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
60
shared/i18n/key-manifest.json
Normal file
60
shared/i18n/key-manifest.json
Normal file
@@ -0,0 +1,60 @@
|
||||
{
|
||||
"locales": ["en", "da"],
|
||||
"frontend_error_keys": [
|
||||
"join_failed",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"session_code_required",
|
||||
"session_fetch_failed",
|
||||
"session_not_found",
|
||||
"start_round_failed",
|
||||
"unknown"
|
||||
],
|
||||
"backend_error_codes": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
],
|
||||
"allowed_contract_only_backend_codes": [
|
||||
"host_only_action"
|
||||
],
|
||||
"backend_error_keys": [
|
||||
"category_has_no_questions",
|
||||
"category_not_found",
|
||||
"category_slug_required",
|
||||
"host_only_mix_answers",
|
||||
"host_only_show_question",
|
||||
"host_only_start_round",
|
||||
"mix_answers_invalid_phase",
|
||||
"nickname_invalid",
|
||||
"nickname_taken",
|
||||
"no_available_questions",
|
||||
"not_enough_answers_to_mix",
|
||||
"question_already_shown",
|
||||
"round_already_configured",
|
||||
"round_config_missing",
|
||||
"round_question_not_found",
|
||||
"round_start_invalid_phase",
|
||||
"session_code_required",
|
||||
"session_not_found",
|
||||
"session_not_joinable",
|
||||
"show_question_invalid_phase"
|
||||
]
|
||||
}
|
||||
@@ -1,14 +1,278 @@
|
||||
{
|
||||
"locales": {
|
||||
"default": "en",
|
||||
"supported": [
|
||||
"en",
|
||||
"da"
|
||||
]
|
||||
},
|
||||
"frontend": {
|
||||
"errors": {
|
||||
"session_code_required": "Session code is required.",
|
||||
"session_fetch_failed": "Could not load lobby status.",
|
||||
"join_failed": "Join failed. Check code or nickname and try again.",
|
||||
"start_round_failed": "Could not start round. Refresh the lobby and try again.",
|
||||
"session_not_found": "Session code is invalid or the session no longer exists.",
|
||||
"nickname_invalid": "Nickname must be between 2 and 40 characters.",
|
||||
"nickname_taken": "Nickname is already taken.",
|
||||
"unknown": "Action failed. Refresh status and try again."
|
||||
"session_code_required": {
|
||||
"en": "Session code is required.",
|
||||
"da": "Sessionskoden er påkrævet."
|
||||
},
|
||||
"session_fetch_failed": {
|
||||
"en": "Could not load lobby status.",
|
||||
"da": "Kunne ikke indlæse lobby-status."
|
||||
},
|
||||
"join_failed": {
|
||||
"en": "Join failed. Check code or nickname and try again.",
|
||||
"da": "Kunne ikke joine. Tjek kode eller kaldenavn og prøv igen."
|
||||
},
|
||||
"start_round_failed": {
|
||||
"en": "Could not start round. Refresh the lobby and try again.",
|
||||
"da": "Kunne ikke starte runden. Opdater lobbyen og prøv igen."
|
||||
},
|
||||
"session_not_found": {
|
||||
"en": "Session code is invalid or the session no longer exists.",
|
||||
"da": "Sessionskoden er ugyldig, eller sessionen findes ikke længere."
|
||||
},
|
||||
"nickname_invalid": {
|
||||
"en": "Nickname must be between 2 and 40 characters.",
|
||||
"da": "Kaldenavn skal være mellem 2 og 40 tegn."
|
||||
},
|
||||
"nickname_taken": {
|
||||
"en": "Nickname is already taken.",
|
||||
"da": "Kaldenavnet er allerede taget."
|
||||
},
|
||||
"unknown": {
|
||||
"en": "Action failed. Refresh status and try again.",
|
||||
"da": "Handlingen fejlede. Opdater status og prøv igen."
|
||||
}
|
||||
},
|
||||
"ui": {
|
||||
"common": {
|
||||
"refresh": {
|
||||
"en": "Refresh",
|
||||
"da": "Opdatér"
|
||||
},
|
||||
"retry": {
|
||||
"en": "Retry",
|
||||
"da": "Prøv igen"
|
||||
},
|
||||
"back_to_join": {
|
||||
"en": "Back to join",
|
||||
"da": "Tilbage til join"
|
||||
},
|
||||
"session_code": {
|
||||
"en": "Session code",
|
||||
"da": "Sessionskode"
|
||||
},
|
||||
"status": {
|
||||
"en": "Status",
|
||||
"da": "Status"
|
||||
},
|
||||
"prompt": {
|
||||
"en": "Prompt",
|
||||
"da": "Spørgsmål"
|
||||
},
|
||||
"round_question_id": {
|
||||
"en": "Round question id",
|
||||
"da": "Rundespørgsmål-id"
|
||||
},
|
||||
"round": {
|
||||
"en": "round",
|
||||
"da": "runde"
|
||||
},
|
||||
"points_short": {
|
||||
"en": "pts",
|
||||
"da": "point"
|
||||
},
|
||||
"unknown_error": {
|
||||
"en": "Unknown error",
|
||||
"da": "Ukendt fejl"
|
||||
}
|
||||
},
|
||||
"app": {
|
||||
"title": {
|
||||
"en": "WPP Angular Shell",
|
||||
"da": "WPP Angular Shell"
|
||||
},
|
||||
"host_nav": {
|
||||
"en": "Host",
|
||||
"da": "Vært"
|
||||
},
|
||||
"player_nav": {
|
||||
"en": "Player",
|
||||
"da": "Spiller"
|
||||
},
|
||||
"language_label": {
|
||||
"en": "Language",
|
||||
"da": "Sprog"
|
||||
}
|
||||
},
|
||||
"host": {
|
||||
"title": {
|
||||
"en": "Host gameplay flow",
|
||||
"da": "Vært gameplay-flow"
|
||||
},
|
||||
"category": {
|
||||
"en": "Category",
|
||||
"da": "Kategori"
|
||||
},
|
||||
"start_round": {
|
||||
"en": "Start round",
|
||||
"da": "Start runde"
|
||||
},
|
||||
"show_question": {
|
||||
"en": "Show question",
|
||||
"da": "Vis spørgsmål"
|
||||
},
|
||||
"mix_answers": {
|
||||
"en": "Mix answers → guess",
|
||||
"da": "Bland svar → gæt"
|
||||
},
|
||||
"calculate_scores": {
|
||||
"en": "Calculate scores → reveal",
|
||||
"da": "Udregn score → afslør"
|
||||
},
|
||||
"load_scoreboard": {
|
||||
"en": "Load scoreboard",
|
||||
"da": "Hent scoreboard"
|
||||
},
|
||||
"start_next_round": {
|
||||
"en": "Start next round",
|
||||
"da": "Start næste runde"
|
||||
},
|
||||
"finish_game": {
|
||||
"en": "Finish game",
|
||||
"da": "Afslut spil"
|
||||
},
|
||||
"retry_scoreboard": {
|
||||
"en": "Retry scoreboard",
|
||||
"da": "Prøv scoreboard igen"
|
||||
},
|
||||
"retry_next_round": {
|
||||
"en": "Retry next round",
|
||||
"da": "Prøv næste runde igen"
|
||||
},
|
||||
"retry_finish": {
|
||||
"en": "Retry finish game",
|
||||
"da": "Prøv afslutning igen"
|
||||
},
|
||||
"session_refresh_failed": {
|
||||
"en": "Session refresh failed",
|
||||
"da": "Kunne ikke opdatere session"
|
||||
},
|
||||
"scoreboard_failed": {
|
||||
"en": "Scoreboard failed",
|
||||
"da": "Scoreboard fejlede"
|
||||
},
|
||||
"next_round_failed": {
|
||||
"en": "Next round failed",
|
||||
"da": "Næste runde fejlede"
|
||||
},
|
||||
"finish_game_failed": {
|
||||
"en": "Finish game failed",
|
||||
"da": "Afslutning fejlede"
|
||||
},
|
||||
"session_code_required": {
|
||||
"en": "Session code is required",
|
||||
"da": "Sessionskode er påkrævet"
|
||||
},
|
||||
"final_leaderboard": {
|
||||
"en": "Final leaderboard",
|
||||
"da": "Finale leaderboard"
|
||||
},
|
||||
"winner": {
|
||||
"en": "Winner",
|
||||
"da": "Vinder"
|
||||
},
|
||||
"audio_locale_hint": {
|
||||
"en": "Host locale for audio references",
|
||||
"da": "Værtens locale for lydreferencer"
|
||||
}
|
||||
},
|
||||
"player": {
|
||||
"title": {
|
||||
"en": "Player gameplay flow",
|
||||
"da": "Spiller gameplay-flow"
|
||||
},
|
||||
"nickname": {
|
||||
"en": "Nickname",
|
||||
"da": "Kaldenavn"
|
||||
},
|
||||
"join": {
|
||||
"en": "Join",
|
||||
"da": "Join"
|
||||
},
|
||||
"lie_label": {
|
||||
"en": "Lie",
|
||||
"da": "Løgn"
|
||||
},
|
||||
"submit_lie": {
|
||||
"en": "Submit lie",
|
||||
"da": "Send løgn"
|
||||
},
|
||||
"retry_lie_submit": {
|
||||
"en": "Retry lie submit",
|
||||
"da": "Prøv løgn igen"
|
||||
},
|
||||
"submit_guess": {
|
||||
"en": "Submit guess",
|
||||
"da": "Send gæt"
|
||||
},
|
||||
"retry_guess_submit": {
|
||||
"en": "Retry guess submit",
|
||||
"da": "Prøv gæt igen"
|
||||
},
|
||||
"final_leaderboard": {
|
||||
"en": "Final leaderboard",
|
||||
"da": "Finale leaderboard"
|
||||
},
|
||||
"reconnecting_text": {
|
||||
"en": "Reconnecting… trying to refresh session state.",
|
||||
"da": "Forbinder igen… prøver at opdatere session."
|
||||
},
|
||||
"offline_text": {
|
||||
"en": "You are offline. Reconnect to continue gameplay.",
|
||||
"da": "Du er offline. Forbind igen for at fortsætte."
|
||||
},
|
||||
"retry_now": {
|
||||
"en": "Retry now",
|
||||
"da": "Prøv nu"
|
||||
},
|
||||
"loading_refresh": {
|
||||
"en": "Loading latest session state…",
|
||||
"da": "Indlæser seneste session-status…"
|
||||
},
|
||||
"loading_join": {
|
||||
"en": "Joining session… restoring your player state.",
|
||||
"da": "Joiner session… gendanner spillerstatus."
|
||||
},
|
||||
"loading_submit_lie": {
|
||||
"en": "Submitting lie… waiting for guess phase.",
|
||||
"da": "Sender løgn… venter på gættefase."
|
||||
},
|
||||
"loading_submit_guess": {
|
||||
"en": "Submitting guess… waiting for reveal.",
|
||||
"da": "Sender gæt… venter på afsløring."
|
||||
},
|
||||
"session_refresh_failed": {
|
||||
"en": "Session refresh failed",
|
||||
"da": "Kunne ikke opdatere session"
|
||||
},
|
||||
"join_failed": {
|
||||
"en": "Join failed",
|
||||
"da": "Join fejlede"
|
||||
},
|
||||
"lie_submit_failed": {
|
||||
"en": "Lie submit failed",
|
||||
"da": "Løgn-fejl"
|
||||
},
|
||||
"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."
|
||||
}
|
||||
}
|
||||
},
|
||||
"capabilities": {
|
||||
"client_has_no_audio_output": true
|
||||
}
|
||||
},
|
||||
"backend": {
|
||||
@@ -21,7 +285,138 @@
|
||||
"category_slug_required": "category_slug_required",
|
||||
"category_not_found": "category_not_found",
|
||||
"round_start_invalid_phase": "round_start_invalid_phase",
|
||||
"round_already_configured": "round_already_configured"
|
||||
"round_already_configured": "round_already_configured",
|
||||
"category_has_no_questions": "category_has_no_questions",
|
||||
"show_question_invalid_phase": "show_question_invalid_phase",
|
||||
"round_config_missing": "round_config_missing",
|
||||
"question_already_shown": "question_already_shown",
|
||||
"no_available_questions": "no_available_questions",
|
||||
"mix_answers_invalid_phase": "mix_answers_invalid_phase",
|
||||
"round_question_not_found": "round_question_not_found",
|
||||
"not_enough_answers_to_mix": "not_enough_answers_to_mix",
|
||||
"host_only_start_round": "host_only_start_round",
|
||||
"host_only_show_question": "host_only_show_question",
|
||||
"host_only_mix_answers": "host_only_mix_answers"
|
||||
},
|
||||
"errors": {
|
||||
"session_code_required": {
|
||||
"en": "Session code is required",
|
||||
"da": "Sessionskode er påkrævet"
|
||||
},
|
||||
"nickname_invalid": {
|
||||
"en": "Nickname must be between 2 and 40 characters",
|
||||
"da": "Kaldenavn skal være mellem 2 og 40 tegn"
|
||||
},
|
||||
"session_not_found": {
|
||||
"en": "Session not found",
|
||||
"da": "Session blev ikke fundet"
|
||||
},
|
||||
"session_not_joinable": {
|
||||
"en": "Session is not joinable",
|
||||
"da": "Sessionen kan ikke joine nu"
|
||||
},
|
||||
"nickname_taken": {
|
||||
"en": "Nickname already taken",
|
||||
"da": "Kaldenavnet er allerede taget"
|
||||
},
|
||||
"category_slug_required": {
|
||||
"en": "category_slug is required",
|
||||
"da": "category_slug er påkrævet"
|
||||
},
|
||||
"category_not_found": {
|
||||
"en": "Category not found",
|
||||
"da": "Kategori blev ikke fundet"
|
||||
},
|
||||
"round_start_invalid_phase": {
|
||||
"en": "Round can only be started from lobby",
|
||||
"da": "Runden kan kun startes fra lobbyen"
|
||||
},
|
||||
"round_already_configured": {
|
||||
"en": "Round already configured",
|
||||
"da": "Runden er allerede konfigureret"
|
||||
},
|
||||
"category_has_no_questions": {
|
||||
"en": "Category has no active questions",
|
||||
"da": "Kategorien har ingen aktive spørgsmål"
|
||||
},
|
||||
"show_question_invalid_phase": {
|
||||
"en": "Question can only be shown in lie phase",
|
||||
"da": "Spørgsmålet kan kun vises i løgnefasen"
|
||||
},
|
||||
"round_config_missing": {
|
||||
"en": "Round config missing",
|
||||
"da": "Rundekonfiguration mangler"
|
||||
},
|
||||
"question_already_shown": {
|
||||
"en": "Question already shown for this round",
|
||||
"da": "Spørgsmålet er allerede vist for denne runde"
|
||||
},
|
||||
"no_available_questions": {
|
||||
"en": "No available questions in category",
|
||||
"da": "Ingen tilgængelige spørgsmål i kategorien"
|
||||
},
|
||||
"mix_answers_invalid_phase": {
|
||||
"en": "Answers can only be mixed in lie or guess phase",
|
||||
"da": "Svar kan kun blandes i løgne- eller gættefasen"
|
||||
},
|
||||
"round_question_not_found": {
|
||||
"en": "Round question not found",
|
||||
"da": "Rundespørgsmål blev ikke fundet"
|
||||
},
|
||||
"not_enough_answers_to_mix": {
|
||||
"en": "Not enough answers to mix",
|
||||
"da": "Ikke nok svar at blande"
|
||||
},
|
||||
"host_only_start_round": {
|
||||
"en": "Only host can start round",
|
||||
"da": "Kun værten kan starte runden"
|
||||
},
|
||||
"host_only_show_question": {
|
||||
"en": "Only host can show question",
|
||||
"da": "Kun værten kan vise spørgsmålet"
|
||||
},
|
||||
"host_only_mix_answers": {
|
||||
"en": "Only host can mix answers",
|
||||
"da": "Kun værten kan blande svar"
|
||||
}
|
||||
}
|
||||
},
|
||||
"contract": {
|
||||
"ownership": {
|
||||
"artifact": "shared/i18n/lobby.json",
|
||||
"backend": "lobby/* reads backend/errors + backend/error_codes",
|
||||
"frontend": "frontend/* reads frontend/errors + frontend/ui + contract/backend_to_frontend_error_keys"
|
||||
},
|
||||
"locale": {
|
||||
"default": "en",
|
||||
"supported": [
|
||||
"en",
|
||||
"da"
|
||||
],
|
||||
"fallback": "Use default locale when requested locale is unsupported or key translation is missing."
|
||||
},
|
||||
"backend_to_frontend_error_keys": {
|
||||
"session_code_required": "session_code_required",
|
||||
"nickname_invalid": "nickname_invalid",
|
||||
"session_not_found": "session_not_found",
|
||||
"session_not_joinable": "join_failed",
|
||||
"nickname_taken": "nickname_taken",
|
||||
"category_slug_required": "start_round_failed",
|
||||
"category_not_found": "start_round_failed",
|
||||
"round_start_invalid_phase": "start_round_failed",
|
||||
"round_already_configured": "start_round_failed",
|
||||
"host_only_start_round": "start_round_failed",
|
||||
"host_only_show_question": "start_round_failed",
|
||||
"host_only_mix_answers": "start_round_failed",
|
||||
"host_only_action": "start_round_failed",
|
||||
"category_has_no_questions": "start_round_failed",
|
||||
"show_question_invalid_phase": "start_round_failed",
|
||||
"round_config_missing": "start_round_failed",
|
||||
"question_already_shown": "start_round_failed",
|
||||
"no_available_questions": "start_round_failed",
|
||||
"mix_answers_invalid_phase": "start_round_failed",
|
||||
"round_question_not_found": "start_round_failed",
|
||||
"not_enough_answers_to_mix": "start_round_failed"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user