diff --git a/classquiz/db/models.py b/classquiz/db/models.py index 6e3ceab..83b3e9f 100644 --- a/classquiz/db/models.py +++ b/classquiz/db/models.py @@ -308,6 +308,9 @@ class GameResults(ormar.Model): answers: Json[list[AnswerData]] = ormar.JSON(True) player_scores: Json[dict[str, str]] = ormar.JSON(nullable=True) custom_field_data: Json[dict[str, str]] | None = ormar.JSON(nullable=True) + title: str = ormar.Text(nullable=False) + description: str = ormar.Text(nullable=False) + questions: Json[list[QuizQuestion]] = ormar.JSON(nullable=False) class Meta: tablename = "game_results" diff --git a/classquiz/helpers/__init__.py b/classquiz/helpers/__init__.py index 6ba3543..90dcb66 100644 --- a/classquiz/helpers/__init__.py +++ b/classquiz/helpers/__init__.py @@ -55,7 +55,7 @@ async def generate_spreadsheet(quiz_results: dict, quiz: Quiz, player_fields: di worksheet.write(0, 5, "Wrong answers") for i, _ in enumerate(quiz_results): question = quiz.questions[i] - print(quiz_results) + # print(quiz_results) try: answer_data = quiz_results[str(i)] except KeyError: diff --git a/classquiz/routers/results.py b/classquiz/routers/results.py index 8b0568e..dbc8810 100644 --- a/classquiz/routers/results.py +++ b/classquiz/routers/results.py @@ -13,20 +13,14 @@ router = APIRouter() @router.get("/list", response_model=list[GameResults]) -async def list_game_results(include_quiz: bool = False, user: User = Depends(get_current_user)): - if include_quiz is True: - results = await GameResults.objects.select_related("quiz").all(user=user.id) - else: - results = await GameResults.objects.all(user=user.id) +async def list_game_results(user: User = Depends(get_current_user)): + results = await GameResults.objects.all(user=user.id) return results @router.get("/list/{quiz_id}", response_model=list[GameResults]) -async def get_results_by_quiz(quiz_id: UUID, include_quiz: bool = False, user: User = Depends(get_current_user)): - if include_quiz is True: - res = await GameResults.objects.select_related("quiz").all(user=user.id, quiz=quiz_id) - else: - res = await GameResults.objects.all(user=user.id, quiz=quiz_id) +async def get_results_by_quiz(quiz_id: UUID, user: User = Depends(get_current_user)): + res = await GameResults.objects.all(user=user.id, quiz=quiz_id) if res is None: raise HTTPException(status_code=404, detail="Game Result not found") else: @@ -34,11 +28,8 @@ async def get_results_by_quiz(quiz_id: UUID, include_quiz: bool = False, user: U @router.get("/{game_id}", response_model=GameResults) -async def get_game_result(game_id: UUID, include_quiz: bool = False, user: User = Depends(get_current_user)): - if include_quiz: - res = await GameResults.objects.select_related("quiz").get_or_none(user=user.id, id=game_id) - else: - res = await GameResults.objects.get_or_none(user=user.id, id=game_id) +async def get_game_result(game_id: UUID, user: User = Depends(get_current_user)): + res = await GameResults.objects.get_or_none(user=user.id, id=game_id) if res is None: raise HTTPException(status_code=404, detail="Game Result not found") else: @@ -56,3 +47,29 @@ async def set_note(id: UUID, data: _SetNoteInput, user: User = Depends(get_curre raise HTTPException(status_code=404, detail="Game Result not found") res.note = data.note return await res.update() + + +""" +@router.get("/export/{result_id}", response_class=StreamingResponse) +async def export_result(result_id: UUID, user: User = Depends(get_current_user)): + res = await GameResults.objects.get_or_none(user=user.id, id=result_id) + if res is None: + raise HTTPException(status_code=404, detail="Game Result not found") + quiz = Quiz(title=res.title, questions=res.questions) + spreadsheet = await generate_spreadsheet( + quiz=quiz, quiz_results=data, player_fields=player_fields, player_scores=score_data + ) + + def iter_file(): + yield from spreadsheet + + return StreamingResponse( + iter_file(), + media_type="application/vnd.ms-excel", + headers={ + "Content-Disposition": f"attachment;filename=ClassQuiz-{urllib.parse.quote(quiz.title)}-{datetime.strftime('%m-%d-%Y')}.xlsx" + # noqa: E501 + }, + ) + +""" diff --git a/classquiz/socket_server/__init__.py b/classquiz/socket_server/__init__.py index c5c95fb..967b136 100644 --- a/classquiz/socket_server/__init__.py +++ b/classquiz/socket_server/__init__.py @@ -21,11 +21,12 @@ from classquiz.db.models import ( VotingQuizAnswer, AnswerDataList, AnswerData, - GameResults, ) from pydantic import BaseModel, ValidationError, validator from datetime import datetime +from classquiz.socket_server.export_helpers import save_quiz_to_storage + sio = socketio.AsyncServer(async_mode="asgi", cors_allowed_origins=[]) settings = settings() @@ -514,26 +515,5 @@ async def save_quiz(sid: str): session: dict = await sio.get_session(sid) if not session["admin"]: return - game_pin = session["game_pin"] - game = PlayGame.parse_raw(await redis.get(f"game:{game_pin}")) - player_count = await redis.scard(f"game_session:{game_pin}:players") - answers = [] - for i in range(len(game.questions)): - redis_res = await redis.get(f"game_session:{game_pin}:{i}") - try: - answers.append(json.loads(redis_res)) - except ValidationError: - answers.append([]) - player_scores = await redis.hgetall(f"game_session:{game_pin}:player_scores") - custom_field_data = await redis.hgetall(f"game:{game_pin}:players:custom_fields") - data = GameResults( - id=game.game_id, - quiz=game.quiz_id, - user=game.user_id, - timestamp=datetime.now(), - player_count=player_count, - answers=json.dumps(answers), - player_scores=json.dumps(player_scores), - custom_field_data=json.dumps(custom_field_data), - ) - await data.save() + await save_quiz_to_storage(session["game_pin"]) + await sio.emit("results_saved_successfully") diff --git a/classquiz/socket_server/export_helpers.py b/classquiz/socket_server/export_helpers.py new file mode 100644 index 0000000..75c4743 --- /dev/null +++ b/classquiz/socket_server/export_helpers.py @@ -0,0 +1,41 @@ +# This Source Code Form is subject to the terms of the Mozilla Public +# License, v. 2.0. If a copy of the MPL was not distributed with this +# file, You can obtain one at https://mozilla.org/MPL/2.0/. +import json +from datetime import datetime + +from pydantic import ValidationError + +from classquiz.config import redis +from classquiz.db.models import PlayGame, GameResults + + +async def save_quiz_to_storage(game_pin: str): + game = PlayGame.parse_raw(await redis.get(f"game:{game_pin}")) + player_count = await redis.scard(f"game_session:{game_pin}:players") + answers = [] + for i in range(len(game.questions)): + redis_res = await redis.get(f"game_session:{game_pin}:{i}") + try: + answers.append(json.loads(redis_res)) + except ValidationError: + answers.append([]) + player_scores = await redis.hgetall(f"game_session:{game_pin}:player_scores") + custom_field_data = await redis.hgetall(f"game:{game_pin}:players:custom_fields") + q_return = [] + for q in game.questions: + q_return.append(q.dict()) + data = GameResults( + id=game.game_id, + quiz=game.quiz_id, + user=game.user_id, + timestamp=datetime.now(), + player_count=player_count, + answers=json.dumps(answers), + player_scores=json.dumps(player_scores), + custom_field_data=json.dumps(custom_field_data), + title=game.title, + description=game.description, + questions=json.dumps(q_return), + ) + await data.save() diff --git a/frontend/src/lib/i18n/locales/en.json b/frontend/src/lib/i18n/locales/en.json index 60b71cc..c6ee4d3 100644 --- a/frontend/src/lib/i18n/locales/en.json +++ b/frontend/src/lib/i18n/locales/en.json @@ -157,7 +157,11 @@ "backup_code": "Backup-code", "totp": "Totp", "text": "Text", - "order": "order" + "order": "order", + "results": "Results", + "note": "Note", + "player_plural": "Players", + "score": "Score" }, "editor": { "time_in_seconds": "Time in seconds", @@ -189,7 +193,8 @@ "show_next_question": "Show next question", "start_by_showing_first_question": "Start by showing the first question.", "no_answers": "No answers!", - "stop_time": "Stop time" + "stop_time": "Stop time", + "save_results": "Save results" }, "password_reset_page": { "reset_password": "Reset password" @@ -253,5 +258,19 @@ "clothe_graphic_type": "Graphic", "thats_you": "That's You!", "start_over": "Start over" + }, + "results_page": { + "no_results_so_far": "No results saved so far...", + "quiz_title": "Quiz Title", + "date_played": "Date Played", + "player_count": "Player count" + }, + "result_page": { + "player_name": "Player name", + "custom_field": "Custom field", + "average_score": "Average score: {{average_score}}", + "correct_answer": "{{count}} correct answer", + "correct_answer_plural": "{{count}} correct answers", + "time_taken": "Time taken" } } diff --git a/frontend/src/routes/admin/+page.svelte b/frontend/src/routes/admin/+page.svelte index 513eea5..0ce5c44 100644 --- a/frontend/src/routes/admin/+page.svelte +++ b/frontend/src/routes/admin/+page.svelte @@ -15,6 +15,7 @@ import { browser } from '$app/environment'; import { onMount } from 'svelte'; import FinalResults from '$lib/play/admin/final_results.svelte'; + import GrayButton from '$lib/components/buttons/gray.svelte'; navbarVisible.set(false); @@ -98,6 +99,10 @@ }, 200); }); + socket.on('results_saved_successfully', (_) => { + results_saved = true; + }); + const confirmUnload = () => { if (warnToLeave) { event.preventDefault(); @@ -135,6 +140,7 @@ }; let bg_color; let bg_image; + let results_saved = false; $: bg_color = quiz_data ? quiz_data.background_color : undefined; $: bg_image = quiz_data ? quiz_data.background_image : undefined; let show_final_results = false; @@ -155,14 +161,34 @@ {#if JSON.stringify(final_results) !== JSON.stringify([null])} {#if control_visible}
| Quiz Title - | -Date Played - | -Player count - | -Note | -||||
|---|---|---|---|---|---|---|---|
| {result.quiz.title} | -{new Date(result.timestamp).toLocaleString()} | -{Object.keys(result.player_scores).length} | -- {#if result.note} - {result.note} - {/if} - | + {#if data.results.length === 0} +
| {$t('results_page.quiz_title')} + | +{$t('results_page.date_played')} + | +{$t('results_page.player_count')} + | +{$t('words.note')} |
|---|
+ The quiz with the title '{title}' was played on + {new Date(timestamp).toLocaleString()} + with {usernames.length} players. The players achieved an average score + of {get_average_final_score()}. +
+Average Score: {get_average_score(i)}
-- {get_number_of_correct_answers(i)} correct Answer(s) -
+ {#if question.type !== QuizQuestionType.VOTING} + {@const correct_answers = get_number_of_correct_answers(i)} ++ {$t('result_page.average_score', { + average_score: get_average_score(i) + })} +
++ {$t('result_page.correct_answer', { count: correct_answers })} + +
+ {/if}