блоки 2 и 3 доработки интерфейса системы тестирования
This commit is contained in:
@@ -1,12 +1,15 @@
|
||||
"""Создание/правка теста, fork версии при наличии попыток (порт `testDraftService.js`)."""
|
||||
"""Создание/правка теста, fork версии при наличии попыток."""
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid as _uuid
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..db import get_engine
|
||||
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
|
||||
|
||||
@@ -19,216 +22,177 @@ class HttpError(Exception):
|
||||
|
||||
|
||||
def create_test_with_version(author_id: str, *, title: str, description: str | None) -> dict:
|
||||
eng = get_engine()
|
||||
with eng.begin() as conn:
|
||||
t = conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO tests (title, description, created_by, is_active, is_versioned)
|
||||
VALUES (:title, :desc, :uid, true, true) RETURNING id
|
||||
"""
|
||||
),
|
||||
{'title': title, 'desc': description or None, 'uid': author_id},
|
||||
).mappings().first()
|
||||
test_id = t['id']
|
||||
v = conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO test_versions (test_id, version, is_active, parent_id)
|
||||
VALUES (:tid, 1, true, NULL) RETURNING id
|
||||
"""
|
||||
),
|
||||
{'tid': test_id},
|
||||
).mappings().first()
|
||||
return {'testId': str(test_id), 'versionId': str(v['id'])}
|
||||
session = get_session()
|
||||
try:
|
||||
uid = _uuid.UUID(author_id)
|
||||
except (ValueError, AttributeError):
|
||||
raise HttpError(400, 'Некорректный user_id.')
|
||||
|
||||
test = Test(
|
||||
title=title,
|
||||
description=description or None,
|
||||
created_by=uid,
|
||||
is_active=True,
|
||||
is_versioned=True,
|
||||
)
|
||||
session.add(test)
|
||||
session.flush() # получаем test.id
|
||||
|
||||
version = TestVersion(test_id=test.id, version=1, is_active=True, parent_id=None)
|
||||
session.add(version)
|
||||
session.commit()
|
||||
return {'testId': str(test.id), 'versionId': str(version.id)}
|
||||
|
||||
|
||||
def _get_active_version_row(conn, test_id: str) -> dict | None:
|
||||
row = conn.execute(
|
||||
text(
|
||||
'SELECT * FROM test_versions WHERE test_id = :id AND is_active = true LIMIT 1'
|
||||
),
|
||||
{'id': test_id},
|
||||
).mappings().first()
|
||||
return dict(row) if row else None
|
||||
def _get_active_version(session: Session, test_id: _uuid.UUID) -> TestVersion | None:
|
||||
return (
|
||||
session.query(TestVersion)
|
||||
.filter(TestVersion.test_id == test_id, TestVersion.is_active.is_(True))
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _copy_question_tree(conn, from_version_id, to_version_id) -> None:
|
||||
questions = conn.execute(
|
||||
text(
|
||||
'SELECT id, text, question_order, has_multiple_answers '
|
||||
'FROM questions WHERE test_version_id = :v ORDER BY question_order'
|
||||
),
|
||||
{'v': from_version_id},
|
||||
).mappings().all()
|
||||
def _copy_question_tree(session: Session, from_version_id, to_version_id) -> None:
|
||||
questions = (
|
||||
session.query(Question)
|
||||
.filter(Question.test_version_id == from_version_id)
|
||||
.order_by(Question.question_order)
|
||||
.all()
|
||||
)
|
||||
for q in questions:
|
||||
new_q = conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO questions (test_version_id, text, question_order, has_multiple_answers)
|
||||
VALUES (:v, :text, :ord, :multi) RETURNING id
|
||||
"""
|
||||
),
|
||||
{
|
||||
'v': to_version_id,
|
||||
'text': q['text'],
|
||||
'ord': q['question_order'],
|
||||
'multi': q['has_multiple_answers'],
|
||||
},
|
||||
).mappings().first()
|
||||
nqid = new_q['id']
|
||||
opts = conn.execute(
|
||||
text(
|
||||
'SELECT text, is_correct, option_order FROM answer_options '
|
||||
'WHERE question_id = :q ORDER BY option_order'
|
||||
),
|
||||
{'q': q['id']},
|
||||
).mappings().all()
|
||||
for o in opts:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO answer_options (question_id, text, is_correct, option_order)
|
||||
VALUES (:q, :text, :ic, :ord)
|
||||
"""
|
||||
),
|
||||
{'q': nqid, 'text': o['text'], 'ic': o['is_correct'], 'ord': o['option_order']},
|
||||
)
|
||||
new_q = Question(
|
||||
test_version_id=to_version_id,
|
||||
text=q.text,
|
||||
question_order=q.question_order,
|
||||
has_multiple_answers=q.has_multiple_answers,
|
||||
ai_hint=q.ai_hint,
|
||||
)
|
||||
session.add(new_q)
|
||||
session.flush()
|
||||
for o in sorted(q.options, key=lambda x: x.option_order):
|
||||
session.add(AnswerOption(
|
||||
question_id=new_q.id,
|
||||
text=o.text,
|
||||
is_correct=o.is_correct,
|
||||
option_order=o.option_order,
|
||||
))
|
||||
|
||||
|
||||
def _replace_version_content(conn, test_version_id, payload: dict) -> None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
DELETE FROM answer_options WHERE question_id IN (
|
||||
SELECT id FROM questions WHERE test_version_id = :v
|
||||
)
|
||||
"""
|
||||
),
|
||||
{'v': test_version_id},
|
||||
)
|
||||
conn.execute(
|
||||
text('DELETE FROM questions WHERE test_version_id = :v'),
|
||||
{'v': test_version_id},
|
||||
)
|
||||
questions = payload.get('questions') or []
|
||||
for i, q in enumerate(questions):
|
||||
ins_q = conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO questions (test_version_id, text, question_order, has_multiple_answers)
|
||||
VALUES (:v, :text, :ord, :multi) RETURNING id
|
||||
"""
|
||||
),
|
||||
{
|
||||
'v': test_version_id,
|
||||
'text': q.get('text'),
|
||||
'ord': q.get('question_order') or (i + 1),
|
||||
'multi': bool(q.get('hasMultipleAnswers')),
|
||||
},
|
||||
).mappings().first()
|
||||
qid = ins_q['id']
|
||||
opts = q.get('options') or []
|
||||
for j, o in enumerate(opts):
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO answer_options (question_id, text, is_correct, option_order)
|
||||
VALUES (:q, :text, :ic, :ord)
|
||||
"""
|
||||
),
|
||||
{
|
||||
'q': qid,
|
||||
'text': o.get('text'),
|
||||
'ic': bool(o.get('isCorrect')),
|
||||
'ord': o.get('option_order') or (j + 1),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _fork_new_version(conn, test_id: str) -> dict:
|
||||
av = _get_active_version_row(conn, test_id)
|
||||
def _fork_new_version(session: Session, test_id: _uuid.UUID) -> TestVersion:
|
||||
av = _get_active_version(session, test_id)
|
||||
if not av:
|
||||
raise HttpError(500, RU['internal']) # invariant: должна быть активная версия
|
||||
mx = conn.execute(
|
||||
text(
|
||||
'SELECT COALESCE(MAX(version), 0) AS v FROM test_versions WHERE test_id = :t'
|
||||
),
|
||||
{'t': test_id},
|
||||
).mappings().first()
|
||||
next_v = (mx['v'] or 0) + 1
|
||||
conn.execute(
|
||||
text('UPDATE test_versions SET is_active = false WHERE test_id = :t'),
|
||||
{'t': test_id},
|
||||
raise HttpError(500, RU['internal'] if 'internal' in RU else 'Внутренняя ошибка.')
|
||||
|
||||
max_ver = (
|
||||
session.query(func.coalesce(func.max(TestVersion.version), 0))
|
||||
.filter(TestVersion.test_id == test_id)
|
||||
.scalar() or 0
|
||||
)
|
||||
nv = conn.execute(
|
||||
text(
|
||||
"""
|
||||
INSERT INTO test_versions (test_id, version, is_active, parent_id)
|
||||
VALUES (:t, :ver, true, :parent) RETURNING *
|
||||
"""
|
||||
),
|
||||
{'t': test_id, 'ver': next_v, 'parent': av['id']},
|
||||
).mappings().first()
|
||||
_copy_question_tree(conn, av['id'], nv['id'])
|
||||
return dict(nv)
|
||||
next_v = int(max_ver) + 1
|
||||
|
||||
# деактивируем все версии
|
||||
session.query(TestVersion).filter(TestVersion.test_id == test_id).update(
|
||||
{TestVersion.is_active: False}, synchronize_session='fetch'
|
||||
)
|
||||
|
||||
new_version = TestVersion(
|
||||
test_id=test_id,
|
||||
version=next_v,
|
||||
is_active=True,
|
||||
parent_id=av.id,
|
||||
)
|
||||
session.add(new_version)
|
||||
session.flush()
|
||||
_copy_question_tree(session, av.id, new_version.id)
|
||||
return new_version
|
||||
|
||||
|
||||
def _replace_version_content(session: Session, version: TestVersion, payload: dict) -> None:
|
||||
# Снимок ai_hint по тексту вопроса перед удалением
|
||||
old_hints: dict[str, str] = {}
|
||||
for q in version.questions:
|
||||
if q.ai_hint and q.text not in old_hints:
|
||||
old_hints[q.text] = q.ai_hint
|
||||
|
||||
# удаляем через cascade (answer_options удалятся каскадно через ORM)
|
||||
for q in list(version.questions):
|
||||
session.delete(q)
|
||||
session.flush()
|
||||
|
||||
questions_payload = payload.get('questions') or []
|
||||
for i, qp in enumerate(questions_payload):
|
||||
q_text = (qp.get('text') or '').strip()
|
||||
new_q = Question(
|
||||
test_version_id=version.id,
|
||||
text=q_text,
|
||||
question_order=qp.get('question_order') or (i + 1),
|
||||
has_multiple_answers=bool(qp.get('hasMultipleAnswers')),
|
||||
ai_hint=old_hints.get(q_text),
|
||||
)
|
||||
session.add(new_q)
|
||||
session.flush()
|
||||
for j, op in enumerate(qp.get('options') or []):
|
||||
session.add(AnswerOption(
|
||||
question_id=new_q.id,
|
||||
text=(op.get('text') or '').strip(),
|
||||
is_correct=bool(op.get('isCorrect')),
|
||||
option_order=op.get('option_order') or (j + 1),
|
||||
))
|
||||
|
||||
|
||||
def save_test_draft(author_id: str, test_id: str, payload: dict) -> dict:
|
||||
if not isinstance(payload, dict):
|
||||
payload = {}
|
||||
eng = get_engine()
|
||||
with eng.begin() as conn:
|
||||
t = conn.execute(
|
||||
text('SELECT id, created_by FROM tests WHERE id = :id'),
|
||||
{'id': test_id},
|
||||
).mappings().first()
|
||||
if not t:
|
||||
raise HttpError(404, RU['testNotFound'] if 'testNotFound' in RU else 'Тест не найден.')
|
||||
if not is_test_author(t['created_by'], author_id):
|
||||
raise HttpError(403, 'Доступ запрещён.')
|
||||
session = get_session()
|
||||
try:
|
||||
tid = _uuid.UUID(test_id)
|
||||
except (ValueError, AttributeError):
|
||||
raise HttpError(404, 'Тест не найден.')
|
||||
|
||||
if payload.get('title') is not None or payload.get('description') is not None:
|
||||
conn.execute(
|
||||
text(
|
||||
"""
|
||||
UPDATE tests
|
||||
SET title = COALESCE(:title, title),
|
||||
description = COALESCE(:desc, description),
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
WHERE id = :id
|
||||
"""
|
||||
),
|
||||
{
|
||||
'title': payload.get('title'),
|
||||
'desc': payload.get('description'),
|
||||
'id': test_id,
|
||||
},
|
||||
)
|
||||
if payload.get('passingThreshold') is not None:
|
||||
try:
|
||||
raw = float(payload['passingThreshold'])
|
||||
pt = max(0, min(100, round(raw)))
|
||||
conn.execute(
|
||||
text(
|
||||
'UPDATE tests SET passing_threshold = :pt, updated_at = CURRENT_TIMESTAMP WHERE id = :id'
|
||||
),
|
||||
{'pt': pt, 'id': test_id},
|
||||
)
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
test = session.get(Test, tid)
|
||||
if not test:
|
||||
raise HttpError(404, 'Тест не найден.')
|
||||
if not is_test_author(test.created_by, author_id):
|
||||
raise HttpError(403, 'Доступ запрещён.')
|
||||
|
||||
has_attempts = has_any_attempt_for_test(conn, test_id)
|
||||
version_row = _get_active_version_row(conn, test_id)
|
||||
if not version_row:
|
||||
raise HttpError(500, 'Нет активной версии теста.')
|
||||
if payload.get('title') is not None:
|
||||
test.title = payload['title']
|
||||
if payload.get('description') is not None:
|
||||
test.description = payload['description'] or None
|
||||
|
||||
forked = False
|
||||
if has_attempts and 'questions' in payload and payload.get('questions') is not None:
|
||||
version_row = _fork_new_version(conn, test_id)
|
||||
forked = True
|
||||
if payload.get('passingThreshold') is not None:
|
||||
try:
|
||||
test.passing_threshold = max(0, min(100, round(float(payload['passingThreshold']))))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
if payload.get('questions') is not None:
|
||||
_replace_version_content(conn, version_row['id'], payload)
|
||||
if 'timeLimit' in payload:
|
||||
tl = payload.get('timeLimit')
|
||||
try:
|
||||
test.time_limit = None if tl in (None, '', 0) else max(0, int(tl))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
|
||||
return {'testId': test_id, 'versionId': str(version_row['id']), 'forked': forked}
|
||||
if 'hintsEnabled' in payload:
|
||||
test.hints_enabled = bool(payload['hintsEnabled'])
|
||||
|
||||
if 'resultMode' in payload:
|
||||
rm = (payload.get('resultMode') or '').strip().lower()
|
||||
if rm in ('immediate', 'end'):
|
||||
test.result_mode = rm
|
||||
|
||||
has_attempts = has_any_attempt_for_test(session, tid)
|
||||
active_version = _get_active_version(session, tid)
|
||||
if not active_version:
|
||||
raise HttpError(500, 'Нет активной версии теста.')
|
||||
|
||||
forked = False
|
||||
if has_attempts and 'questions' in payload and payload.get('questions') is not None:
|
||||
active_version = _fork_new_version(session, tid)
|
||||
forked = True
|
||||
|
||||
if payload.get('questions') is not None:
|
||||
_replace_version_content(session, active_version, payload)
|
||||
|
||||
session.commit()
|
||||
return {'testId': test_id, 'versionId': str(active_version.id), 'forked': forked}
|
||||
|
||||
Reference in New Issue
Block a user