✨ Finished game-results
This commit is contained in:
@@ -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"
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
|
||||
},
|
||||
)
|
||||
|
||||
"""
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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()
|
||||
Reference in New Issue
Block a user