Тесты и опросы: генерация ИИ, критерии оценки, версия 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:
@@ -0,0 +1,198 @@
|
||||
'use strict';
|
||||
|
||||
const JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error']);
|
||||
const PRUNE_DAYS = 7;
|
||||
const HISTORY_DEFAULT_LIMIT = 20;
|
||||
const HISTORY_MAX_LIMIT = 100;
|
||||
|
||||
function publicJob(row) {
|
||||
if (!row) return null;
|
||||
return {
|
||||
id: row.id,
|
||||
user_id: row.user_id,
|
||||
status: JOB_STATUSES.has(row.status) ? row.status : 'pending',
|
||||
kind: row.kind,
|
||||
count: row.question_count,
|
||||
questions: row.questions == null ? null : Number(row.questions),
|
||||
model: row.model || null,
|
||||
quiz_id: row.quiz_id == null ? null : Number(row.quiz_id),
|
||||
error: row.error || null,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
finished_at: row.finished_at,
|
||||
};
|
||||
}
|
||||
|
||||
function historyJob(row) {
|
||||
const job = publicJob(row);
|
||||
if (!job) return null;
|
||||
job.user_name = row.user_name || null;
|
||||
job.user_username = row.user_username || null;
|
||||
job.prompt = row.prompt || '';
|
||||
job.difficulty = row.difficulty || 'medium';
|
||||
job.profile = row.profile || '';
|
||||
job.attempts = Number(row.attempts) || 0;
|
||||
return job;
|
||||
}
|
||||
|
||||
async function listQuizAiJobs(pool, user, options = {}) {
|
||||
const limit = Math.max(1, Math.min(HISTORY_MAX_LIMIT, parseInt(options.limit, 10) || HISTORY_DEFAULT_LIMIT));
|
||||
const offset = Math.max(0, parseInt(options.offset, 10) || 0);
|
||||
const own = user.role !== 'admin';
|
||||
const where = own ? 'WHERE j.user_id = $1' : '';
|
||||
const params = own ? [user.id] : [];
|
||||
params.push(limit, offset);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT j.*, u.name AS user_name, u.username AS user_username
|
||||
FROM quiz_ai_jobs j
|
||||
LEFT JOIN users u ON u.id = j.user_id
|
||||
${where}
|
||||
ORDER BY j.id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}`,
|
||||
params
|
||||
);
|
||||
const { rows: countRows } = await pool.query(
|
||||
`SELECT count(*)::int AS total FROM quiz_ai_jobs j ${where}`,
|
||||
own ? [user.id] : []
|
||||
);
|
||||
return { items: rows.map(historyJob), total: countRows[0] ? countRows[0].total : 0 };
|
||||
}
|
||||
|
||||
async function ensureQuizAiJobsTable(pool) {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_ai_jobs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
prompt TEXT NOT NULL,
|
||||
kind VARCHAR(16) NOT NULL DEFAULT 'test',
|
||||
question_count INT NOT NULL DEFAULT 10,
|
||||
difficulty VARCHAR(16) NOT NULL DEFAULT 'medium',
|
||||
profile TEXT NOT NULL DEFAULT '',
|
||||
status VARCHAR(16) NOT NULL DEFAULT 'pending',
|
||||
attempts INT NOT NULL DEFAULT 0,
|
||||
quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL,
|
||||
questions INT,
|
||||
model TEXT,
|
||||
error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
finished_at TIMESTAMPTZ
|
||||
)`);
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS profile TEXT NOT NULL DEFAULT \'\'');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS quiz_id INT REFERENCES quizzes(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS questions INT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS model TEXT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS error TEXT');
|
||||
await pool.query('ALTER TABLE quiz_ai_jobs ADD COLUMN IF NOT EXISTS finished_at TIMESTAMPTZ');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_status ON quiz_ai_jobs(status, id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_ai_jobs_user ON quiz_ai_jobs(user_id, status)');
|
||||
}
|
||||
|
||||
async function createQuizAiJob(pool, user, request) {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO quiz_ai_jobs (user_id, prompt, kind, question_count, difficulty, profile)
|
||||
VALUES ($1, $2, $3, $4, $5, $6)
|
||||
RETURNING *`,
|
||||
[user.id, request.prompt, request.kind, request.count, request.difficulty, request.profile]
|
||||
);
|
||||
return publicJob(rows[0]);
|
||||
}
|
||||
|
||||
async function findActiveQuizAiJob(pool, userId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT * FROM quiz_ai_jobs
|
||||
WHERE user_id = $1 AND status IN ('pending', 'processing')
|
||||
ORDER BY id DESC LIMIT 1`,
|
||||
[userId]
|
||||
);
|
||||
return rows.length ? publicJob(rows[0]) : null;
|
||||
}
|
||||
|
||||
async function getQuizAiJob(pool, id, user) {
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_ai_jobs WHERE id = $1', [id]);
|
||||
if (!rows.length) return null;
|
||||
const row = rows[0];
|
||||
if (user.role !== 'admin' && Number(row.user_id) !== Number(user.id)) return null;
|
||||
return publicJob(row);
|
||||
}
|
||||
|
||||
async function claimQuizAiJob(pool) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows } = await client.query(
|
||||
`SELECT id, user_id, prompt, kind, question_count, difficulty, profile
|
||||
FROM quiz_ai_jobs
|
||||
WHERE status = 'pending'
|
||||
ORDER BY id ASC LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED`
|
||||
);
|
||||
if (!rows.length) {
|
||||
await client.query('COMMIT');
|
||||
return null;
|
||||
}
|
||||
await client.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'processing', attempts = attempts + 1, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[rows[0].id]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return rows[0];
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function finishQuizAiJob(pool, id, result) {
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'done', quiz_id = $2, questions = $3, model = $4,
|
||||
error = NULL, updated_at = now(), finished_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, result.quiz.id, result.questions, result.model]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function failQuizAiJob(pool, id, message) {
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE quiz_ai_jobs
|
||||
SET status = 'error', error = $2, updated_at = now(), finished_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[id, String(message || '').slice(0, 500)]
|
||||
);
|
||||
return rows[0] || null;
|
||||
}
|
||||
|
||||
async function resetStaleQuizAiJobs(pool) {
|
||||
await pool.query(`UPDATE quiz_ai_jobs SET status = 'pending', updated_at = now() WHERE status = 'processing'`);
|
||||
}
|
||||
|
||||
async function pruneQuizAiJobs(pool, days = PRUNE_DAYS) {
|
||||
const keep = Math.max(1, parseInt(days, 10) || PRUNE_DAYS);
|
||||
await pool.query(
|
||||
`DELETE FROM quiz_ai_jobs
|
||||
WHERE status IN ('done', 'error')
|
||||
AND updated_at < now() - ($1::int * interval '1 day')`,
|
||||
[keep]
|
||||
);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
ensureQuizAiJobsTable,
|
||||
createQuizAiJob,
|
||||
findActiveQuizAiJob,
|
||||
getQuizAiJob,
|
||||
listQuizAiJobs,
|
||||
claimQuizAiJob,
|
||||
finishQuizAiJob,
|
||||
failQuizAiJob,
|
||||
resetStaleQuizAiJobs,
|
||||
pruneQuizAiJobs,
|
||||
};
|
||||
+379
@@ -0,0 +1,379 @@
|
||||
'use strict';
|
||||
|
||||
const {
|
||||
createQuiz,
|
||||
saveQuiz,
|
||||
httpError,
|
||||
QUIZ_QUESTIONS_MAX,
|
||||
QUIZ_OPTIONS_MAX,
|
||||
QUIZ_TITLE_MAX,
|
||||
QUIZ_DESCRIPTION_MAX,
|
||||
QUIZ_TEXT_MAX,
|
||||
QUIZ_DESC_MAX,
|
||||
QUIZ_ANSWER_MAX,
|
||||
QUIZ_ACCEPTED_MAX,
|
||||
QUIZ_ACCEPTED_LEN,
|
||||
} = require('./quizzes');
|
||||
|
||||
const QUIZ_AI_PROMPT_MAX = 4000;
|
||||
const QUIZ_AI_QUESTIONS_DEFAULT = 10;
|
||||
const QUIZ_AI_QUESTIONS_MAX = 40;
|
||||
const QUIZ_AI_TIMEOUT_MS = 300000;
|
||||
const QUIZ_AI_DIFFICULTIES = new Set(['easy', 'medium', 'hard']);
|
||||
const QUIZ_AI_DIFFICULTY_LABELS = { easy: 'лёгкая', medium: 'средняя', hard: 'сложная' };
|
||||
|
||||
const QUIZ_AI_SYSTEM_PROMPT = [
|
||||
'Ты — методист образовательного центра и составляешь проверочные тесты и опросы по описанию пользователя.',
|
||||
'Верни ТОЛЬКО валидный JSON без markdown-разметки, без пояснений и без текста до или после него.',
|
||||
'Схема ответа:',
|
||||
'{"title":"string","description":"string","questions":[{"text":"string","kind":"single","description":"string","options":[{"text":"string","is_correct":true}],"accepted_answers":["string"]}]}',
|
||||
'Правила:',
|
||||
'- kind — один из: single (один верный вариант), multiple (несколько верных), select (выпадающий список), line (короткий свободный ответ), text (развёрнутый свободный ответ), number (число), date (дата).',
|
||||
'- Для single, multiple и select обязательно от 2 до 25 вариантов в options; у single и select ровно один вариант с is_correct = true; у multiple минимум один.',
|
||||
'- Для line, text, number и date options не нужны; в тесте можно указать accepted_answers — список допустимых ответов для автопроверки.',
|
||||
'- Не добавляй description в вопросах и вариантах, если пользователь прямо об этом не просил.',
|
||||
'- Формулируй вопросы и варианты кратко — до 120 символов, без вступлений и пояснений.',
|
||||
'- Все тексты на русском языке, без нумерации вида «1.», без LaTeX и без служебных пометок.',
|
||||
'- Не выдумывай факты, которых нет в описании; раскрывай тему по существу и формулируй вопросы однозначно.',
|
||||
].join('\n');
|
||||
|
||||
const KIND_ALIASES = {
|
||||
single: 'single',
|
||||
single_choice: 'single',
|
||||
singlechoice: 'single',
|
||||
radio: 'single',
|
||||
one: 'single',
|
||||
one_answer: 'single',
|
||||
multiple: 'multiple',
|
||||
multiple_choice: 'multiple',
|
||||
multiplechoice: 'multiple',
|
||||
checkbox: 'multiple',
|
||||
checkboxes: 'multiple',
|
||||
multi: 'multiple',
|
||||
select: 'select',
|
||||
dropdown: 'select',
|
||||
line: 'line',
|
||||
input: 'line',
|
||||
short: 'line',
|
||||
short_text: 'line',
|
||||
short_answer: 'line',
|
||||
text: 'text',
|
||||
long: 'text',
|
||||
long_text: 'text',
|
||||
textarea: 'text',
|
||||
free: 'text',
|
||||
number: 'number',
|
||||
numeric: 'number',
|
||||
int: 'number',
|
||||
integer: 'number',
|
||||
date: 'date',
|
||||
};
|
||||
|
||||
const FREE_KINDS = new Set(['line', 'text', 'number', 'date']);
|
||||
|
||||
function strOf(value, max) {
|
||||
if (value == null) return '';
|
||||
const text = String(value).replace(/\s+/g, ' ').trim();
|
||||
return text.length > max ? text.slice(0, max) : text;
|
||||
}
|
||||
|
||||
function blockOf(value, max) {
|
||||
if (value == null) return '';
|
||||
const text = String(value).replace(/\r\n/g, '\n').trim();
|
||||
return text.length > max ? text.slice(0, max) : text;
|
||||
}
|
||||
|
||||
function stripNumbering(text) {
|
||||
return String(text || '').replace(/^\s*\d+[.)]\s+/, '');
|
||||
}
|
||||
|
||||
function normKind(value) {
|
||||
const key = String(value || '').trim().toLowerCase().replace(/[\s-]+/g, '_');
|
||||
return KIND_ALIASES[key] || 'single';
|
||||
}
|
||||
|
||||
function clampCount(value) {
|
||||
const n = parseInt(value, 10);
|
||||
if (!Number.isFinite(n)) return QUIZ_AI_QUESTIONS_DEFAULT;
|
||||
return Math.max(1, Math.min(QUIZ_AI_QUESTIONS_MAX, n));
|
||||
}
|
||||
|
||||
function quizAiMaxTokens(count) {
|
||||
return Math.min(4096, Math.max(1024, count * 320 + 512));
|
||||
}
|
||||
|
||||
function quizAiUserPrompt({ prompt, kind, count, difficulty }) {
|
||||
const lines = [
|
||||
`Тема и требования пользователя: ${prompt}`,
|
||||
`Формат: ${kind === 'survey' ? 'опрос без правильных ответов' : 'тест с правильными ответами'}.`,
|
||||
`Количество вопросов: ${count}.`,
|
||||
`Сложность: ${QUIZ_AI_DIFFICULTY_LABELS[difficulty] || QUIZ_AI_DIFFICULTY_LABELS.medium}.`,
|
||||
];
|
||||
if (kind === 'survey') lines.push('В вопросах с вариантами не указывай is_correct — просто перечисли варианты.');
|
||||
else lines.push('Отметь правильные ответы is_correct = true и укажи accepted_answers там, где ответ вводится текстом.');
|
||||
lines.push('Ответ — только JSON по схеме, без пояснений.');
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
function stringField(text, key) {
|
||||
const re = new RegExp(`"${key}"\\s*:\\s*"((?:[^"\\\\]|\\\\.)*)"`);
|
||||
const m = re.exec(text);
|
||||
if (!m) return '';
|
||||
try {
|
||||
return JSON.parse('"' + m[1] + '"');
|
||||
} catch (e) {
|
||||
return m[1];
|
||||
}
|
||||
}
|
||||
|
||||
function salvageQuestions(text) {
|
||||
const qKey = text.indexOf('"questions"');
|
||||
const arrStart = qKey === -1 ? text.indexOf('[') : text.indexOf('[', qKey);
|
||||
if (arrStart === -1) return null;
|
||||
const objects = [];
|
||||
let depth = 0;
|
||||
let objStart = -1;
|
||||
let inString = false;
|
||||
let escaped = false;
|
||||
for (let i = arrStart + 1; i < text.length; i++) {
|
||||
const ch = text[i];
|
||||
if (inString) {
|
||||
if (escaped) escaped = false;
|
||||
else if (ch === '\\') escaped = true;
|
||||
else if (ch === '"') inString = false;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"') {
|
||||
inString = true;
|
||||
continue;
|
||||
}
|
||||
if (ch === '{') {
|
||||
if (depth === 0) objStart = i;
|
||||
depth++;
|
||||
} else if (ch === '}') {
|
||||
depth--;
|
||||
if (depth === 0 && objStart !== -1) {
|
||||
try {
|
||||
objects.push(JSON.parse(text.slice(objStart, i + 1)));
|
||||
} catch (e) {
|
||||
void e;
|
||||
}
|
||||
objStart = -1;
|
||||
}
|
||||
} else if (ch === ']' && depth === 0) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!objects.length) return null;
|
||||
return {
|
||||
title: stringField(text, 'title'),
|
||||
description: stringField(text, 'description'),
|
||||
questions: objects,
|
||||
};
|
||||
}
|
||||
|
||||
function extractJson(raw) {
|
||||
let text = String(raw || '').trim();
|
||||
text = text.replace(/^```[a-z]*\s*/i, '').replace(/\s*```$/i, '').trim();
|
||||
if (!text) throw httpError(502, 'Модель вернула пустой ответ');
|
||||
const objStart = text.indexOf('{');
|
||||
const arrStart = text.indexOf('[');
|
||||
const start = arrStart !== -1 && (objStart === -1 || arrStart < objStart) ? arrStart : objStart;
|
||||
if (start === -1) throw httpError(502, 'Модель вернула ответ без JSON');
|
||||
const close = text[start] === '{' ? '}' : ']';
|
||||
const end = text.lastIndexOf(close);
|
||||
if (end > start) {
|
||||
try {
|
||||
return JSON.parse(text.slice(start, end + 1));
|
||||
} catch (e) {
|
||||
void e;
|
||||
}
|
||||
}
|
||||
const salvaged = salvageQuestions(text);
|
||||
if (salvaged) return salvaged;
|
||||
throw httpError(502, 'Модель вернула повреждённый JSON');
|
||||
}
|
||||
|
||||
function normOptions(raw) {
|
||||
const list = raw.options ?? raw.answers ?? raw.variants ?? raw.choices ?? raw.items;
|
||||
if (!Array.isArray(list)) return [];
|
||||
const seen = new Set();
|
||||
const options = [];
|
||||
for (const item of list) {
|
||||
const source = typeof item === 'string' ? { text: item } : item;
|
||||
if (!source || typeof source !== 'object') continue;
|
||||
const text = stripNumbering(strOf(source.text ?? source.title ?? source.value ?? source.label, QUIZ_TEXT_MAX));
|
||||
if (!text) continue;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
options.push({ text, is_correct: source.is_correct === true || source.is_correct === 'true' || source.correct === true || source.correct === 'true' });
|
||||
if (options.length >= QUIZ_OPTIONS_MAX) break;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function normAccepted(raw) {
|
||||
const list = raw.accepted_answers ?? raw.acceptedAnswers ?? raw.correct_answers ?? raw.answers;
|
||||
if (!Array.isArray(list)) return [];
|
||||
const seen = new Set();
|
||||
const accepted = [];
|
||||
for (const item of list) {
|
||||
const text = strOf(typeof item === 'object' && item ? item.text : item, QUIZ_ACCEPTED_LEN);
|
||||
if (!text) continue;
|
||||
const key = text.toLowerCase();
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
accepted.push(text);
|
||||
if (accepted.length >= QUIZ_ACCEPTED_MAX) break;
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
function normQuestion(raw, quizKind) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const text = stripNumbering(blockOf(raw.text ?? raw.question ?? raw.title ?? raw.prompt, QUIZ_TEXT_MAX));
|
||||
if (!text) return null;
|
||||
const kind = normKind(raw.kind ?? raw.type ?? raw.question_type);
|
||||
const free = FREE_KINDS.has(kind);
|
||||
const question = {
|
||||
kind,
|
||||
text,
|
||||
description: blockOf(raw.description ?? raw.note, QUIZ_DESC_MAX) || null,
|
||||
weight: 1,
|
||||
partial_credit: false,
|
||||
required: true,
|
||||
min_length: 0,
|
||||
options_inline: false,
|
||||
text_match: 'exact',
|
||||
accepted_answers: [],
|
||||
asset_ids: [],
|
||||
options: [],
|
||||
};
|
||||
if (free) {
|
||||
if (quizKind === 'test') question.accepted_answers = normAccepted(raw);
|
||||
return question;
|
||||
}
|
||||
const options = normOptions(raw);
|
||||
if (options.length < 2) return null;
|
||||
if (quizKind === 'test') {
|
||||
const correct = options.filter(o => o.is_correct);
|
||||
if (kind === 'multiple') {
|
||||
if (!correct.length) options[0].is_correct = true;
|
||||
} else {
|
||||
const keep = correct[0] || options[0];
|
||||
options.forEach(o => { o.is_correct = o === keep; });
|
||||
}
|
||||
} else {
|
||||
options.forEach(o => { o.is_correct = false; });
|
||||
}
|
||||
question.options = options;
|
||||
return question;
|
||||
}
|
||||
|
||||
function normalizeDraft(raw, { kind, count, fallbackTitle }) {
|
||||
let body = raw;
|
||||
if (Array.isArray(body)) body = { questions: body };
|
||||
if (body && typeof body === 'object' && !Array.isArray(body.questions)) {
|
||||
const nested = body.quiz || body.test || body.survey || body.data;
|
||||
if (nested && typeof nested === 'object' && !Array.isArray(nested)) body = nested;
|
||||
}
|
||||
if (!body || typeof body !== 'object') throw httpError(502, 'Модель вернула неожиданный формат ответа');
|
||||
const list = Array.isArray(body.questions)
|
||||
? body.questions
|
||||
: Array.isArray(body.items)
|
||||
? body.items
|
||||
: Array.isArray(body.quiz)
|
||||
? body.quiz
|
||||
: [];
|
||||
const limit = Math.min(count, QUIZ_QUESTIONS_MAX);
|
||||
const questions = [];
|
||||
for (const item of list) {
|
||||
const question = normQuestion(item, kind);
|
||||
if (!question) continue;
|
||||
questions.push(question);
|
||||
if (questions.length >= limit) break;
|
||||
}
|
||||
if (!questions.length) throw httpError(502, 'Модель не вернула ни одного корректного вопроса');
|
||||
return {
|
||||
title: strOf(body.title ?? body.name, QUIZ_TITLE_MAX) || fallbackTitle,
|
||||
description: blockOf(body.description ?? body.summary, QUIZ_DESCRIPTION_MAX),
|
||||
questions,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeQuizAiRequest(body = {}) {
|
||||
const prompt = String(body.prompt ?? '').trim();
|
||||
if (!prompt) throw httpError(400, 'Опишите тему теста');
|
||||
if (prompt.length > QUIZ_AI_PROMPT_MAX) {
|
||||
throw httpError(400, `Описание не может быть длиннее ${QUIZ_AI_PROMPT_MAX} символов`);
|
||||
}
|
||||
const kind = body.kind === 'survey' ? 'survey' : 'test';
|
||||
const count = clampCount(body.count);
|
||||
const difficulty = QUIZ_AI_DIFFICULTIES.has(String(body.difficulty)) ? String(body.difficulty) : 'medium';
|
||||
const rawProfile = body.profile ?? body.model;
|
||||
const profile = rawProfile == null ? '' : String(rawProfile);
|
||||
return { prompt, kind, count, difficulty, profile };
|
||||
}
|
||||
|
||||
async function generateQuizDraft(pool, user, body, deps) {
|
||||
const request = normalizeQuizAiRequest(body);
|
||||
const { prompt, kind, count, difficulty, profile: profileId } = request;
|
||||
const profile = await deps.resolveProfile(profileId, user.id);
|
||||
if (profileId && profileId !== 'native' && !profile) throw httpError(400, 'Профиль ИИ не найден');
|
||||
let answer;
|
||||
try {
|
||||
answer = await deps.complete(
|
||||
QUIZ_AI_SYSTEM_PROMPT,
|
||||
quizAiUserPrompt({ prompt, kind, count, difficulty }),
|
||||
quizAiMaxTokens(count),
|
||||
profile,
|
||||
QUIZ_AI_TIMEOUT_MS
|
||||
);
|
||||
} catch (e) {
|
||||
if (e && e.name === 'AbortError') {
|
||||
throw httpError(504, `Модель не ответила за ${Math.round(QUIZ_AI_TIMEOUT_MS / 1000)} с — попробуйте меньше вопросов или другую модель`);
|
||||
}
|
||||
throw httpError(502, 'Сервис ИИ недоступен: ' + (e && e.message ? e.message : 'ошибка запроса'));
|
||||
}
|
||||
const fallbackTitle = kind === 'survey'
|
||||
? `Опрос: ${prompt.slice(0, 120)}`
|
||||
: `Тест: ${prompt.slice(0, 120)}`;
|
||||
const draft = normalizeDraft(extractJson(answer), { kind, count, fallbackTitle });
|
||||
const created = await createQuiz(pool, user, { kind, title: draft.title });
|
||||
const id = created.quiz.id;
|
||||
let saved;
|
||||
try {
|
||||
saved = await saveQuiz(pool, id, user, {
|
||||
kind,
|
||||
title: draft.title,
|
||||
description: draft.description || null,
|
||||
is_published: false,
|
||||
show_results: true,
|
||||
questions: draft.questions,
|
||||
});
|
||||
} catch (e) {
|
||||
await pool.query('DELETE FROM quizzes WHERE id = $1', [id]).catch(() => {});
|
||||
if (e && e.status) throw httpError(502, 'Модель вернула вопросы, которые не прошли проверку: ' + e.message);
|
||||
throw e;
|
||||
}
|
||||
return {
|
||||
quiz: { id, title: saved.quiz.title, kind: saved.quiz.kind },
|
||||
questions: draft.questions.length,
|
||||
model: profile ? profile.model : 'native',
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
QUIZ_AI_PROMPT_MAX,
|
||||
QUIZ_AI_QUESTIONS_DEFAULT,
|
||||
QUIZ_AI_QUESTIONS_MAX,
|
||||
QUIZ_AI_TIMEOUT_MS,
|
||||
QUIZ_AI_SYSTEM_PROMPT,
|
||||
quizAiMaxTokens,
|
||||
quizAiUserPrompt,
|
||||
extractJson,
|
||||
normalizeDraft,
|
||||
normalizeQuizAiRequest,
|
||||
generateQuizDraft,
|
||||
};
|
||||
@@ -0,0 +1,294 @@
|
||||
const GRADE_NAME_MAX = 200;
|
||||
const GRADE_DESC_MAX = 2000;
|
||||
const GRADE_LABEL_MAX = 200;
|
||||
const GRADE_RANGES_MAX = 30;
|
||||
const GRADE_SCORE_MAX = 100000;
|
||||
const GRADE_IMAGES_LIMIT = 300;
|
||||
|
||||
function gradeError(status, message) {
|
||||
const e = new Error(message);
|
||||
e.status = status;
|
||||
return e;
|
||||
}
|
||||
|
||||
function gradeText(v, max, label, required) {
|
||||
if (v === undefined || v === null) {
|
||||
if (required) throw gradeError(400, `${label}: обязательное поле`);
|
||||
return '';
|
||||
}
|
||||
if (typeof v !== 'string') throw gradeError(400, `${label}: неверный текст`);
|
||||
const s = v.trim();
|
||||
if (required && !s) throw gradeError(400, `${label}: обязательное поле`);
|
||||
if (s.length > max) throw gradeError(400, `${label}: максимум ${max} символов`);
|
||||
return s;
|
||||
}
|
||||
|
||||
function gradeScore(v, label) {
|
||||
if (v === undefined || v === null || v === '') throw gradeError(400, `${label}: обязательное поле`);
|
||||
const n = Number(v);
|
||||
if (!Number.isFinite(n) || n < 0 || n > GRADE_SCORE_MAX) throw gradeError(400, `Неверное значение: ${label}`);
|
||||
return Math.round(n * 100) / 100;
|
||||
}
|
||||
|
||||
function gradeImagePath(v, label) {
|
||||
if (v === undefined || v === null || v === '') return null;
|
||||
if (typeof v !== 'string' || !/^\/uploads\/[\w,.()-]+$/.test(v)) throw gradeError(400, `${label}: неверный путь к картинке`);
|
||||
return v;
|
||||
}
|
||||
|
||||
function normalizeRanges(list) {
|
||||
if (!Array.isArray(list)) return [];
|
||||
if (list.length > GRADE_RANGES_MAX) throw gradeError(400, `Диапазонов не больше ${GRADE_RANGES_MAX}`);
|
||||
return list.map((raw, i) => {
|
||||
const label = `Диапазон ${i + 1}`;
|
||||
if (!raw || typeof raw !== 'object') throw gradeError(400, `${label}: неверные данные`);
|
||||
const min = gradeScore(raw.min_score, `${label}: мин. балл`);
|
||||
const max = gradeScore(raw.max_score, `${label}: макс. балл`);
|
||||
if (max < min) throw gradeError(400, `${label}: макс. балл меньше минимального`);
|
||||
return {
|
||||
min_score: min,
|
||||
max_score: max,
|
||||
label: gradeText(raw.label, GRADE_LABEL_MAX, `${label}: результат`, true),
|
||||
image_path: gradeImagePath(raw.image_path, label),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizeScale(body) {
|
||||
const name = gradeText(body.name, GRADE_NAME_MAX, 'Название', true);
|
||||
const description = gradeText(body.description, GRADE_DESC_MAX, 'Описание', false) || null;
|
||||
const rawSort = body.sort_order;
|
||||
const sortOrder = rawSort === undefined || rawSort === null || rawSort === '' ? 0 : Number(rawSort);
|
||||
if (!Number.isFinite(sortOrder) || sortOrder < -100000 || sortOrder > 100000) {
|
||||
throw gradeError(400, 'Неверное значение: порядок сортировки');
|
||||
}
|
||||
const ranges = normalizeRanges(body.ranges);
|
||||
if (!ranges.length) throw gradeError(400, 'Добавьте хотя бы один диапазон баллов');
|
||||
return { name, description, sort_order: Math.trunc(sortOrder), ranges };
|
||||
}
|
||||
|
||||
function rangeToJson(row) {
|
||||
return {
|
||||
id: row.id,
|
||||
min_score: Number(row.min_score),
|
||||
max_score: Number(row.max_score),
|
||||
label: row.label,
|
||||
image_path: row.image_path || null,
|
||||
};
|
||||
}
|
||||
|
||||
function scaleToJson(row, ranges) {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
description: row.description || null,
|
||||
sort_order: row.sort_order,
|
||||
created_by: row.created_by,
|
||||
created_at: row.created_at,
|
||||
updated_at: row.updated_at,
|
||||
ranges: ranges || [],
|
||||
};
|
||||
}
|
||||
|
||||
async function ensureQuizGradeTables(pool) {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_grade_scales (
|
||||
id SERIAL PRIMARY KEY,
|
||||
name VARCHAR(200) NOT NULL DEFAULT '',
|
||||
description TEXT,
|
||||
sort_order INT NOT NULL DEFAULT 0,
|
||||
created_by INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_grade_ranges (
|
||||
id SERIAL PRIMARY KEY,
|
||||
scale_id INT NOT NULL REFERENCES quiz_grade_scales(id) ON DELETE CASCADE,
|
||||
min_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
max_score NUMERIC(8,2) NOT NULL DEFAULT 0,
|
||||
label VARCHAR(200) NOT NULL DEFAULT '',
|
||||
image_path TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id)');
|
||||
}
|
||||
|
||||
async function listGradeScales(pool) {
|
||||
const { rows: scales } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_scales ORDER BY sort_order ASC, id ASC'
|
||||
);
|
||||
if (!scales.length) return [];
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_ranges ORDER BY scale_id ASC, min_score ASC, id ASC'
|
||||
);
|
||||
const map = new Map();
|
||||
for (const r of ranges) {
|
||||
if (!map.has(r.scale_id)) map.set(r.scale_id, []);
|
||||
map.get(r.scale_id).push(rangeToJson(r));
|
||||
}
|
||||
return scales.map(s => scaleToJson(s, map.get(s.id) || []));
|
||||
}
|
||||
|
||||
async function getGradeScale(pool, id) {
|
||||
const { rows } = await pool.query('SELECT * FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!rows.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
const { rows: ranges } = await pool.query(
|
||||
'SELECT * FROM quiz_grade_ranges WHERE scale_id = $1 ORDER BY min_score ASC, id ASC',
|
||||
[id]
|
||||
);
|
||||
return scaleToJson(rows[0], ranges.map(rangeToJson));
|
||||
}
|
||||
|
||||
async function assertUniqueName(client, name, excludeId) {
|
||||
const { rows } = await client.query(
|
||||
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1',
|
||||
[name, excludeId || 0]
|
||||
);
|
||||
if (rows.length) throw gradeError(400, 'Критерий с таким названием уже есть');
|
||||
}
|
||||
|
||||
async function insertRanges(client, scaleId, ranges) {
|
||||
for (const r of ranges) {
|
||||
await client.query(
|
||||
`INSERT INTO quiz_grade_ranges (scale_id, min_score, max_score, label, image_path)
|
||||
VALUES ($1,$2,$3,$4,$5)`,
|
||||
[scaleId, r.min_score, r.max_score, r.label, r.image_path]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async function unusedImages(client, candidates) {
|
||||
const list = [...new Set((candidates || []).filter(Boolean))];
|
||||
if (!list.length) return [];
|
||||
const { rows } = await client.query(
|
||||
'SELECT DISTINCT image_path FROM quiz_grade_ranges WHERE image_path = ANY($1::text[])',
|
||||
[list]
|
||||
);
|
||||
const used = new Set(rows.map(r => r.image_path));
|
||||
return list.filter(p => !used.has(p));
|
||||
}
|
||||
|
||||
async function createGradeScale(pool, user, body = {}) {
|
||||
const data = normalizeScale(body);
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await assertUniqueName(client, data.name, 0);
|
||||
const { rows } = await client.query(
|
||||
'INSERT INTO quiz_grade_scales (name, description, sort_order, created_by) VALUES ($1,$2,$3,$4) RETURNING *',
|
||||
[data.name, data.description, data.sort_order, user.id]
|
||||
);
|
||||
await insertRanges(client, rows[0].id, data.ranges);
|
||||
await client.query('COMMIT');
|
||||
return { item: await getGradeScale(pool, rows[0].id) };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function updateGradeScale(pool, id, body = {}) {
|
||||
const data = normalizeScale(body);
|
||||
const client = await pool.connect();
|
||||
let removed = [];
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows: existing } = await client.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!existing.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
await assertUniqueName(client, data.name, id);
|
||||
const { rows: oldRanges } = await client.query(
|
||||
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
|
||||
[id]
|
||||
);
|
||||
await client.query(
|
||||
'UPDATE quiz_grade_scales SET name = $2, description = $3, sort_order = $4, updated_at = now() WHERE id = $1',
|
||||
[id, data.name, data.description, data.sort_order]
|
||||
);
|
||||
await client.query('DELETE FROM quiz_grade_ranges WHERE scale_id = $1', [id]);
|
||||
await insertRanges(client, id, data.ranges);
|
||||
removed = await unusedImages(client, oldRanges.map(r => r.image_path));
|
||||
await client.query('COMMIT');
|
||||
return { item: await getGradeScale(pool, id), removed };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteGradeScale(pool, id) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const { rows: existing } = await client.query('SELECT id FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
if (!existing.length) throw gradeError(404, 'Критерий оценки не найден');
|
||||
const { rows: oldRanges } = await client.query(
|
||||
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
|
||||
[id]
|
||||
);
|
||||
await client.query('DELETE FROM quiz_grade_scales WHERE id = $1', [id]);
|
||||
const removed = await unusedImages(client, oldRanges.map(r => r.image_path));
|
||||
await client.query('COMMIT');
|
||||
return { removed };
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw e;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
function gradeForScore(ranges, score) {
|
||||
const value = Number(score);
|
||||
if (!Number.isFinite(value)) return null;
|
||||
for (const r of ranges || []) {
|
||||
const min = Number(r.min_score);
|
||||
const max = Number(r.max_score);
|
||||
if (value >= min && value <= max) {
|
||||
return {
|
||||
label: r.label,
|
||||
image_path: r.image_path || null,
|
||||
min_score: min,
|
||||
max_score: max,
|
||||
};
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function listGradeImages(pool, limit) {
|
||||
const max = Math.min(Math.max(Number(limit) || GRADE_IMAGES_LIMIT, 1), GRADE_IMAGES_LIMIT);
|
||||
const { rows } = await pool.query(
|
||||
`SELECT path FROM (
|
||||
SELECT path FROM doc_images
|
||||
UNION SELECT photo_path AS path FROM bookmarks WHERE photo_path IS NOT NULL
|
||||
UNION SELECT photo_path AS path FROM student_photos
|
||||
UNION SELECT photo_path AS path FROM group_photos
|
||||
UNION SELECT photo_path AS path FROM entry_photos
|
||||
UNION SELECT path FROM quiz_assets WHERE path ~* '\\.(jpe?g|png|gif|webp|bmp|avif|heic|heif|jfif|ico)$'
|
||||
UNION SELECT image_path AS path FROM quiz_grade_ranges WHERE image_path IS NOT NULL
|
||||
) t
|
||||
WHERE path LIKE '/uploads/%'
|
||||
ORDER BY path DESC
|
||||
LIMIT $1`,
|
||||
[max]
|
||||
);
|
||||
return rows.map(r => r.path);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
GRADE_NAME_MAX,
|
||||
GRADE_LABEL_MAX,
|
||||
GRADE_RANGES_MAX,
|
||||
ensureQuizGradeTables,
|
||||
listGradeScales,
|
||||
getGradeScale,
|
||||
createGradeScale,
|
||||
updateGradeScale,
|
||||
deleteGradeScale,
|
||||
gradeForScore,
|
||||
listGradeImages,
|
||||
};
|
||||
+84
-26
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user