Тесты и опросы: критерии оценки, génération ИИ, улучшения конструктора и прохождения

- lib/quizzes.js: система criterial-оценки (quiz_grade_scales/quiz_grade_ranges), подсчёт баллов, попытки, anon-опросы, системные поля, доступ по коду
- lib/quiz-grades.js: CRUD критериев оценки, диапазоны, картинки
- lib/quiz-ai.js: генерация черновика теста через ИИ
- server.js: роуты тестов, критериев, медиа-ассетов, попыток
- db/init.sql + db/migration.sql: таблицы quizzes*, валидация и индексы
- public/: конструктор, прохождение, публичная страница, список, критерии оценки
- quiz.selftest.js, quiz-ai.selftest.js: юнит-проверки
This commit is contained in:
dev
2026-12-02 18:19:18 +03:00
parent cb2621d848
commit 646d352a9e
20 changed files with 822 additions and 151 deletions
+18 -17
View File
@@ -3,8 +3,6 @@
const fs = require('fs');
const path = require('path');
const storage = require('../storage');
const UPLOADS_DIR = path.join(__dirname, '..', 'uploads');
const THUMBS_DIR = path.join(UPLOADS_DIR, '.thumbs');
@@ -18,20 +16,24 @@ function thumbUnlinkFor(key) {
try { if (fs.existsSync(tp)) fs.unlinkSync(tp); } catch {}
}
function safeUnlink(relPath) {
const key = storage.keyFromPath(relPath);
if (!key) return;
storage.unlinkLocalOnly(key);
if (!storage.isRemote()) return;
storage.del(key).catch(err => console.error('Upload delete failed:', key, err.message));
}
function unlinkMedia(list) {
for (const p of list || []) {
if (!p) continue;
safeUnlink(p);
thumbUnlinkFor(p);
function createFileTools(storage) {
function safeUnlink(relPath) {
const key = storage.keyFromPath(relPath);
if (!key) return;
storage.unlinkLocalOnly(key);
if (!storage.isRemote()) return;
storage.del(key).catch(err => console.error('Upload delete failed:', key, err.message));
}
function unlinkMedia(list) {
for (const p of list || []) {
if (!p) continue;
safeUnlink(p);
thumbUnlinkFor(p);
}
}
return { safeUnlink, unlinkMedia };
}
module.exports = {
@@ -39,6 +41,5 @@ module.exports = {
THUMBS_DIR,
thumbFileFor,
thumbUnlinkFor,
safeUnlink,
unlinkMedia,
createFileTools,
};
+1 -1
View File
@@ -209,7 +209,7 @@ function normOptions(raw) {
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' });
options.push({ text, is_correct: source.is_correct === true || source.is_correct === 'true' || source.correct === true || source.correct === 'true', weight: 1 });
if (options.length >= QUIZ_OPTIONS_MAX) break;
}
return options;
+61 -18
View File
@@ -83,6 +83,7 @@ function scaleToJson(row, ranges) {
name: row.name,
description: row.description || null,
sort_order: row.sort_order,
is_shared: row.is_shared === true,
created_by: row.created_by,
created_at: row.created_at,
updated_at: row.updated_at,
@@ -96,10 +97,12 @@ async function ensureQuizGradeTables(pool) {
name VARCHAR(200) NOT NULL DEFAULT '',
description TEXT,
sort_order INT NOT NULL DEFAULT 0,
is_shared BOOLEAN NOT NULL DEFAULT false,
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('ALTER TABLE quiz_grade_scales ADD COLUMN IF NOT EXISTS is_shared BOOLEAN NOT NULL DEFAULT false');
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,
@@ -113,13 +116,21 @@ async function ensureQuizGradeTables(pool) {
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_grade_ranges_scale ON quiz_grade_ranges(scale_id)');
}
async function listGradeScales(pool) {
async function listGradeScales(pool, user) {
const isAdmin = user && user.role === 'admin';
const where = isAdmin
? ''
: ` WHERE (s.created_by = $1 OR (s.is_shared = TRUE AND EXISTS (
SELECT 1 FROM users u WHERE u.id = s.created_by AND u.role = 'admin')))`;
const params = isAdmin ? [] : [user ? user.id : 0];
const { rows: scales } = await pool.query(
'SELECT * FROM quiz_grade_scales ORDER BY sort_order ASC, id ASC'
`SELECT s.* FROM quiz_grade_scales s${where} ORDER BY s.sort_order ASC, s.id ASC`,
params
);
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'
'SELECT * FROM quiz_grade_ranges WHERE scale_id = ANY($1::int[]) ORDER BY scale_id ASC, min_score ASC, id ASC',
[scales.map(s => s.id)]
);
const map = new Map();
for (const r of ranges) {
@@ -139,14 +150,43 @@ async function getGradeScale(pool, id) {
return scaleToJson(rows[0], ranges.map(rangeToJson));
}
async function assertUniqueName(client, name, excludeId) {
async function assertUniqueName(client, name, excludeId, ownerId) {
const { rows } = await client.query(
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 LIMIT 1',
[name, excludeId || 0]
'SELECT id FROM quiz_grade_scales WHERE lower(name) = lower($1) AND id <> $2 AND created_by IS NOT DISTINCT FROM $3 LIMIT 1',
[name, excludeId || 0, ownerId == null ? null : ownerId]
);
if (rows.length) throw gradeError(400, 'Критерий с таким названием уже есть');
}
async function loadScaleForWrite(client, id, user) {
const { rows } = await client.query(
`SELECT s.id, s.created_by, s.is_shared, u.role AS owner_role
FROM quiz_grade_scales s LEFT JOIN users u ON u.id = s.created_by
WHERE s.id = $1`,
[id]
);
if (!rows.length) throw gradeError(404, 'Критерий оценки не найден');
const row = rows[0];
const isAdmin = user && user.role === 'admin';
const isOwner = user && row.created_by != null && Number(row.created_by) === Number(user.id);
if (!isAdmin && !isOwner) throw gradeError(403, 'Изменять можно только свои критерии оценки');
return row;
}
async function gradeScaleAccessible(pool, id, user) {
const { rows } = await pool.query(
`SELECT s.created_by, s.is_shared, u.role AS owner_role
FROM quiz_grade_scales s LEFT JOIN users u ON u.id = s.created_by
WHERE s.id = $1`,
[id]
);
if (!rows.length) return false;
if (user && user.role === 'admin') return true;
const row = rows[0];
if (user && row.created_by != null && Number(row.created_by) === Number(user.id)) return true;
return row.is_shared === true && row.owner_role === 'admin';
}
async function insertRanges(client, scaleId, ranges) {
for (const r of ranges) {
await client.query(
@@ -170,13 +210,14 @@ async function unusedImages(client, candidates) {
async function createGradeScale(pool, user, body = {}) {
const data = normalizeScale(body);
const isShared = user.role === 'admin' && body.is_shared === true;
const client = await pool.connect();
try {
await client.query('BEGIN');
await assertUniqueName(client, data.name, 0);
await assertUniqueName(client, data.name, 0, user.id);
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]
'INSERT INTO quiz_grade_scales (name, description, sort_order, is_shared, created_by) VALUES ($1,$2,$3,$4,$5) RETURNING *',
[data.name, data.description, data.sort_order, isShared, user.id]
);
await insertRanges(client, rows[0].id, data.ranges);
await client.query('COMMIT');
@@ -189,22 +230,24 @@ async function createGradeScale(pool, user, body = {}) {
}
}
async function updateGradeScale(pool, id, body = {}) {
async function updateGradeScale(pool, id, user, 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 existing = await loadScaleForWrite(client, id, user);
await assertUniqueName(client, data.name, id, existing.created_by);
const isShared = user.role === 'admin'
? (body.is_shared === undefined ? existing.is_shared === true : body.is_shared === true)
: existing.is_shared === true;
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]
'UPDATE quiz_grade_scales SET name = $2, description = $3, sort_order = $4, is_shared = $5, updated_at = now() WHERE id = $1',
[id, data.name, data.description, data.sort_order, isShared]
);
await client.query('DELETE FROM quiz_grade_ranges WHERE scale_id = $1', [id]);
await insertRanges(client, id, data.ranges);
@@ -219,12 +262,11 @@ async function updateGradeScale(pool, id, body = {}) {
}
}
async function deleteGradeScale(pool, id) {
async function deleteGradeScale(pool, id, user) {
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, 'Критерий оценки не найден');
await loadScaleForWrite(client, id, user);
const { rows: oldRanges } = await client.query(
'SELECT image_path FROM quiz_grade_ranges WHERE scale_id = $1',
[id]
@@ -289,6 +331,7 @@ module.exports = {
createGradeScale,
updateGradeScale,
deleteGradeScale,
gradeScaleAccessible,
gradeForScore,
listGradeImages,
};
+167 -31
View File
@@ -1,12 +1,15 @@
'use strict';
const crypto = require('crypto');
const { ensureQuizGradeTables, gradeForScore } = require('./quiz-grades');
const { ensureQuizGradeTables, gradeForScore, gradeScaleAccessible } = require('./quiz-grades');
const QUIZ_KINDS = new Set(['test', 'survey']);
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date']);
const QUESTION_KINDS = new Set(['single', 'multiple', 'select', 'line', 'text', 'number', 'date', 'student', 'group', 'branch', 'module']);
const OPTION_KINDS = new Set(['single', 'multiple', 'select']);
const FREE_KINDS = new Set(['line', 'text', 'number', 'date']);
const SYSTEM_FIELD_KINDS = new Set(['student', 'group', 'branch', 'module']);
const SYSTEM_FIELD_LABELS = { student: 'Ученик', group: 'Группа', branch: 'Филиал', module: 'Тема модуля' };
const QUIZ_ACCESS_CODE_MAX = 64;
const QUIZ_TITLE_MAX = 200;
const QUIZ_DESCRIPTION_MAX = 20000;
const QUIZ_TEXT_MAX = 5000;
@@ -19,6 +22,7 @@ const QUIZ_ASSETS_MAX = 10;
const QUIZ_WEIGHT_MAX = 100;
const QUIZ_MAX_ATTEMPTS_MAX = 1000;
const QUIZ_TIME_LIMIT_MAX = 1440;
const QUIZ_RETRY_COOLDOWN_MAX = 10080;
const QUIZ_ATTEMPT_ANSWERS_MAX = 500;
const QUIZ_ACCEPTED_MAX = 50;
const QUIZ_ACCEPTED_LEN = 200;
@@ -94,6 +98,32 @@ function normalizeQuestionKind(v) {
return QUESTION_KINDS.has(v) ? v : 'single';
}
function isFreeKind(kind) {
return FREE_KINDS.has(kind) || SYSTEM_FIELD_KINDS.has(kind);
}
function accessCodeValue(raw) {
if (raw == null) return null;
const value = String(raw).replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim();
if (!value) return null;
if (value.length > QUIZ_ACCESS_CODE_MAX) {
throw httpError(400, `Код доступа: максимум ${QUIZ_ACCESS_CODE_MAX} символов`);
}
return value;
}
function accessCodeMatches(expected, given) {
if (!expected) return true;
const a = crypto.createHash('sha256').update(String(expected), 'utf8').digest();
const b = crypto.createHash('sha256').update(String(given == null ? '' : given), 'utf8').digest();
return crypto.timingSafeEqual(a, b);
}
function normalizeAnswerId(value) {
const n = Number(value);
return Number.isInteger(n) && n > 0 ? n : null;
}
function normalizeAnswerText(v) {
return String(v == null ? '' : v)
.toLowerCase()
@@ -159,9 +189,11 @@ async function ensureQuizTables(pool) {
show_answers BOOLEAN NOT NULL DEFAULT true,
max_attempts INT,
time_limit_min INT NOT NULL DEFAULT 0,
retry_cooldown_min INT NOT NULL DEFAULT 0,
pass_percent INT NOT NULL DEFAULT 60,
cover_path TEXT,
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
access_code VARCHAR(64),
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(),
@@ -176,9 +208,11 @@ async function ensureQuizTables(pool) {
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 retry_cooldown_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 access_code VARCHAR(64)');
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');
@@ -189,7 +223,7 @@ async function ensureQuizTables(pool) {
kind VARCHAR(16) NOT NULL DEFAULT 'single',
text TEXT NOT NULL DEFAULT '',
description TEXT,
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
partial_credit BOOLEAN NOT NULL DEFAULT false,
required BOOLEAN NOT NULL DEFAULT true,
min_length INT NOT NULL DEFAULT 0,
@@ -201,7 +235,8 @@ async function ensureQuizTables(pool) {
)`);
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS kind VARCHAR(16) NOT NULL DEFAULT \'single\'');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS description TEXT');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 1');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quiz_questions ALTER COLUMN weight SET DEFAULT 0');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS partial_credit BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS required BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS text_match VARCHAR(16) NOT NULL DEFAULT \'exact\'');
@@ -215,13 +250,14 @@ async function ensureQuizTables(pool) {
text TEXT NOT NULL DEFAULT '',
description TEXT,
is_correct BOOLEAN NOT NULL DEFAULT false,
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
weight NUMERIC(6,2) NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`);
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS description TEXT');
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS is_correct BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 1');
await pool.query('ALTER TABLE quiz_options ADD COLUMN IF NOT EXISTS weight NUMERIC(6,2) NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quiz_options ALTER COLUMN weight SET DEFAULT 0');
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_assets (
id SERIAL PRIMARY KEY,
quiz_id INT REFERENCES quizzes(id) ON DELETE CASCADE,
@@ -270,12 +306,14 @@ async function ensureQuizTables(pool) {
option_ids INT[] NOT NULL DEFAULT '{}',
answer_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
text_answer TEXT,
answer_id INT,
is_correct BOOLEAN,
score NUMERIC(8,2) NOT NULL DEFAULT 0,
max_score NUMERIC(8,2) NOT NULL DEFAULT 0
)`);
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS question_text TEXT NOT NULL DEFAULT \'\'');
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_snapshot JSONB NOT NULL DEFAULT \'{}\'::jsonb');
await pool.query('ALTER TABLE quiz_attempt_answers ADD COLUMN IF NOT EXISTS answer_id INT');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_author ON quizzes(author_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_kind ON quizzes(kind, is_published)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quizzes_purge ON quizzes(purge_at) WHERE purge_at IS NOT NULL');
@@ -415,9 +453,11 @@ function quizMeta(row) {
show_answers: row.show_answers !== false,
max_attempts: row.max_attempts,
time_limit_min: row.time_limit_min,
retry_cooldown_min: Number(row.retry_cooldown_min) || 0,
pass_percent: row.pass_percent,
cover_path: row.cover_path,
allow_anonymous: row.allow_anonymous === true,
requires_code: !!(row.access_code && String(row.access_code).trim()),
grade_scale_id: row.grade_scale_id == null ? null : Number(row.grade_scale_id),
author_id: row.author_id,
created_at: row.created_at,
@@ -522,7 +562,11 @@ async function getQuiz(pool, id, user, opts = {}) {
authorName = u.rows[0]?.name || null;
}
return {
quiz: { ...quizMeta(row), author_name: authorName },
quiz: {
...quizMeta(row),
author_name: authorName,
access_code: editable ? (row.access_code || '') : null,
},
quiz_assets: structure.quiz_assets,
questions: structure.questions,
my_attempts: att.rows.map(r => ({
@@ -544,6 +588,7 @@ function normalizeMeta(body, current) {
const description = textValue(body.description, QUIZ_DESCRIPTION_MAX, 'Описание', false);
const passPercent = intValue(body.pass_percent, 0, 100, 'порог сдачи');
const timeLimit = intValue(body.time_limit_min, 0, QUIZ_TIME_LIMIT_MAX, 'лимит времени');
const retryCooldown = intValue(body.retry_cooldown_min, 0, QUIZ_RETRY_COOLDOWN_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;
@@ -553,6 +598,9 @@ function normalizeMeta(body, current) {
else if (typeof raw === 'string' && /^\/uploads\/[\w,.()-]+$/.test(raw)) coverPath = raw;
else throw httpError(400, 'Неверный путь к обложке');
}
const accessCode = body.access_code === undefined
? (current.access_code == null ? null : accessCodeValue(current.access_code))
: accessCodeValue(body.access_code);
return {
kind,
title,
@@ -568,8 +616,10 @@ function normalizeMeta(body, current) {
: (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,
retry_cooldown_min: retryCooldown == null ? (Number(current.retry_cooldown_min) || 0) : retryCooldown,
pass_percent: passPercent == null ? current.pass_percent : passPercent,
cover_path: coverPath,
access_code: accessCode,
};
}
@@ -578,16 +628,17 @@ function validateQuestion(q, quizKind, index) {
const kind = normalizeQuestionKind(q.kind);
const text = textValue(q.text, QUIZ_TEXT_MAX, `${label}: текст`, true);
const description = textValue(q.description, QUIZ_DESC_MAX, `${label}: описание`, false);
const weight = quizKind === 'test' ? numWeight(q.weight, 1) : 1;
const weight = quizKind === 'test' ? numWeight(q.weight, 0) : 1;
const required = asBool(q.required, true);
const free = FREE_KINDS.has(kind);
const free = isFreeKind(kind);
const plainFree = FREE_KINDS.has(kind);
const minLength = required && (kind === 'line' || kind === 'text')
? (intValue(q.min_length, 0, QUIZ_ANSWER_MAX, 'минимальная длина ответа') ?? 0)
: 0;
const optionsInline = !free && asBool(q.options_inline, false);
const partialCredit = quizKind === 'test' && kind === 'multiple' && asBool(q.partial_credit, false);
const textMatch = free ? normalizeTextMatch(q.text_match) : 'exact';
const acceptedAnswers = free && quizKind === 'test'
const textMatch = plainFree ? normalizeTextMatch(q.text_match) : 'exact';
const acceptedAnswers = plainFree && quizKind === 'test'
? normalizeAcceptedAnswers(q.accepted_answers)
: [];
const rawOptions = free || !Array.isArray(q.options) ? [] : q.options.slice(0, QUIZ_OPTIONS_MAX);
@@ -601,7 +652,7 @@ function validateQuestion(q, quizKind, index) {
text: textValue(o.text, QUIZ_TEXT_MAX, `${olabel}: текст`, true),
description: textValue(o.description, QUIZ_DESC_MAX, `${olabel}: описание`, false) || null,
is_correct: quizKind === 'test' ? asBool(o.is_correct, false) : false,
weight: quizKind === 'test' ? numWeight(o.weight, 1) : 1,
weight: quizKind === 'test' ? numWeight(o.weight, 0) : 1,
asset_ids: normalizeIdList(o.asset_ids, QUIZ_ASSETS_MAX),
};
});
@@ -689,7 +740,7 @@ async function saveQuestionOptions(client, quizId, user, questionId, q, removedP
const { rows: existing } = await client.query('SELECT id FROM quiz_options WHERE question_id = $1', [questionId]);
const existingIds = new Set(existing.map(r => r.id));
const kept = [];
const options = FREE_KINDS.has(q.kind) ? [] : q.options;
const options = isFreeKind(q.kind) ? [] : q.options;
for (let i = 0; i < options.length; i++) {
const o = options[i];
let oid = o.id && existingIds.has(o.id) ? o.id : null;
@@ -723,12 +774,15 @@ 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, 'Критерий оценки не найден');
if (meta.grade_scale_id != null && !(await gradeScaleAccessible(pool, meta.grade_scale_id, user))) {
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 hasSystemFields = questions.some(q => SYSTEM_FIELD_KINDS.has(q.kind));
if (meta.allow_anonymous && hasSystemFields && !meta.access_code) {
throw httpError(400, 'Для теста с системными полями задайте код доступа — его вводят перед прохождением по ссылке');
}
const quizAssetIds = normalizeIdList(body.asset_ids, QUIZ_ASSETS_MAX);
const removedPaths = [];
const client = await pool.connect();
@@ -738,11 +792,12 @@ async function saveQuiz(pool, id, user, body = {}) {
`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, show_answers = $14,
grade_scale_id = $15, updated_at = now()
grade_scale_id = $15, access_code = $16, retry_cooldown_min = $17, 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.show_answers, meta.grade_scale_id]
meta.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id,
meta.access_code, meta.retry_cooldown_min]
);
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));
@@ -911,7 +966,7 @@ async function deleteAsset(pool, id, user) {
function scoreTextAnswer(question, textAnswer) {
const accepted = Array.isArray(question.accepted_answers) ? question.accepted_answers : [];
if (!accepted.length) return { score: 0, max_score: 0, is_correct: null };
const qWeight = Number(question.weight == null ? 1 : question.weight);
const qWeight = Number(question.weight == null ? 0 : question.weight);
const maxScore = round2(qWeight);
let ok = false;
if (question.kind === 'number') {
@@ -937,17 +992,16 @@ function scoreTextAnswer(question, textAnswer) {
function scoreQuestion(question, selectedIds, textAnswer) {
const options = Array.isArray(question.options) ? question.options : [];
if (FREE_KINDS.has(question.kind)) return scoreTextAnswer(question, textAnswer);
if (isFreeKind(question.kind)) return scoreTextAnswer(question, textAnswer);
const selected = new Set((selectedIds || []).map(Number).filter(Number.isInteger));
const kind = question.kind;
const correct = options.filter(o => o.is_correct);
const maxRaw = correct.reduce((s, o) => s + Number(o.weight || 0), 0);
const qWeight = Number(question.weight == null ? 1 : question.weight);
const maxScore = round2(maxRaw * qWeight);
const maxScore = round2(maxRaw);
if (kind === 'single' || kind === 'select') {
const chosen = options.filter(o => selected.has(Number(o.id)));
const ok = chosen.length === 1 && chosen[0].is_correct === true;
return { score: ok ? round2(Number(chosen[0].weight || 0) * qWeight) : 0, max_score: maxScore, is_correct: ok };
return { score: ok ? round2(Number(chosen[0].weight || 0)) : 0, max_score: maxScore, is_correct: ok };
}
const exact = correct.length === selected.size && correct.every(o => selected.has(Number(o.id)));
if (!question.partial_credit) {
@@ -957,7 +1011,7 @@ function scoreQuestion(question, selectedIds, textAnswer) {
let raw = 0;
for (const o of chosen) raw += (o.is_correct ? 1 : -1) * Number(o.weight || 0);
raw = Math.max(0, Math.min(raw, maxRaw));
return { score: round2(raw * qWeight), max_score: maxScore, is_correct: exact };
return { score: round2(raw), max_score: maxScore, is_correct: exact };
}
async function startAttempt(pool, quizId, user) {
@@ -1011,6 +1065,7 @@ async function performSubmit(pool, row, attempt, body = {}) {
const quizId = Number(row.id);
const attemptId = Number(attempt.id);
const structure = await loadQuizStructure(pool, quizId);
const skipRequired = body.time_up === true;
const answers = Array.isArray(body.answers) ? body.answers.slice(0, QUIZ_ATTEMPT_ANSWERS_MAX) : [];
const byQuestion = new Map();
for (const a of answers) {
@@ -1026,13 +1081,18 @@ async function performSubmit(pool, row, attempt, body = {}) {
await client.query('BEGIN');
for (const q of structure.questions) {
const a = byQuestion.get(q.id) || {};
const free = FREE_KINDS.has(q.kind);
const free = isFreeKind(q.kind);
const optionIds = free ? [] : normalizeIdList(a.option_ids, QUIZ_OPTIONS_MAX);
const textAnswer = free
? textValue(a.text, QUIZ_ANSWER_MAX, 'Ответ', false)
: '';
if (free && q.required !== false && q.min_length > 0 && textAnswer.length < q.min_length) {
throw httpError(400, `Вопрос «${q.text}»: минимум ${q.min_length} символов`);
const answerId = SYSTEM_FIELD_KINDS.has(q.kind) ? normalizeAnswerId(a.answer_id) : null;
if (!skipRequired && q.required !== false) {
const answered = free ? (textAnswer !== '' || answerId != null) : optionIds.length > 0;
if (!answered) throw httpError(400, `Вопрос «${q.text}»: ответ обязателен`);
if (free && q.min_length > 0 && textAnswer.length < q.min_length) {
throw httpError(400, `Вопрос «${q.text}»: минимум ${q.min_length} символов`);
}
}
const res = row.kind === 'survey'
? { score: 0, max_score: 0, is_correct: null }
@@ -1054,11 +1114,15 @@ async function performSubmit(pool, row, attempt, body = {}) {
accepted_answers: q.accepted_answers,
selected: optionIds,
};
if (SYSTEM_FIELD_KINDS.has(q.kind)) {
snapshot.field = q.kind;
snapshot.answer_id = answerId;
}
await client.query(
`INSERT INTO quiz_attempt_answers (attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, is_correct, score, max_score)
VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9)`,
`INSERT INTO quiz_attempt_answers (attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, answer_id, is_correct, score, max_score)
VALUES ($1,$2,$3,$4,$5::jsonb,$6,$7,$8,$9,$10)`,
[attemptId, q.id, q.text, optionIds, JSON.stringify(snapshot), textAnswer || null,
res.is_correct, res.score, res.max_score]
answerId, res.is_correct, res.score, res.max_score]
);
results.push({
question_id: q.id,
@@ -1152,7 +1216,10 @@ async function getPublicQuiz(pool, quizId) {
delete meta.deleted_at;
delete meta.purge_at;
return {
quiz: meta,
quiz: {
...meta,
has_system_fields: structure.questions.some(q => SYSTEM_FIELD_KINDS.has(q.kind)),
},
quiz_assets: structure.quiz_assets,
questions: structure.questions,
};
@@ -1160,6 +1227,7 @@ async function getPublicQuiz(pool, quizId) {
async function startPublicAttempt(pool, quizId, opts = {}) {
const row = await findPublicQuiz(pool, quizId);
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null;
const token = crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex');
const { rows } = await pool.query(
@@ -1190,6 +1258,69 @@ async function submitPublicAttempt(pool, quizId, attemptId, token, body = {}) {
return performSubmit(pool, row, attempt, body);
}
async function lookupSystemOptions(pool, field, query, branchIds = null) {
if (!SYSTEM_FIELD_KINDS.has(field)) throw httpError(400, 'Неизвестное системное поле');
const term = String(query == null ? '' : query).trim().slice(0, 80);
const like = '%' + term.replace(/[\\%_]/g, ch => '\\' + ch) + '%';
const params = [like];
let branch = '';
if (Array.isArray(branchIds) && (field === 'student' || field === 'group' || field === 'branch')) {
params.push(branchIds.length ? branchIds : [0]);
const column = field === 'branch' ? 'b.id' : 'g.branch_id';
branch = ` AND ${column} = ANY($2::int[])`;
}
let sql;
if (field === 'student') {
sql = `SELECT s.id, s.name, g.name AS sub
FROM students s
LEFT JOIN groups g ON g.id = s.group_id
WHERE s.deleted_at IS NULL AND s.name ILIKE $1${branch}
ORDER BY s.name ASC
LIMIT 20`;
} else if (field === 'group') {
sql = `SELECT g.id, g.name, b.name AS sub
FROM groups g
LEFT JOIN branches b ON b.id = g.branch_id
WHERE g.deleted_at IS NULL AND g.hidden = false AND g.name ILIKE $1${branch}
ORDER BY g.name ASC
LIMIT 20`;
} else if (field === 'branch') {
sql = `SELECT b.id, b.name, NULL AS sub
FROM branches b
WHERE b.name ILIKE $1${branch}
ORDER BY b.name ASC
LIMIT 20`;
} else {
sql = `SELECT m.id, m.name, NULL AS sub
FROM modules m
WHERE m.is_active = true AND m.name ILIKE $1
ORDER BY m.name ASC
LIMIT 20`;
}
const { rows } = await pool.query(sql, params);
return { items: rows.map(r => ({ id: r.id, name: r.name, sub: r.sub || null })) };
}
async function lookupPublicQuizOptions(pool, quizId, opts = {}) {
const row = await findPublicQuiz(pool, quizId);
if (!row.access_code) throw httpError(403, 'Подсказки недоступны: автор не задал код доступа');
if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа');
let branchIds = null;
if (row.author_id != null) {
const { rows } = await pool.query(
`SELECT u.role, ub.branch_id
FROM users u
LEFT JOIN user_branches ub ON ub.user_id = u.id
WHERE u.id = $1`,
[row.author_id]
);
if (rows.length && rows[0].role !== 'admin') {
branchIds = rows.map(r => r.branch_id).filter(id => id != null);
}
}
return lookupSystemOptions(pool, opts.field, opts.query, branchIds);
}
async function listAttempts(pool, quizId, user, params = {}) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
@@ -1373,6 +1504,9 @@ module.exports = {
QUESTION_KINDS,
OPTION_KINDS,
FREE_KINDS,
SYSTEM_FIELD_KINDS,
SYSTEM_FIELD_LABELS,
QUIZ_ACCESS_CODE_MAX,
QUIZ_TITLE_MAX,
QUIZ_DESCRIPTION_MAX,
QUIZ_TEXT_MAX,
@@ -1409,6 +1543,8 @@ module.exports = {
getPublicQuiz,
startPublicAttempt,
submitPublicAttempt,
lookupSystemOptions,
lookupPublicQuizOptions,
normalizeAnswerText,
normalizeNumberValue,
normalizeDateValue,