Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0

- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js)
- Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js)
- Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES
- Обновление AGENTS.md под новый функционал тестов/опросов
This commit is contained in:
dev
2026-12-02 14:27:57 +03:00
parent 664f76d820
commit ef4d7cc472
22 changed files with 2884 additions and 130 deletions
+84 -26
View File
@@ -1,6 +1,7 @@
'use strict';
const crypto = require('crypto');
const { ensureQuizGradeTables, gradeForScore } = require('./quiz-grades');
const QUIZ_KINDS = new Set(['test', 'survey']);
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date']);
@@ -145,6 +146,7 @@ function normalizeIdList(list, max) {
}
async function ensureQuizTables(pool) {
await ensureQuizGradeTables(pool);
await pool.query(`CREATE TABLE IF NOT EXISTS quizzes (
id SERIAL PRIMARY KEY,
title VARCHAR(200) NOT NULL DEFAULT '',
@@ -154,11 +156,13 @@ async function ensureQuizTables(pool) {
shuffle_questions BOOLEAN NOT NULL DEFAULT false,
shuffle_options BOOLEAN NOT NULL DEFAULT false,
show_results BOOLEAN NOT NULL DEFAULT true,
show_answers BOOLEAN NOT NULL DEFAULT true,
max_attempts INT,
time_limit_min INT NOT NULL DEFAULT 0,
pass_percent INT NOT NULL DEFAULT 60,
cover_path TEXT,
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
author_id INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
@@ -169,11 +173,13 @@ async function ensureQuizTables(pool) {
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS shuffle_questions BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS shuffle_options BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_results BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS show_answers BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS max_attempts INT');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS time_limit_min INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS pass_percent INT NOT NULL DEFAULT 60');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS cover_path TEXT');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_questions (
@@ -250,10 +256,12 @@ async function ensureQuizTables(pool) {
percent NUMERIC(6,2) NOT NULL DEFAULT 0,
passed BOOLEAN,
anon_token TEXT,
guest_name TEXT,
started_at TIMESTAMPTZ NOT NULL DEFAULT now(),
finished_at TIMESTAMPTZ
)`);
await pool.query('ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS anon_token TEXT');
await pool.query('ALTER TABLE quiz_attempts ADD COLUMN IF NOT EXISTS guest_name TEXT');
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_attempt_answers (
id SERIAL PRIMARY KEY,
attempt_id INT NOT NULL REFERENCES quiz_attempts(id) ON DELETE CASCADE,
@@ -404,11 +412,13 @@ function quizMeta(row) {
shuffle_questions: row.shuffle_questions === true,
shuffle_options: row.shuffle_options === true,
show_results: row.show_results !== false,
show_answers: row.show_answers !== false,
max_attempts: row.max_attempts,
time_limit_min: row.time_limit_min,
pass_percent: row.pass_percent,
cover_path: row.cover_path,
allow_anonymous: row.allow_anonymous === true,
grade_scale_id: row.grade_scale_id == null ? null : Number(row.grade_scale_id),
author_id: row.author_id,
created_at: row.created_at,
updated_at: row.updated_at,
@@ -535,6 +545,7 @@ function normalizeMeta(body, current) {
const passPercent = intValue(body.pass_percent, 0, 100, 'порог сдачи');
const timeLimit = intValue(body.time_limit_min, 0, QUIZ_TIME_LIMIT_MAX, 'лимит времени');
const maxAttempts = intValue(body.max_attempts, 1, QUIZ_MAX_ATTEMPTS_MAX, 'число попыток');
const gradeScaleId = intValue(body.grade_scale_id, 1, 1000000000, 'критерий оценки');
let coverPath = current.cover_path;
if (body.cover_path !== undefined) {
const raw = body.cover_path;
@@ -550,7 +561,11 @@ function normalizeMeta(body, current) {
shuffle_questions: asBool(body.shuffle_questions, current.shuffle_questions === true),
shuffle_options: asBool(body.shuffle_options, current.shuffle_options === true),
show_results: asBool(body.show_results, current.show_results !== false),
allow_anonymous: kind === 'survey' && asBool(body.allow_anonymous, current.allow_anonymous === true),
show_answers: asBool(body.show_answers, current.show_answers !== false),
allow_anonymous: asBool(body.allow_anonymous, current.allow_anonymous === true),
grade_scale_id: kind === 'survey'
? null
: (body.grade_scale_id === undefined ? (current.grade_scale_id == null ? null : Number(current.grade_scale_id)) : gradeScaleId),
max_attempts: maxAttempts,
time_limit_min: timeLimit == null ? current.time_limit_min : timeLimit,
pass_percent: passPercent == null ? current.pass_percent : passPercent,
@@ -708,6 +723,10 @@ async function saveQuiz(pool, id, user, body = {}) {
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Изменять тест может только автор или администратор');
const meta = normalizeMeta(body, row);
if (meta.grade_scale_id != null) {
const { rows: scaleRows } = await pool.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [meta.grade_scale_id]);
if (!scaleRows.length) throw httpError(400, 'Критерий оценки не найден');
}
const rawQuestions = Array.isArray(body.questions) ? body.questions.slice(0, QUIZ_QUESTIONS_MAX) : [];
const questions = rawQuestions.map((q, i) => validateQuestion(q, meta.kind, i));
const quizAssetIds = normalizeIdList(body.asset_ids, QUIZ_ASSETS_MAX);
@@ -718,11 +737,12 @@ async function saveQuiz(pool, id, user, body = {}) {
await client.query(
`UPDATE quizzes SET title = $2, description = $3, kind = $4, is_published = $5, shuffle_questions = $6,
shuffle_options = $7, show_results = $8, max_attempts = $9, time_limit_min = $10,
pass_percent = $11, cover_path = $12, allow_anonymous = $13, updated_at = now()
pass_percent = $11, cover_path = $12, allow_anonymous = $13, show_answers = $14,
grade_scale_id = $15, updated_at = now()
WHERE id = $1`,
[id, meta.title, meta.description, meta.kind, meta.is_published, meta.shuffle_questions,
meta.shuffle_options, meta.show_results, meta.max_attempts, meta.time_limit_min,
meta.pass_percent, meta.cover_path, meta.allow_anonymous]
meta.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id]
);
const { rows: existingQ } = await client.query('SELECT id FROM quiz_questions WHERE quiz_id = $1', [id]);
const existingQIds = new Set(existingQ.map(r => r.id));
@@ -1061,16 +1081,34 @@ async function performSubmit(pool, row, attempt, body = {}) {
);
await client.query('COMMIT');
const show = row.show_results !== false;
const showAnswers = show && row.show_answers !== false;
let grade = null;
if (row.kind === 'test' && row.grade_scale_id != null) {
const { rows: ranges } = await pool.query(
'SELECT min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
[row.grade_scale_id]
);
grade = gradeForScore(ranges, totalScore);
}
const saved = upd.rows[0];
return {
attempt: {
...saved,
guest_name: attempt.guest_name || null,
score: Number(saved.score),
max_score: Number(saved.max_score),
percent: Number(saved.percent),
},
result: show ? { score: totalScore, max_score: totalMax, percent, passed, questions: results } : null,
revealed: show,
result: show ? {
score: totalScore,
max_score: totalMax,
percent,
passed,
grade,
answers_hidden: !showAnswers,
questions: showAnswers ? results : [],
} : null,
revealed: showAnswers,
};
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
@@ -1091,17 +1129,23 @@ async function submitAttempt(pool, quizId, attemptId, user, body = {}) {
return performSubmit(pool, row, attempt, body);
}
async function findAnonymousSurvey(pool, quizId) {
function guestNameValue(raw) {
if (typeof raw !== 'string') return null;
const value = raw.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 120);
return value || null;
}
async function findPublicQuiz(pool, quizId) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Опрос не найден');
if (row.kind !== 'survey' || row.allow_anonymous !== true || row.is_published !== true) {
throw httpError(404, 'Опрос не найден');
if (!row) throw httpError(404, 'Тест не найден');
if (row.allow_anonymous !== true || row.is_published !== true) {
throw httpError(404, 'Тест не найден');
}
return row;
}
async function getPublicSurvey(pool, quizId) {
const row = await findAnonymousSurvey(pool, quizId);
async function getPublicQuiz(pool, quizId) {
const row = await findPublicQuiz(pool, quizId);
const structure = stripAnswers(await loadQuizStructure(pool, quizId));
const meta = quizMeta(row);
delete meta.author_id;
@@ -1114,16 +1158,17 @@ async function getPublicSurvey(pool, quizId) {
};
}
async function startAnonymousAttempt(pool, quizId) {
await findAnonymousSurvey(pool, quizId);
async function startPublicAttempt(pool, quizId, opts = {}) {
const row = await findPublicQuiz(pool, quizId);
const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null;
const token = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
const { rows } = await pool.query(
'INSERT INTO quiz_attempts (quiz_id, user_id, anon_token) VALUES ($1, NULL, $2) RETURNING id, started_at',
[quizId, token]
'INSERT INTO quiz_attempts (quiz_id, user_id, anon_token, guest_name) VALUES ($1, NULL, $2, $3) RETURNING id, started_at',
[quizId, token, guestName]
);
return {
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: token },
quiz: await getPublicSurvey(pool, quizId),
attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: token, guest_name: guestName },
quiz: await getPublicQuiz(pool, quizId),
};
}
@@ -1134,8 +1179,8 @@ function anonTokenMatches(expected, given) {
return crypto.timingSafeEqual(a, b);
}
async function submitAnonymousAttempt(pool, quizId, attemptId, token, body = {}) {
const row = await findAnonymousSurvey(pool, quizId);
async function submitPublicAttempt(pool, quizId, attemptId, token, body = {}) {
const row = await findPublicQuiz(pool, quizId);
const { rows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, quizId]);
if (!rows.length) throw httpError(404, 'Попытка не найдена');
const attempt = rows[0];
@@ -1159,8 +1204,9 @@ async function listAttempts(pool, quizId, user, params = {}) {
where += ` AND a.user_id = $${args.length}`;
}
const { rows } = await pool.query(
`SELECT a.id, a.user_id, a.status, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at,
CASE WHEN a.user_id IS NULL THEN 'Аноним' ELSE u.name END AS user_name, a.anon_token IS NOT NULL AS anonymous
`SELECT a.id, a.user_id, a.guest_name, a.status, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at,
CASE WHEN a.user_id IS NULL THEN COALESCE(NULLIF(a.guest_name, ''), 'Аноним') ELSE u.name END AS user_name,
(a.user_id IS NULL AND COALESCE(a.guest_name, '') = '') AS anonymous
FROM quiz_attempts a LEFT JOIN users u ON u.id = a.user_id
WHERE ${where}
ORDER BY a.finished_at DESC NULLS LAST, a.id DESC
@@ -1184,7 +1230,7 @@ async function getAttempt(pool, quizId, attemptId, user) {
if (!row) throw httpError(404, 'Тест не найден');
const editable = canEditQuiz(row, user);
const { rows } = await pool.query(
`SELECT a.*, CASE WHEN a.user_id IS NULL THEN 'Аноним' ELSE u.name END AS user_name
`SELECT a.*, CASE WHEN a.user_id IS NULL THEN COALESCE(NULLIF(a.guest_name, ''), 'Аноним') ELSE u.name END AS user_name
FROM quiz_attempts a LEFT JOIN users u ON u.id = a.user_id
WHERE a.id = $1 AND a.quiz_id = $2`,
[attemptId, quizId]
@@ -1198,7 +1244,15 @@ async function getAttempt(pool, quizId, attemptId, user) {
[attemptId]
);
const structure = await loadQuizStructure(pool, quizId);
const revealed = editable || row.show_results !== false;
const revealed = editable || (row.show_results !== false && row.show_answers !== false);
let grade = null;
if (row.kind === 'test' && row.grade_scale_id != null) {
const { rows: ranges } = await pool.query(
'SELECT min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
[row.grade_scale_id]
);
grade = gradeForScore(ranges, attempt.score);
}
const qmap = new Map(structure.questions.map(q => [q.id, q]));
return {
attempt: {
@@ -1224,6 +1278,7 @@ async function getAttempt(pool, quizId, attemptId, user) {
};
}),
revealed,
grade,
};
}
@@ -1321,8 +1376,11 @@ module.exports = {
QUIZ_TITLE_MAX,
QUIZ_DESCRIPTION_MAX,
QUIZ_TEXT_MAX,
QUIZ_DESC_MAX,
QUIZ_ANSWER_MAX,
QUIZ_CAPTION_MAX,
QUIZ_ACCEPTED_MAX,
QUIZ_ACCEPTED_LEN,
QUIZ_QUESTIONS_MAX,
QUIZ_OPTIONS_MAX,
QUIZ_ASSETS_MAX,
@@ -1348,9 +1406,9 @@ module.exports = {
startAttempt,
restartAttempt,
submitAttempt,
getPublicSurvey,
startAnonymousAttempt,
submitAnonymousAttempt,
getPublicQuiz,
startPublicAttempt,
submitPublicAttempt,
normalizeAnswerText,
normalizeNumberValue,
normalizeDateValue,