feat(quizzes): тесты ученика на странице профиля

- GET /api/students/:id/overview отдаёт quizzes (история попыток ученика)
- studentQuizResults(pool, studentId, user) в lib/quizzes.js
- идентификация ученика через системный вопрос kind='student'
- индекс idx_quiz_attempt_answers_answer в init/migration/ensureQuizTables
- таб «Тесты» на public/student.html + рендер в public/js/student.js
- обновление AGENTS.md (раздел 3n)
This commit is contained in:
dev
2026-12-02 19:09:39 +03:00
parent 08fc6f9356
commit 527c6db75b
7 changed files with 253 additions and 5 deletions
+140
View File
@@ -329,6 +329,7 @@ async function ensureQuizTables(pool) {
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempts_user ON quiz_attempts(user_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_attempt ON quiz_attempt_answers(attempt_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_question ON quiz_attempt_answers(question_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_answer ON quiz_attempt_answers(answer_id) WHERE answer_id IS NOT NULL');
}
function canEditQuiz(quiz, user) {
@@ -1423,6 +1424,144 @@ async function getAttempt(pool, quizId, attemptId, user) {
};
}
function quizAnswerPayload(a, graded, revealed, optionText) {
const snapshot = a.answer_snapshot && typeof a.answer_snapshot === 'object' ? a.answer_snapshot : {};
const snapOptions = Array.isArray(snapshot.options) ? snapshot.options : [];
const selectedIds = Array.isArray(a.option_ids)
? a.option_ids.map(Number).filter(n => Number.isInteger(n) && n > 0)
: [];
const optionMap = new Map();
for (const o of snapOptions) {
const oid = Number(o && o.id);
if (!Number.isInteger(oid) || oid <= 0) continue;
optionMap.set(oid, { id: oid, text: String(o.text || ''), is_correct: o.is_correct === true });
}
for (const [oid, text] of optionText) {
if (!optionMap.has(oid)) optionMap.set(oid, { id: oid, text, is_correct: false });
}
const selected = selectedIds.map(oid => {
const o = optionMap.get(oid) || { id: oid, text: '', is_correct: false };
return { id: oid, text: o.text, is_correct: graded && revealed ? o.is_correct : null };
});
const correct = graded && revealed
? [...optionMap.values()].filter(o => o.is_correct).map(o => ({ id: o.id, text: o.text }))
: [];
return {
question_id: a.question_id,
text: a.text,
kind: a.kind,
text_answer: a.text_answer || '',
answer_id: a.answer_id == null ? null : Number(a.answer_id),
selected,
correct,
is_correct: graded && revealed ? a.is_correct : null,
score: graded && revealed ? Number(a.score) : null,
max_score: graded && revealed ? Number(a.max_score) : null,
};
}
async function studentQuizResults(pool, studentId, user, opts = {}) {
const limit = Math.min(Math.max(Number(opts.limit) || 200, 1), 500);
const base = `FROM quiz_attempts a
JOIN quizzes q ON q.id = a.quiz_id
WHERE a.status = 'done'
AND q.deleted_at IS NULL
AND EXISTS (
SELECT 1 FROM quiz_attempt_answers aa
LEFT JOIN quiz_questions qq ON qq.id = aa.question_id
WHERE aa.attempt_id = a.id
AND aa.answer_id = $1
AND (qq.kind = 'student' OR aa.answer_snapshot->>'field' = 'student'))`;
const [totalRes, listRes] = await Promise.all([
pool.query(`SELECT count(*)::int AS n ${base}`, [studentId]),
pool.query(
`SELECT a.id, a.quiz_id, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at,
q.title, q.kind, q.show_results, q.show_answers, q.pass_percent, q.author_id, q.grade_scale_id
${base}
ORDER BY a.finished_at DESC NULLS LAST, a.id DESC
LIMIT $2`,
[studentId, limit]
),
]);
const attempts = listRes.rows;
const attemptIds = attempts.map(r => r.id);
let answerRows = [];
if (attemptIds.length) {
const { rows } = await pool.query(
`SELECT aa.attempt_id, aa.question_id, aa.option_ids, aa.answer_snapshot, aa.text_answer,
aa.answer_id, aa.is_correct, aa.score, aa.max_score,
COALESCE(aa.answer_snapshot->>'kind', qq.kind, 'line') AS kind,
COALESCE(NULLIF(aa.question_text, ''), qq.text, '') AS text
FROM quiz_attempt_answers aa
LEFT JOIN quiz_questions qq ON qq.id = aa.question_id
WHERE aa.attempt_id = ANY($1::int[])
ORDER BY aa.attempt_id, COALESCE(qq.sort_order, 0), aa.id`,
[attemptIds]
);
answerRows = rows;
}
const optionIds = new Set();
for (const a of answerRows) {
if (Array.isArray(a.option_ids)) a.option_ids.forEach((oid) => { if (Number(oid) > 0) optionIds.add(Number(oid)); });
const snapOptions = a.answer_snapshot && Array.isArray(a.answer_snapshot.options) ? a.answer_snapshot.options : [];
snapOptions.forEach((o) => { if (Number(o && o.id) > 0) optionIds.add(Number(o.id)); });
}
const optionText = new Map();
if (optionIds.size) {
const { rows } = await pool.query('SELECT id, text FROM quiz_options WHERE id = ANY($1::int[])', [[...optionIds]]);
rows.forEach(o => optionText.set(Number(o.id), String(o.text || '')));
}
const scaleIds = [...new Set(attempts
.filter(r => r.kind === 'test' && r.grade_scale_id != null)
.map(r => Number(r.grade_scale_id)))];
const rangesByScale = new Map();
if (scaleIds.length) {
const { rows } = await pool.query(
'SELECT scale_id, min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = ANY($1::int[]) ORDER BY min_score ASC, id ASC',
[scaleIds]
);
for (const r of rows) {
const key = Number(r.scale_id);
if (!rangesByScale.has(key)) rangesByScale.set(key, []);
rangesByScale.get(key).push(r);
}
}
const byAttempt = new Map();
for (const a of answerRows) {
if (!byAttempt.has(a.attempt_id)) byAttempt.set(a.attempt_id, []);
byAttempt.get(a.attempt_id).push(a);
}
const items = attempts.map(row => {
const editable = canEditQuiz(row, user);
const showResults = editable || row.show_results !== false;
const revealed = editable || (row.show_results !== false && row.show_answers !== false);
const graded = row.kind === 'test';
const answers = (byAttempt.get(row.id) || [])
.filter(a => !SYSTEM_FIELD_KINDS.has(a.kind))
.map(a => quizAnswerPayload(a, graded, revealed, optionText));
const grade = graded && row.grade_scale_id != null
? gradeForScore(rangesByScale.get(Number(row.grade_scale_id)) || [], Number(row.score))
: null;
return {
id: row.id,
quiz_id: row.quiz_id,
title: row.title,
kind: row.kind,
show_results: showResults,
revealed,
score: showResults ? Number(row.score) : null,
max_score: showResults ? Number(row.max_score) : null,
percent: showResults ? Number(row.percent) : null,
passed: showResults ? row.passed : null,
grade: showResults ? grade : null,
started_at: row.started_at,
finished_at: row.finished_at,
answers,
};
});
return { items, total: totalRes.rows[0].n };
}
function statsId(v) {
const n = Number(v);
return Number.isInteger(n) && n > 0 ? n : null;
@@ -1730,6 +1869,7 @@ module.exports = {
normalizeDateValue,
listAttempts,
getAttempt,
studentQuizResults,
quizStats,
statsSummary,
statsFilterRows,