блоки 2 и 3 доработки интерфейса системы тестирования

This commit is contained in:
Константин Лебединский
2026-04-29 21:06:17 +05:00
parent eff3fda5b0
commit bba96f8f9f
37 changed files with 4440 additions and 1292 deletions
+70 -71
View File
@@ -1,14 +1,14 @@
"""Контент редактора: тест + активная версия + дерево вопросов с правильными вариантами.
Порт `getEditorContent` + `loadQuestionsForVersion` (только includeCorrect=true вариант)
из `services/testAttemptService.js`.
"""
"""Контент редактора: тест + активная версия + дерево вопросов с правильными вариантами."""
from __future__ import annotations
from sqlalchemy import text
import uuid as _uuid
from ..db import get_engine
from sqlalchemy import func
from sqlalchemy.orm import selectinload
from ..db import get_session
from ..messages import RU
from ..models import AnswerOption, Question, Test, TestVersion
from .test_access import is_test_author
from .test_chain import has_any_attempt_for_test
@@ -20,86 +20,85 @@ class HttpError(Exception):
self.message = message
def load_questions_for_version(conn, test_version_id, *, include_correct: bool) -> list[dict]:
qrows = conn.execute(
text(
'SELECT id, text, question_order, has_multiple_answers '
'FROM questions WHERE test_version_id = :v ORDER BY question_order'
),
{'v': test_version_id},
).mappings().all()
def load_questions_for_version(session, test_version_id, *, include_correct: bool) -> list[dict]:
if not isinstance(test_version_id, _uuid.UUID):
try:
test_version_id = _uuid.UUID(str(test_version_id))
except (ValueError, AttributeError):
return []
questions = (
session.query(Question)
.options(selectinload(Question.options))
.filter(Question.test_version_id == test_version_id)
.order_by(Question.question_order)
.all()
)
out = []
for r in qrows:
orows = conn.execute(
text(
'SELECT id, text, is_correct, option_order '
'FROM answer_options WHERE question_id = :q ORDER BY option_order'
),
{'q': r['id']},
).mappings().all()
for q in questions:
options = []
for o in orows:
for o in sorted(q.options, key=lambda x: x.option_order):
base = {
'id': str(o['id']),
'text': o['text'],
'optionOrder': o['option_order'],
'id': str(o.id),
'text': o.text,
'optionOrder': o.option_order,
}
if include_correct:
base['isCorrect'] = bool(o['is_correct'])
base['isCorrect'] = bool(o.is_correct)
options.append(base)
out.append(
{
'id': str(r['id']),
'text': r['text'],
'questionOrder': r['question_order'],
'hasMultipleAnswers': bool(r['has_multiple_answers']),
'options': options,
}
)
out.append({
'id': str(q.id),
'text': q.text,
'questionOrder': q.question_order,
'hasMultipleAnswers': bool(q.has_multiple_answers),
'options': options,
})
return out
def get_editor_content(user_id: str, test_id: str) -> dict:
eng = get_engine()
with eng.connect() as conn:
tr = conn.execute(
text(
'SELECT id, title, description, passing_threshold, created_by '
'FROM tests WHERE id = :id'
),
{'id': test_id},
).mappings().first()
if not tr:
raise HttpError(404, 'Тест не найден.')
if not is_test_author(tr['created_by'], user_id):
raise HttpError(403, 'Доступ запрещён.')
tv = conn.execute(
text(
'SELECT id FROM test_versions WHERE test_id = :id AND is_active = true LIMIT 1'
),
{'id': test_id},
).mappings().first()
if not tv:
raise HttpError(400, 'Нет активной версии теста.')
version_id = tv['id']
version_count_row = conn.execute(
text('SELECT COUNT(*) AS n FROM test_versions WHERE test_id = :id'),
{'id': test_id},
).mappings().first()
version_count = int(version_count_row['n'] or 0)
questions = load_questions_for_version(conn, version_id, include_correct=True)
has_attempts = has_any_attempt_for_test(conn, test_id)
session = get_session()
try:
tid = _uuid.UUID(test_id)
except (ValueError, AttributeError):
raise HttpError(404, 'Тест не найден.')
test = session.get(Test, tid)
if not test:
raise HttpError(404, 'Тест не найден.')
if not is_test_author(test.created_by, user_id):
raise HttpError(403, 'Доступ запрещён.')
active_version = (
session.query(TestVersion)
.filter(TestVersion.test_id == tid, TestVersion.is_active.is_(True))
.first()
)
if not active_version:
raise HttpError(400, 'Нет активной версии теста.')
version_count = (
session.query(func.count(TestVersion.id))
.filter(TestVersion.test_id == tid)
.scalar() or 0
)
questions = load_questions_for_version(session, active_version.id, include_correct=True)
has_attempts = has_any_attempt_for_test(session, tid)
return {
'test': {
'id': str(tr['id']),
'title': tr['title'],
'description': tr['description'],
'passingThreshold': tr['passing_threshold'],
'id': str(test.id),
'title': test.title,
'description': test.description,
'passingThreshold': test.passing_threshold,
'timeLimit': test.time_limit,
'hintsEnabled': bool(test.hints_enabled),
'resultMode': test.result_mode or 'end',
'hasAttempts': bool(has_attempts),
'versionCount': version_count,
'hasForkRisk': bool(has_attempts) or version_count > 1,
},
'activeVersionId': str(version_id),
'activeVersionId': str(active_version.id),
'questions': questions,
}