From a0277fd8be17a923d992cf92fa8e530cd2c462aa Mon Sep 17 00:00:00 2001 From: DEV-bot Date: Fri, 13 Mar 2026 16:11:06 +0000 Subject: [PATCH] fix(gameplay): add explicit scoreboard phase (#288) --- .../src/app/api-contract-smoke.spec.ts | 26 +++++----- frontend/tests/angular-api-client.test.ts | 2 +- .../0005_alter_gamesession_status.py | 18 +++++++ fupogfakta/models.py | 1 + lobby/templates/lobby/host_screen.html | 4 +- lobby/templates/lobby/player_screen.html | 2 +- lobby/tests.py | 48 ++++++++++++++++--- lobby/views.py | 27 +++++++---- 8 files changed, 94 insertions(+), 34 deletions(-) create mode 100644 fupogfakta/migrations/0005_alter_gamesession_status.py diff --git a/frontend/angular/src/app/api-contract-smoke.spec.ts b/frontend/angular/src/app/api-contract-smoke.spec.ts index 7be1d6a..429e28c 100644 --- a/frontend/angular/src/app/api-contract-smoke.spec.ts +++ b/frontend/angular/src/app/api-contract-smoke.spec.ts @@ -31,17 +31,17 @@ describe('SPA Angular API contract smoke (host/player foundation)', () => { }, 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 + 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: true, - can_submit_guess: true, + can_submit_lie: false, + can_submit_guess: false, can_view_final_result: false } } @@ -50,7 +50,7 @@ describe('SPA Angular API contract smoke (host/player foundation)', () => { if (url === '/lobby/sessions/ABCD12/scoreboard') { return { - session: { code: 'ABCD12', status: 'reveal', current_round: 1 }, + session: { code: 'ABCD12', status: 'scoreboard', current_round: 1 }, leaderboard: [ { id: 9, nickname: 'Maja', score: 200 }, { id: 10, nickname: 'Bo', score: 150 } @@ -104,7 +104,7 @@ describe('SPA Angular API contract smoke (host/player foundation)', () => { if (url === '/lobby/sessions/ABCD12/questions/77/scores/calculate') { expect(body).toEqual({}); return { - session: { code: 'ABCD12', status: 'reveal', current_round: 1 }, + session: { code: 'ABCD12', status: 'scoreboard', current_round: 1 }, round_question: { id: 77, round_number: 1 }, events_created: 2, leaderboard: [ @@ -116,7 +116,7 @@ describe('SPA Angular API contract smoke (host/player foundation)', () => { if (url === '/lobby/sessions/ABCD12/rounds/next') { expect(body).toEqual({}); - return { session: { code: 'ABCD12', status: 'lie', current_round: 2 } } as T; + return { session: { code: 'ABCD12', status: 'lobby', current_round: 2 } } as T; } if (url === '/lobby/sessions/ABCD12/finish') { @@ -170,8 +170,8 @@ describe('SPA Angular API contract smoke (host/player foundation)', () => { 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(session.data.phase_view_model.host.can_start_next_round).toBe(false); + expect(session.data.phase_view_model.player.can_submit_guess).toBe(false); } expect((await client.joinSession({ code: ' abcd12 ', nickname: ' Maja ' })).ok).toBe(true); diff --git a/frontend/tests/angular-api-client.test.ts b/frontend/tests/angular-api-client.test.ts index 82c9336..13a574b 100644 --- a/frontend/tests/angular-api-client.test.ts +++ b/frontend/tests/angular-api-client.test.ts @@ -210,7 +210,7 @@ describe('createAngularApiClient', () => { const get = vi.fn(async (url: string) => { if (url === '/lobby/sessions/ABCD12/scoreboard') { return { - session: { code: 'ABCD12', status: 'reveal', current_round: 1 }, + session: { code: 'ABCD12', status: 'scoreboard', current_round: 1 }, leaderboard: [ { id: 2, nickname: 'Maja', score: 11 }, { id: 3, nickname: 'Bo', score: 7 } diff --git a/fupogfakta/migrations/0005_alter_gamesession_status.py b/fupogfakta/migrations/0005_alter_gamesession_status.py new file mode 100644 index 0000000..202f7be --- /dev/null +++ b/fupogfakta/migrations/0005_alter_gamesession_status.py @@ -0,0 +1,18 @@ +# Generated by Django 6.0.2 on 2026-03-13 16:05 + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('fupogfakta', '0004_player_session_token'), + ] + + operations = [ + migrations.AlterField( + model_name='gamesession', + name='status', + field=models.CharField(choices=[('lobby', 'Lobby'), ('lie', 'Løgnfase'), ('guess', 'Gættefase'), ('reveal', 'Reveal'), ('scoreboard', 'Scoreboard'), ('finished', 'Afsluttet')], default='lobby', max_length=16), + ), + ] diff --git a/fupogfakta/models.py b/fupogfakta/models.py index 6a5a39d..8670349 100644 --- a/fupogfakta/models.py +++ b/fupogfakta/models.py @@ -42,6 +42,7 @@ class GameSession(models.Model): LIE = "lie", "Løgnfase" GUESS = "guess", "Gættefase" REVEAL = "reveal", "Reveal" + SCOREBOARD = "scoreboard", "Scoreboard" FINISHED = "finished", "Afsluttet" host = models.ForeignKey(User, on_delete=models.PROTECT, related_name="hosted_sessions") diff --git a/lobby/templates/lobby/host_screen.html b/lobby/templates/lobby/host_screen.html index 49f9d01..09d3187 100644 --- a/lobby/templates/lobby/host_screen.html +++ b/lobby/templates/lobby/host_screen.html @@ -85,7 +85,7 @@ function code(){return document.getElementById("code").value.trim().toUpperCase( function rq(){return document.getElementById("roundQuestionId").value.trim();} function saveHostContext(){try{localStorage.setItem("wppHostContext",JSON.stringify({code:code(),round_question_id:rq(),session_status:currentSessionStatus||"",auto_refresh:autoRefreshEnabled}));}catch(_e){}} function restoreHostContext(){try{var raw=localStorage.getItem("wppHostContext");if(!raw){return false;}var ctx=JSON.parse(raw);if(ctx.code){document.getElementById("code").value=(ctx.code||"").toUpperCase();}if(ctx.round_question_id){document.getElementById("roundQuestionId").value=ctx.round_question_id;}if(ctx.session_status){currentSessionStatus=ctx.session_status;}autoRefreshEnabled=!!ctx.auto_refresh;updateAutoRefreshUi();return !!ctx.code;}catch(_e){return false;}} -function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Afsluttet";}return"Ukendt";} +function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Afsluttet";}return"Ukendt";} function hostShellRouteFromPath(){var marker="/lobby/ui/host";var path=(window.location.pathname||"").toLowerCase();var idx=path.indexOf(marker);if(idx===-1){return"";}var remainder=path.slice(idx+marker.length).replace(/^\/+|\/+$/g,"");if(!remainder){return"";}var route=remainder.split("/")[0];return HOST_SHELL_ROUTES[route]?route:"";} function expectedHostShellRoute(){return HOST_SHELL_ROUTES[currentSessionStatus]||"";} function syncHostShellRoute(){var currentRoute=hostShellRouteFromPath();var expectedRoute=expectedHostShellRoute();if(!currentRoute||!expectedRoute){hostShellRouteHint="";return;}if(currentRoute===expectedRoute){hostShellRouteHint="";return;}var nextPath="/lobby/ui/host/"+expectedRoute;window.history.replaceState(null,"",nextPath);hostShellRouteHint="Deep-link route guard: omdirigeret fra /"+currentRoute+" til /"+expectedRoute+" for fase "+phaseLabel(currentSessionStatus)+".";} @@ -104,7 +104,7 @@ function updateCreateSessionState(){var btn=document.getElementById("createSessi function updatePhaseStatus(){var el=document.getElementById("phaseStatus");syncHostShellRoute();if(!el){return;}if(!currentSessionStatus){el.textContent="Fase: ukendt (opdatér session-status).";return;}el.textContent="Fase: "+phaseLabel(currentSessionStatus)+" ("+currentSessionStatus+")";} function syncStartRoundGuard(data){var btn=document.getElementById("startRoundBtn");var hint=document.getElementById("startRoundHint");var status=document.getElementById("playerCountStatus");if(!btn||!hint||!status){return;}var count=(data&&data.session&&typeof data.session.players_count==="number")?data.session.players_count:null;var phase=currentSessionStatus||"";if(phase&&phase!=="lobby"){btn.disabled=true;status.textContent=count===null?"Spillere i session: ukendt":"Spillere i session: "+count;hint.textContent="Start runde er kun tilladt i lobby-fasen.";return;}if(count===null){btn.disabled=true;status.textContent="Spillere i session: ukendt";hint.textContent="Opdatér session-status for at validere 3-5 spillere.";return;}status.textContent="Spillere i session: "+count;if(count<3){btn.disabled=true;hint.textContent="Mangler spillere: kræver mindst 3 for at starte runde.";return;}if(count>5){btn.disabled=true;hint.textContent="For mange spillere: maks 5 i MVP før runde-start.";return;}btn.disabled=false;hint.textContent="Klar: spillerantal er indenfor 3-5 til runde-start.";} -function updateHostActionState(){updateCreateSessionState();var hasCode=!!code();var hasRound=!!rq();var phase=currentSessionStatus||"";var showQuestionBtn=document.getElementById("showQuestionBtn");var mixAnswersBtn=document.getElementById("mixAnswersBtn");var calcScoresBtn=document.getElementById("calcScoresBtn");var showScoreboardBtn=document.getElementById("showScoreboardBtn");var nextRoundBtn=document.getElementById("nextRoundBtn");var finishGameBtn=document.getElementById("finishGameBtn");var roundQuestionInput=document.getElementById("roundQuestionId");var roundQuestionGuardHint=document.getElementById("roundQuestionGuardHint");var categorySelect=document.getElementById("category");var categoryGuardHint=document.getElementById("categoryGuardHint");var hint=document.getElementById("hostActionHint");if(showQuestionBtn){showQuestionBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lie";}if(showScoreboardBtn){showScoreboardBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(nextRoundBtn){nextRoundBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(finishGameBtn){finishGameBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(mixAnswersBtn){mixAnswersBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||(phase!=="lie"&&phase!=="guess");}if(calcScoresBtn){calcScoresBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||phase!=="guess";}var canEditRoundQuestion=!!hasCode&&(phase==="lie"||phase==="guess"||phase==="reveal");if(roundQuestionInput){roundQuestionInput.disabled=hostActionInFlight||sessionDetailInFlight||!canEditRoundQuestion;}if(roundQuestionGuardHint){if(hostActionInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens en handling kører.";}else if(sessionDetailInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens session-opdatering kører.";}else if(!hasCode){roundQuestionGuardHint.textContent="Angiv sessionkode for at redigere round question-id.";}else if(!phase){roundQuestionGuardHint.textContent="Opdatér session-status for round question-id.";}else if(canEditRoundQuestion){roundQuestionGuardHint.textContent="Round question-id kan redigeres i fase: "+phaseLabel(phase)+".";}else{roundQuestionGuardHint.textContent="Round question-id er låst i fase: "+phaseLabel(phase)+".";}}if(categorySelect){categorySelect.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lobby";}if(categoryGuardHint){if(hostActionInFlight){categoryGuardHint.textContent="Kategori er midlertidigt låst mens en handling kører.";}else if(sessionDetailInFlight){categoryGuardHint.textContent="Kategori er låst mens session-opdatering kører.";}else if(!hasCode){categoryGuardHint.textContent="Angiv sessionkode for at låse kategori til lobby-fasen.";}else if(phase==="lobby"){categoryGuardHint.textContent="Kategori kan vælges i lobby-fasen.";}else if(!phase){categoryGuardHint.textContent="Opdatér session-status for at validere kategori-lås.";}else{categoryGuardHint.textContent="Kategori er låst udenfor lobby-fasen.";}}if(!hint){return;}if(hostActionInFlight){hint.textContent="Handling kører… afvent svar før næste klik.";return;}if(sessionDetailInFlight){hint.textContent="Host-actions er låst mens session-opdatering kører.";return;}if(!hasCode){hint.textContent="Angiv sessionkode for at aktivere host-actions.";return;}if(!phase){hint.textContent="Opdatér session-status for fasebaserede host-actions.";return;}if(phase==="finished"){hint.textContent="Spillet er afsluttet: gameplay-actions er låst.";return;}if((phase==="lie"||phase==="guess")&&!hasRound){hint.textContent="Round question id mangler: mix/beregn score er låst.";return;}if(hostShellRouteHint){hint.textContent=hostShellRouteHint;return;}hint.textContent="Host-actions er klar for fase: "+phaseLabel(phase)+".";} +function updateHostActionState(){updateCreateSessionState();var hasCode=!!code();var hasRound=!!rq();var phase=currentSessionStatus||"";var showQuestionBtn=document.getElementById("showQuestionBtn");var mixAnswersBtn=document.getElementById("mixAnswersBtn");var calcScoresBtn=document.getElementById("calcScoresBtn");var showScoreboardBtn=document.getElementById("showScoreboardBtn");var nextRoundBtn=document.getElementById("nextRoundBtn");var finishGameBtn=document.getElementById("finishGameBtn");var roundQuestionInput=document.getElementById("roundQuestionId");var roundQuestionGuardHint=document.getElementById("roundQuestionGuardHint");var categorySelect=document.getElementById("category");var categoryGuardHint=document.getElementById("categoryGuardHint");var hint=document.getElementById("hostActionHint");if(showQuestionBtn){showQuestionBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lie";}if(showScoreboardBtn){showScoreboardBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="reveal";}if(nextRoundBtn){nextRoundBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="scoreboard";}if(finishGameBtn){finishGameBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="scoreboard";}if(mixAnswersBtn){mixAnswersBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||(phase!=="lie"&&phase!=="guess");}if(calcScoresBtn){calcScoresBtn.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||!hasRound||phase!=="guess";}var canEditRoundQuestion=!!hasCode&&(phase==="lie"||phase==="guess"||phase==="reveal");if(roundQuestionInput){roundQuestionInput.disabled=hostActionInFlight||sessionDetailInFlight||!canEditRoundQuestion;}if(roundQuestionGuardHint){if(hostActionInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens en handling kører.";}else if(sessionDetailInFlight){roundQuestionGuardHint.textContent="Round question-id er låst mens session-opdatering kører.";}else if(!hasCode){roundQuestionGuardHint.textContent="Angiv sessionkode for at redigere round question-id.";}else if(!phase){roundQuestionGuardHint.textContent="Opdatér session-status for round question-id.";}else if(canEditRoundQuestion){roundQuestionGuardHint.textContent="Round question-id kan redigeres i fase: "+phaseLabel(phase)+".";}else{roundQuestionGuardHint.textContent="Round question-id er låst i fase: "+phaseLabel(phase)+".";}}if(categorySelect){categorySelect.disabled=hostActionInFlight||sessionDetailInFlight||!hasCode||phase!=="lobby";}if(categoryGuardHint){if(hostActionInFlight){categoryGuardHint.textContent="Kategori er midlertidigt låst mens en handling kører.";}else if(sessionDetailInFlight){categoryGuardHint.textContent="Kategori er låst mens session-opdatering kører.";}else if(!hasCode){categoryGuardHint.textContent="Angiv sessionkode for at låse kategori til lobby-fasen.";}else if(phase==="lobby"){categoryGuardHint.textContent="Kategori kan vælges i lobby-fasen.";}else if(!phase){categoryGuardHint.textContent="Opdatér session-status for at validere kategori-lås.";}else{categoryGuardHint.textContent="Kategori er låst udenfor lobby-fasen.";}}if(!hint){return;}if(hostActionInFlight){hint.textContent="Handling kører… afvent svar før næste klik.";return;}if(sessionDetailInFlight){hint.textContent="Host-actions er låst mens session-opdatering kører.";return;}if(!hasCode){hint.textContent="Angiv sessionkode for at aktivere host-actions.";return;}if(!phase){hint.textContent="Opdatér session-status for fasebaserede host-actions.";return;}if(phase==="finished"){hint.textContent="Spillet er afsluttet: gameplay-actions er låst.";return;}if((phase==="lie"||phase==="guess")&&!hasRound){hint.textContent="Round question id mangler: mix/beregn score er låst.";return;}if(hostShellRouteHint){hint.textContent=hostShellRouteHint;return;}hint.textContent="Host-actions er klar for fase: "+phaseLabel(phase)+".";} async function api(path,method,payload){var o={method:method||"GET",headers:{"Accept":"application/json"}};if(payload!==null){o.headers["Content-Type"]="application/json";o.headers["X-CSRFToken"]=csrf();o.body=JSON.stringify(payload);}var r=await fetch(path,o);var d=await r.json().catch(function(){return {};});var isSessionDetailRead=(method||"GET")==="GET"&&/^\/lobby\/sessions\/[A-Z0-9]+$/.test(path);if(isSessionDetailRead){markSessionRefresh(r.status);}document.getElementById("out").textContent=JSON.stringify({status:r.status,data:d},null,2);if(d.session&&d.session.code){document.getElementById("code").value=d.session.code;}if(d.session&&d.session.status){currentSessionStatus=d.session.status;}if(d.round_question&&d.round_question.id){document.getElementById("roundQuestionId").value=d.round_question.id;}if(d.session){hydrateHostCriticalView(d);}updateErrorHint(r.status,d);updatePhaseStatus();syncStartRoundGuard(d);updateHostActionState();if(currentSessionStatus==="finished"&&autoRefreshEnabled){stopAutoRefresh("Auto-refresh stoppet: spillet er afsluttet.");}else{updateAutoRefreshUi();}if(hostShellFatalError){clearHostShellFatalError();}saveHostContext();return d;} function withHostActionLock(fn){if(hostActionInFlight){return Promise.resolve({error:"host_action_in_flight"});}hostActionInFlight=true;updateHostActionState();return Promise.resolve().then(fn).finally(function(){hostActionInFlight=false;updateHostActionState();});} diff --git a/lobby/templates/lobby/player_screen.html b/lobby/templates/lobby/player_screen.html index b0f3fc6..fa7d95b 100644 --- a/lobby/templates/lobby/player_screen.html +++ b/lobby/templates/lobby/player_screen.html @@ -105,7 +105,7 @@ function clearPlayerShellFatalError(){playerShellFatalError=false;playerShellRec function recoverPlayerShell(mode){if(playerShellRecoverInFlight){return Promise.resolve({error:"recover_in_flight"});}playerShellRecoverInFlight=true;updatePlayerShellErrorBoundary();if(mode==="reload"){window.location.reload();return Promise.resolve({ok:true});}if(!code()){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();return Promise.resolve({error:"missing_session_code"});}return sessionDetail().then(function(result){clearPlayerShellFatalError();return result;}).catch(function(err){playerShellRecoverInFlight=false;updatePlayerShellErrorBoundary();throw err;});} function pid(){return document.getElementById("playerId").value.trim();} function rq(){return document.getElementById("roundQuestionId").value.trim();} -function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="finished"){return"Afsluttet";}return"Ukendt";} +function phaseLabel(status){if(status==="lobby"){return"Lobby";}if(status==="lie"){return"Løgn";}if(status==="guess"){return"Gæt";}if(status==="reveal"){return"Reveal";}if(status==="scoreboard"){return"Scoreboard";}if(status==="finished"){return"Afsluttet";}return"Ukendt";} function updatePhaseStatus(){var el=document.getElementById("phaseStatus");if(!el){return;}if(!currentSessionStatus){el.textContent="Fase: ukendt (opdatér session-status).";return;}el.textContent="Fase: "+phaseLabel(currentSessionStatus)+" ("+currentSessionStatus+")";} function savePlayerContext(){try{localStorage.setItem(PLAYER_CONTEXT_KEY,JSON.stringify({code:code(),nickname:document.getElementById("nickname").value.trim(),player_id:pid(),session_token:document.getElementById("sessionToken").value.trim(),round_question_id:rq(),auto_refresh:playerAutoRefreshEnabled}));}catch(_e){}} function loadPlayerContext(){try{var raw=localStorage.getItem(PLAYER_CONTEXT_KEY);if(!raw){return null;}return JSON.parse(raw);}catch(_e){return null;}} diff --git a/lobby/tests.py b/lobby/tests.py index 6b156f3..3938c6f 100644 --- a/lobby/tests.py +++ b/lobby/tests.py @@ -779,9 +779,12 @@ class RevealRoundFlowTests(TestCase): self.assertEqual(response.status_code, 200) payload = response.json() - self.assertEqual(payload["session"]["status"], GameSession.Status.REVEAL) + self.assertEqual(payload["session"]["status"], GameSession.Status.SCOREBOARD) self.assertEqual([item["nickname"] for item in payload["leaderboard"]], ["Luna", "Mads"]) + self.session.refresh_from_db() + self.assertEqual(self.session.status, GameSession.Status.SCOREBOARD) + def test_reveal_scoreboard_requires_host(self): self.client.login(username="other_reveal", password="secret123") @@ -795,8 +798,9 @@ class RevealRoundFlowTests(TestCase): self.assertEqual(response.status_code, 403) self.assertEqual(response.json()["error"], "Only host can view scoreboard") - def test_host_can_finish_game_from_reveal(self): + def test_host_can_finish_game_from_scoreboard(self): self.client.login(username="host_reveal", password="secret123") + self.client.get(reverse("lobby:reveal_scoreboard", kwargs={"code": self.session.code})) response = self.client.post( reverse( @@ -840,10 +844,11 @@ class RevealRoundFlowTests(TestCase): ) self.assertEqual(response.status_code, 400) - self.assertEqual(response.json()["error"], "Game can only be finished from reveal phase") + self.assertEqual(response.json()["error"], "Game can only be finished from scoreboard phase") - def test_host_can_start_next_round_from_reveal(self): + def test_host_can_start_next_round_from_scoreboard(self): self.client.login(username="host_reveal", password="secret123") + self.client.get(reverse("lobby:reveal_scoreboard", kwargs={"code": self.session.code})) response = self.client.post( reverse( @@ -861,6 +866,26 @@ class RevealRoundFlowTests(TestCase): self.assertEqual(self.session.status, GameSession.Status.LOBBY) self.assertEqual(self.session.current_round, 2) + def test_reveal_scoreboard_allows_repeated_reads_from_scoreboard_phase(self): + self.client.login(username="host_reveal", password="secret123") + + first_response = self.client.get( + reverse( + "lobby:reveal_scoreboard", + kwargs={"code": self.session.code}, + ) + ) + second_response = self.client.get( + reverse( + "lobby:reveal_scoreboard", + kwargs={"code": self.session.code}, + ) + ) + + self.assertEqual(first_response.status_code, 200) + self.assertEqual(second_response.status_code, 200) + self.assertEqual(second_response.json()["session"]["status"], GameSession.Status.SCOREBOARD) + def test_start_next_round_rejects_wrong_phase(self): self.client.login(username="host_reveal", password="secret123") self.session.status = GameSession.Status.GUESS @@ -874,7 +899,7 @@ class RevealRoundFlowTests(TestCase): ) self.assertEqual(response.status_code, 400) - self.assertEqual(response.json()["error"], "Next round can only start from reveal phase") + self.assertEqual(response.json()["error"], "Next round can only start from scoreboard phase") class UiScreenTests(TestCase): def setUp(self): @@ -1218,10 +1243,19 @@ class SessionDetailPhaseViewModelTests(TestCase): reveal_payload = self.client.get(reverse("lobby:session_detail", kwargs={"code": self.session.code})).json() reveal_phase = reveal_payload["phase_view_model"] self.assertTrue(reveal_phase["host"]["can_reveal_scoreboard"]) - self.assertTrue(reveal_phase["host"]["can_start_next_round"]) - self.assertTrue(reveal_phase["host"]["can_finish_game"]) + self.assertFalse(reveal_phase["host"]["can_start_next_round"]) + self.assertFalse(reveal_phase["host"]["can_finish_game"]) self.assertFalse(reveal_phase["player"]["can_view_final_result"]) + self.session.status = GameSession.Status.SCOREBOARD + self.session.save(update_fields=["status"]) + scoreboard_payload = self.client.get(reverse("lobby:session_detail", kwargs={"code": self.session.code})).json() + scoreboard_phase = scoreboard_payload["phase_view_model"] + self.assertFalse(scoreboard_phase["host"]["can_reveal_scoreboard"]) + self.assertTrue(scoreboard_phase["host"]["can_start_next_round"]) + self.assertTrue(scoreboard_phase["host"]["can_finish_game"]) + self.assertFalse(scoreboard_phase["player"]["can_view_final_result"]) + self.session.status = GameSession.Status.FINISHED self.session.save(update_fields=["status"]) finished_payload = self.client.get(reverse("lobby:session_detail", kwargs={"code": self.session.code})).json() diff --git a/lobby/views.py b/lobby/views.py index 0282fb2..8b94fbe 100644 --- a/lobby/views.py +++ b/lobby/views.py @@ -67,6 +67,7 @@ def _build_phase_view_model(session: GameSession, *, players_count: int, has_rou in_lie = status == GameSession.Status.LIE in_guess = status == GameSession.Status.GUESS in_reveal = status == GameSession.Status.REVEAL + in_scoreboard = status == GameSession.Status.SCOREBOARD in_finished = status == GameSession.Status.FINISHED min_players_reached = players_count >= 3 @@ -88,8 +89,8 @@ def _build_phase_view_model(session: GameSession, *, players_count: int, has_rou "can_mix_answers": in_lie or in_guess, "can_calculate_scores": in_guess, "can_reveal_scoreboard": in_reveal, - "can_start_next_round": in_reveal, - "can_finish_game": in_reveal, + "can_start_next_round": in_scoreboard, + "can_finish_game": in_scoreboard, }, "player": { "can_join": status in JOINABLE_STATUSES, @@ -710,8 +711,14 @@ def reveal_scoreboard(request: HttpRequest, code: str) -> JsonResponse: if session.host_id != request.user.id: return JsonResponse({"error": "Only host can view scoreboard"}, status=403) - if session.status != GameSession.Status.REVEAL: - return JsonResponse({"error": "Scoreboard is only available in reveal phase"}, status=400) + with transaction.atomic(): + locked_session = GameSession.objects.select_for_update().get(pk=session.pk) + if locked_session.status not in {GameSession.Status.REVEAL, GameSession.Status.SCOREBOARD}: + return JsonResponse({"error": "Scoreboard is only available in reveal or scoreboard phase"}, status=400) + + if locked_session.status == GameSession.Status.REVEAL: + locked_session.status = GameSession.Status.SCOREBOARD + locked_session.save(update_fields=["status"]) leaderboard = list( Player.objects.filter(session=session) @@ -723,8 +730,8 @@ def reveal_scoreboard(request: HttpRequest, code: str) -> JsonResponse: { "session": { "code": session.code, - "status": session.status, - "current_round": session.current_round, + "status": locked_session.status, + "current_round": locked_session.current_round, }, "leaderboard": leaderboard, } @@ -746,8 +753,8 @@ def start_next_round(request: HttpRequest, code: str) -> JsonResponse: with transaction.atomic(): locked_session = GameSession.objects.select_for_update().get(pk=session.pk) - if locked_session.status != GameSession.Status.REVEAL: - return JsonResponse({"error": "Next round can only start from reveal phase"}, status=400) + if locked_session.status != GameSession.Status.SCOREBOARD: + return JsonResponse({"error": "Next round can only start from scoreboard phase"}, status=400) locked_session.current_round += 1 locked_session.status = GameSession.Status.LOBBY @@ -778,8 +785,8 @@ def finish_game(request: HttpRequest, code: str) -> JsonResponse: with transaction.atomic(): locked_session = GameSession.objects.select_for_update().get(pk=session.pk) - if locked_session.status != GameSession.Status.REVEAL: - return JsonResponse({"error": "Game can only be finished from reveal phase"}, status=400) + if locked_session.status != GameSession.Status.SCOREBOARD: + return JsonResponse({"error": "Game can only be finished from scoreboard phase"}, status=400) locked_session.status = GameSession.Status.FINISHED locked_session.save(update_fields=["status"])