Files
WhatIDo/lib/quizzes.js
T
dev ef4d7cc472 Тесты и опросы: генерация ИИ, критерии оценки, версия 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 под новый функционал тестов/опросов
2026-12-02 14:27:57 +03:00

1421 lines
60 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'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']);
const OPTION_KINDS = new Set(['single', 'multiple', 'select']);
const FREE_KINDS = new Set(['line', 'text', 'number', 'date']);
const QUIZ_TITLE_MAX = 200;
const QUIZ_DESCRIPTION_MAX = 20000;
const QUIZ_TEXT_MAX = 5000;
const QUIZ_DESC_MAX = 5000;
const QUIZ_ANSWER_MAX = 2000;
const QUIZ_CAPTION_MAX = 300;
const QUIZ_QUESTIONS_MAX = 100;
const QUIZ_OPTIONS_MAX = 25;
const QUIZ_ASSETS_MAX = 10;
const QUIZ_WEIGHT_MAX = 100;
const QUIZ_MAX_ATTEMPTS_MAX = 1000;
const QUIZ_TIME_LIMIT_MAX = 1440;
const QUIZ_ATTEMPT_ANSWERS_MAX = 500;
const QUIZ_ACCEPTED_MAX = 50;
const QUIZ_ACCEPTED_LEN = 200;
const QUIZ_TEXT_MATCHES = new Set(['exact', 'contains']);
const QUIZ_ANON_TOKEN_BYTES = 16;
const IMAGE_EXT = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'avif', 'heic', 'heif', 'jfif'];
const AUDIO_EXT = ['mp3', 'wav', 'ogg', 'oga', 'm4a', 'aac', 'flac', 'opus', 'weba'];
const VIDEO_EXT = ['mp4', 'm4v', 'webm', 'ogv', 'mov', 'mkv', 'avi'];
const FILE_EXT = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'md', 'csv', 'rtf', 'odt', 'ods', 'odp', 'zip', 'rar', '7z'];
const QUIZ_MEDIA_EXT = [...IMAGE_EXT, ...AUDIO_EXT, ...VIDEO_EXT, ...FILE_EXT];
function httpError(status, message) {
const err = new Error(message);
err.status = status;
return err;
}
function quizError(res, e, fallback, label) {
if (e && e.status) return res.status(e.status).json({ error: e.message });
if (e && (e.message === 'Invalid string' || e.message === 'Invalid string length' || e.message === 'Invalid integer')) {
return res.status(400).json({ error: 'Неверные данные' });
}
console.error(`${label}:`, e);
return res.status(500).json({ error: fallback });
}
function round2(n) {
return Math.round((Number(n) || 0) * 100) / 100;
}
function numWeight(v, fallback) {
const n = Number(v);
if (!Number.isFinite(n)) return fallback;
if (n < 0) return 0;
if (n > QUIZ_WEIGHT_MAX) return QUIZ_WEIGHT_MAX;
return round2(n);
}
function asBool(v, def) {
if (v === undefined || v === null) return def;
return v === true || v === 'true' || v === 1 || v === '1';
}
function textValue(v, max, label, required) {
if (v === undefined || v === null) {
if (required) throw httpError(400, `${label}: обязательное поле`);
return '';
}
if (typeof v !== 'string') throw httpError(400, `${label}: неверный текст`);
const s = v.trim();
if (required && !s) throw httpError(400, `${label}: обязательное поле`);
if (s.length > max) throw httpError(400, `${label}: максимум ${max} символов`);
return s;
}
function intValue(v, lo, hi, label) {
if (v === null || v === undefined || v === '') return null;
const n = Number(v);
if (!Number.isInteger(n) || n < lo || n > hi) throw httpError(400, `Неверное значение: ${label}`);
return n;
}
function mediaKind(fileName) {
const ext = String(fileName || '').toLowerCase().split('.').pop();
if (IMAGE_EXT.includes(ext)) return 'image';
if (AUDIO_EXT.includes(ext)) return 'audio';
if (VIDEO_EXT.includes(ext)) return 'video';
return 'file';
}
function normalizeQuestionKind(v) {
return QUESTION_KINDS.has(v) ? v : 'single';
}
function normalizeAnswerText(v) {
return String(v == null ? '' : v)
.toLowerCase()
.replace(/ё/g, 'е')
.replace(/\s+/g, ' ')
.trim()
.replace(/[.,;:!?]+$/g, '')
.trim();
}
function normalizeTextMatch(v) {
return QUIZ_TEXT_MATCHES.has(v) ? v : 'exact';
}
function normalizeNumberValue(v) {
const s = String(v == null ? '' : v).replace(/\s+/g, '').replace(',', '.');
if (!s) return null;
const n = Number(s);
return Number.isFinite(n) ? n : null;
}
function normalizeDateValue(v) {
const s = String(v == null ? '' : v).trim();
let m = s.match(/^(\d{4})-(\d{2})-(\d{2})$/);
if (m) return `${m[1]}-${m[2]}-${m[3]}`;
m = s.match(/^(\d{1,2})[.\/](\d{1,2})[.\/](\d{4})$/);
if (m) return `${m[3]}-${m[2].padStart(2, '0')}-${m[1].padStart(2, '0')}`;
return null;
}
function normalizeAcceptedAnswers(list) {
if (!Array.isArray(list)) return [];
const seen = new Set();
const out = [];
for (const raw of list) {
if (typeof raw !== 'string') continue;
const value = raw.trim().slice(0, QUIZ_ACCEPTED_LEN);
const key = normalizeAnswerText(value);
if (!key || seen.has(key)) continue;
seen.add(key);
out.push(value);
if (out.length >= QUIZ_ACCEPTED_MAX) break;
}
return out;
}
function normalizeIdList(list, max) {
if (!Array.isArray(list)) return [];
return [...new Set(list.map(Number).filter(n => Number.isInteger(n) && n > 0))].slice(0, 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 '',
description TEXT,
kind VARCHAR(16) NOT NULL DEFAULT 'test',
is_published BOOLEAN NOT NULL DEFAULT false,
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(),
deleted_at TIMESTAMPTZ,
purge_at TIMESTAMPTZ
)`);
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS kind VARCHAR(16) NOT NULL DEFAULT \'test\'');
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 (
id SERIAL PRIMARY KEY,
quiz_id INT NOT NULL REFERENCES quizzes(id) ON DELETE CASCADE,
sort_order INT NOT NULL DEFAULT 0,
kind VARCHAR(16) NOT NULL DEFAULT 'single',
text TEXT NOT NULL DEFAULT '',
description TEXT,
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
partial_credit BOOLEAN NOT NULL DEFAULT false,
required BOOLEAN NOT NULL DEFAULT true,
min_length INT NOT NULL DEFAULT 0,
options_inline BOOLEAN NOT NULL DEFAULT false,
text_match VARCHAR(16) NOT NULL DEFAULT 'exact',
accepted_answers TEXT[] NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
)`);
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 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\'');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS accepted_answers TEXT[] NOT NULL DEFAULT \'{}\'');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS min_length INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS options_inline BOOLEAN NOT NULL DEFAULT false');
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_options (
id SERIAL PRIMARY KEY,
question_id INT NOT NULL REFERENCES quiz_questions(id) ON DELETE CASCADE,
sort_order INT NOT NULL DEFAULT 0,
text TEXT NOT NULL DEFAULT '',
description TEXT,
is_correct BOOLEAN NOT NULL DEFAULT false,
weight NUMERIC(6,2) NOT NULL DEFAULT 1,
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(`CREATE TABLE IF NOT EXISTS quiz_assets (
id SERIAL PRIMARY KEY,
quiz_id INT REFERENCES quizzes(id) ON DELETE CASCADE,
question_id INT REFERENCES quiz_questions(id) ON DELETE CASCADE,
option_id INT REFERENCES quiz_options(id) ON DELETE CASCADE,
kind VARCHAR(16) NOT NULL DEFAULT 'file',
path TEXT NOT NULL,
original_name TEXT,
mime TEXT,
size_bytes BIGINT,
caption 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(),
CONSTRAINT quiz_assets_one_owner CHECK (num_nonnulls(quiz_id, question_id, option_id) <= 1)
)`);
await pool.query('ALTER TABLE quiz_assets ADD COLUMN IF NOT EXISTS caption TEXT');
await pool.query('ALTER TABLE quiz_assets ADD COLUMN IF NOT EXISTS sort_order INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE quiz_assets ADD COLUMN IF NOT EXISTS created_by INT REFERENCES users(id) ON DELETE SET NULL');
await pool.query(`DO $$ BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'quiz_assets_one_owner' AND conrelid = 'quiz_assets'::regclass) THEN
ALTER TABLE quiz_assets ADD CONSTRAINT quiz_assets_one_owner CHECK (num_nonnulls(quiz_id, question_id, option_id) <= 1) NOT VALID;
END IF;
END $$`);
await pool.query(`CREATE TABLE IF NOT EXISTS quiz_attempts (
id SERIAL PRIMARY KEY,
quiz_id INT NOT NULL REFERENCES quizzes(id) ON DELETE CASCADE,
user_id INT REFERENCES users(id) ON DELETE SET NULL,
status VARCHAR(16) NOT NULL DEFAULT 'in_progress',
score NUMERIC(8,2) NOT NULL DEFAULT 0,
max_score NUMERIC(8,2) NOT NULL DEFAULT 0,
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,
question_id INT REFERENCES quiz_questions(id) ON DELETE SET NULL,
question_text TEXT NOT NULL DEFAULT '',
option_ids INT[] NOT NULL DEFAULT '{}',
answer_snapshot JSONB NOT NULL DEFAULT '{}'::jsonb,
text_answer TEXT,
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('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');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_questions_quiz ON quiz_questions(quiz_id, sort_order)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_options_question ON quiz_options(question_id, sort_order)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_assets_quiz ON quiz_assets(quiz_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_assets_question ON quiz_assets(question_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_assets_option ON quiz_assets(option_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_assets_unbound ON quiz_assets(created_at) WHERE quiz_id IS NULL AND question_id IS NULL AND option_id IS NULL');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempts_quiz ON quiz_attempts(quiz_id, started_at)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempts_user ON quiz_attempts(user_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_attempt ON quiz_attempt_answers(attempt_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_question ON quiz_attempt_answers(question_id)');
}
function canEditQuiz(quiz, user) {
if (!quiz || !user) return false;
if (user.role === 'admin') return true;
if (quiz.author_id == null) return false;
return Number(quiz.author_id) === Number(user.id);
}
function quizWriteBlocked(res, quiz, user) {
if (canEditQuiz(quiz, user)) return false;
res.status(403).json({ error: 'Изменять тест может только автор или администратор' });
return true;
}
async function findQuizRow(pool, id, opts = {}) {
const { rows } = await pool.query('SELECT * FROM quizzes WHERE id = $1', [id]);
if (!rows.length) return null;
if (!opts.withDeleted && rows[0].deleted_at) return null;
return rows[0];
}
async function loadQuizStructure(pool, quizId) {
const { rows: questions } = await pool.query(
'SELECT * FROM quiz_questions WHERE quiz_id = $1 ORDER BY sort_order ASC, id ASC',
[quizId]
);
const ids = questions.map(q => q.id);
const idList = ids.length ? ids : [0];
const { rows: options } = await pool.query(
'SELECT * FROM quiz_options WHERE question_id = ANY($1::int[]) ORDER BY sort_order ASC, id ASC',
[idList]
);
const { rows: assets } = await pool.query(
`SELECT * FROM quiz_assets
WHERE quiz_id = $1
OR question_id = ANY($2::int[])
OR option_id IN (SELECT id FROM quiz_options WHERE question_id = ANY($2::int[]))
ORDER BY sort_order ASC, id ASC`,
[quizId, idList]
);
const assetRow = a => ({
id: a.id,
kind: a.kind,
path: a.path,
original_name: a.original_name,
mime: a.mime,
size_bytes: a.size_bytes == null ? null : Number(a.size_bytes),
caption: a.caption,
sort_order: a.sort_order,
});
const byQuestion = new Map();
const byOption = new Map();
const quizAssets = [];
for (const a of assets) {
if (a.question_id) {
if (!byQuestion.has(a.question_id)) byQuestion.set(a.question_id, []);
byQuestion.get(a.question_id).push(assetRow(a));
} else if (a.option_id) {
if (!byOption.has(a.option_id)) byOption.set(a.option_id, []);
byOption.get(a.option_id).push(assetRow(a));
} else if (a.quiz_id) {
quizAssets.push(assetRow(a));
}
}
const optsByQuestion = new Map();
for (const o of options) {
if (!optsByQuestion.has(o.question_id)) optsByQuestion.set(o.question_id, []);
optsByQuestion.get(o.question_id).push(o);
}
return {
quiz_assets: quizAssets,
questions: questions.map(q => ({
id: q.id,
kind: q.kind,
text: q.text,
description: q.description,
weight: Number(q.weight),
partial_credit: q.partial_credit === true,
required: q.required !== false,
min_length: Number(q.min_length) || 0,
options_inline: q.options_inline === true,
text_match: q.text_match === 'contains' ? 'contains' : 'exact',
accepted_answers: Array.isArray(q.accepted_answers) ? q.accepted_answers : [],
sort_order: q.sort_order,
assets: byQuestion.get(q.id) || [],
options: (optsByQuestion.get(q.id) || []).map(o => ({
id: o.id,
text: o.text,
description: o.description,
is_correct: o.is_correct === true,
weight: Number(o.weight),
sort_order: o.sort_order,
assets: byOption.get(o.id) || [],
})),
})),
};
}
function stripAnswers(structure) {
return {
quiz_assets: structure.quiz_assets,
questions: structure.questions.map(q => ({
...q,
weight: 0,
partial_credit: false,
text_match: 'exact',
accepted_answers: [],
options: q.options.map(o => ({ ...o, is_correct: false, weight: 0 })),
})),
};
}
function quizMeta(row) {
return {
id: row.id,
title: row.title,
description: row.description,
kind: row.kind,
is_published: row.is_published === true,
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,
deleted_at: row.deleted_at,
purge_at: row.purge_at,
};
}
async function listQuizzes(pool, user, params = {}) {
const kind = QUIZ_KINDS.has(params.kind) ? params.kind : null;
const search = typeof params.search === 'string' ? params.search.trim().slice(0, 200) : '';
const mine = asBool(params.mine, false);
const deleted = asBool(params.deleted, false);
const limit = Math.min(Math.max(parseInt(params.limit, 10) || 100, 1), 200);
const offset = Math.max(parseInt(params.offset, 10) || 0, 0);
const isAdmin = user.role === 'admin';
const where = [];
const args = [];
where.push(deleted ? 'q.deleted_at IS NOT NULL' : 'q.deleted_at IS NULL');
if (deleted && !isAdmin) {
args.push(user.id);
where.push(`q.author_id = $${args.length}`);
} else if (!deleted) {
if (mine) {
args.push(user.id);
where.push(`q.author_id = $${args.length}`);
} else if (!isAdmin) {
args.push(user.id);
where.push(`(q.is_published = true OR q.author_id = $${args.length})`);
}
}
if (kind) {
args.push(kind);
where.push(`q.kind = $${args.length}`);
}
if (search) {
args.push(`%${search}%`);
where.push(`(q.title ILIKE $${args.length} OR COALESCE(q.description, '') ILIKE $${args.length})`);
}
const whereSql = 'WHERE ' + where.join(' AND ');
const { rows } = await pool.query(
`SELECT q.*, u.name AS author_name,
(SELECT count(*)::int FROM quiz_questions qq WHERE qq.quiz_id = q.id) AS question_count,
(SELECT count(*)::int FROM quiz_attempts a WHERE a.quiz_id = q.id AND a.status = 'done') AS attempt_count,
(SELECT count(*)::int FROM quiz_attempts a WHERE a.quiz_id = q.id AND a.status = 'done' AND a.user_id = $${args.length + 1}) AS my_attempt_count
FROM quizzes q LEFT JOIN users u ON u.id = q.author_id
${whereSql}
ORDER BY q.updated_at DESC, q.id DESC
LIMIT $${args.length + 2} OFFSET $${args.length + 3}`,
[...args, user.id, limit, offset]
);
const totalRes = await pool.query(`SELECT count(*)::int AS c FROM quizzes q ${whereSql}`, args);
const items = rows.map(r => ({
...quizMeta(r),
author_name: r.author_name,
question_count: r.question_count,
attempt_count: r.attempt_count,
my_attempt_count: r.my_attempt_count,
can_edit: canEditQuiz(r, user),
can_take: r.is_published === true && !r.deleted_at,
}));
return { items, total: totalRes.rows[0].c };
}
async function createQuiz(pool, user, body = {}) {
const kind = body.kind === 'survey' ? 'survey' : 'test';
const title = typeof body.title === 'string' && body.title.trim()
? body.title.trim().slice(0, QUIZ_TITLE_MAX)
: (kind === 'survey' ? 'Новый опрос' : 'Новый тест');
const { rows } = await pool.query(
'INSERT INTO quizzes (title, description, kind, author_id) VALUES ($1, $2, $3, $4) RETURNING id',
[title, null, kind, user.id]
);
return getQuiz(pool, rows[0].id, user);
}
async function getQuiz(pool, id, user, opts = {}) {
const row = await findQuizRow(pool, id);
if (!row) throw httpError(404, 'Тест не найден');
const editable = canEditQuiz(row, user);
if (!editable && row.is_published !== true) throw httpError(404, 'Тест не найден');
let structure = await loadQuizStructure(pool, id);
if (!editable && !opts.withAnswers) structure = stripAnswers(structure);
const att = await pool.query(
`SELECT id, status, score, max_score, percent, passed, started_at, finished_at
FROM quiz_attempts WHERE quiz_id = $1 AND user_id = $2 AND status = 'done'
ORDER BY finished_at DESC NULLS LAST, id DESC`,
[id, user.id]
);
const doneCount = att.rowCount;
const attemptsLeft = row.max_attempts == null ? null : Math.max(0, row.max_attempts - doneCount);
const current = await pool.query(
`SELECT id, started_at FROM quiz_attempts
WHERE quiz_id = $1 AND user_id = $2 AND status = 'in_progress'
ORDER BY id DESC LIMIT 1`,
[id, user.id]
);
let authorName = null;
if (row.author_id != null) {
const u = await pool.query('SELECT name FROM users WHERE id = $1', [row.author_id]);
authorName = u.rows[0]?.name || null;
}
return {
quiz: { ...quizMeta(row), author_name: authorName },
quiz_assets: structure.quiz_assets,
questions: structure.questions,
my_attempts: att.rows.map(r => ({
...r,
score: Number(r.score),
max_score: Number(r.max_score),
percent: Number(r.percent),
})),
current_attempt: current.rows[0] || null,
attempts_left: attemptsLeft,
can_edit: editable,
can_take: row.is_published === true && !row.deleted_at && (row.max_attempts == null || attemptsLeft > 0),
};
}
function normalizeMeta(body, current) {
const kind = body.kind === 'survey' || body.kind === 'test' ? body.kind : current.kind;
const title = textValue(body.title, QUIZ_TITLE_MAX, 'Название', true);
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 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;
if (raw == null || raw === '') coverPath = null;
else if (typeof raw === 'string' && /^\/uploads\/[\w,.()-]+$/.test(raw)) coverPath = raw;
else throw httpError(400, 'Неверный путь к обложке');
}
return {
kind,
title,
description: description || null,
is_published: asBool(body.is_published, current.is_published === true),
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),
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,
cover_path: coverPath,
};
}
function validateQuestion(q, quizKind, index) {
const label = `Вопрос ${index + 1}`;
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 required = asBool(q.required, true);
const free = 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'
? normalizeAcceptedAnswers(q.accepted_answers)
: [];
const rawOptions = free || !Array.isArray(q.options) ? [] : q.options.slice(0, QUIZ_OPTIONS_MAX);
if (!free && rawOptions.length < 2) {
throw httpError(400, `${label}: нужно минимум два варианта ответа`);
}
const options = rawOptions.map((o, oi) => {
const olabel = `${label}, вариант ${oi + 1}`;
return {
id: intValue(o.id, 1, Number.MAX_SAFE_INTEGER, `${olabel}: id`),
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,
asset_ids: normalizeIdList(o.asset_ids, QUIZ_ASSETS_MAX),
};
});
if (quizKind === 'test' && !free) {
const correct = options.filter(o => o.is_correct).length;
if ((kind === 'single' || kind === 'select') && correct !== 1) {
throw httpError(400, `${label}: отметьте ровно один правильный ответ`);
}
if (kind === 'multiple' && correct < 1) throw httpError(400, `${label}: отметьте хотя бы один правильный ответ`);
}
return {
id: intValue(q.id, 1, Number.MAX_SAFE_INTEGER, `${label}: id`),
kind,
text,
description: description || null,
weight,
partial_credit: partialCredit,
required,
min_length: minLength,
options_inline: optionsInline,
text_match: textMatch,
accepted_answers: acceptedAnswers,
asset_ids: normalizeIdList(q.asset_ids, QUIZ_ASSETS_MAX),
options,
};
}
async function collectAssetPaths(client, whereSql, params) {
const { rows } = await client.query(`SELECT path FROM quiz_assets WHERE ${whereSql}`, params);
return rows.map(r => r.path).filter(Boolean);
}
async function bindAssets(client, quizId, user, owner, ownerId, ids, removedPaths) {
const targetQuiz = owner === 'quiz' ? quizId : null;
const targetQuestion = owner === 'question' ? ownerId : null;
const targetOption = owner === 'option' ? ownerId : null;
if (ids.length) {
const { rows } = await client.query(
`SELECT a.id, a.quiz_id, a.created_by,
(SELECT qz.quiz_id FROM quiz_questions qz WHERE qz.id = a.question_id) AS question_quiz,
(SELECT qz.quiz_id FROM quiz_options o JOIN quiz_questions qz ON qz.id = o.question_id WHERE o.id = a.option_id) AS option_quiz
FROM quiz_assets a
WHERE a.id = ANY($1::int[])`,
[ids]
);
const allowed = [];
for (const a of rows) {
if (user.role !== 'admin' && a.created_by != null && Number(a.created_by) !== Number(user.id)) continue;
const boundQuiz = a.quiz_id != null
? Number(a.quiz_id)
: a.question_quiz != null
? Number(a.question_quiz)
: a.option_quiz != null
? Number(a.option_quiz)
: null;
if (boundQuiz != null && boundQuiz !== Number(quizId)) continue;
allowed.push(a.id);
}
if (allowed.length) {
await client.query(
'UPDATE quiz_assets SET quiz_id = $2, question_id = $3, option_id = $4 WHERE id = ANY($1::int[])',
[allowed, targetQuiz, targetQuestion, targetOption]
);
}
}
const idList = ids.length ? ids : [0];
let del;
if (owner === 'quiz') {
del = await client.query(
`DELETE FROM quiz_assets WHERE quiz_id = $1 AND question_id IS NULL AND option_id IS NULL
AND NOT (id = ANY($2::int[])) RETURNING path`,
[quizId, idList]
);
} else {
const column = owner === 'question' ? 'question_id' : 'option_id';
del = await client.query(
`DELETE FROM quiz_assets WHERE ${column} = $1 AND NOT (id = ANY($2::int[])) RETURNING path`,
[ownerId, idList]
);
}
del.rows.forEach(r => { if (r.path) removedPaths.push(r.path); });
}
async function saveQuestionOptions(client, quizId, user, questionId, q, removedPaths) {
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;
for (let i = 0; i < options.length; i++) {
const o = options[i];
let oid = o.id && existingIds.has(o.id) ? o.id : null;
if (oid) {
await client.query(
`UPDATE quiz_options SET sort_order = $2, text = $3, description = $4, is_correct = $5, weight = $6, updated_at = now()
WHERE id = $1 AND question_id = $7`,
[oid, i, o.text, o.description, o.is_correct, o.weight, questionId]
);
} else {
const ins = await client.query(
`INSERT INTO quiz_options (question_id, sort_order, text, description, is_correct, weight)
VALUES ($1,$2,$3,$4,$5,$6) RETURNING id`,
[questionId, i, o.text, o.description, o.is_correct, o.weight]
);
oid = ins.rows[0].id;
}
kept.push(oid);
await bindAssets(client, quizId, user, 'option', oid, o.asset_ids, removedPaths);
}
const gone = existing.map(r => r.id).filter(id => !kept.includes(id));
if (gone.length) {
const paths = await collectAssetPaths(client, 'option_id = ANY($1::int[])', [gone]);
paths.forEach(p => removedPaths.push(p));
await client.query('DELETE FROM quiz_options WHERE id = ANY($1::int[])', [gone]);
}
}
async function saveQuiz(pool, id, user, body = {}) {
const row = await findQuizRow(pool, id);
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);
const removedPaths = [];
const client = await pool.connect();
try {
await client.query('BEGIN');
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, 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.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));
const keptQ = [];
for (let i = 0; i < questions.length; i++) {
const q = questions[i];
let qid = q.id && existingQIds.has(q.id) ? q.id : null;
if (qid) {
await client.query(
`UPDATE quiz_questions SET sort_order = $2, kind = $3, text = $4, description = $5,
weight = $6, partial_credit = $7, required = $8, min_length = $12,
options_inline = $13, text_match = $10, accepted_answers = $11::text[], updated_at = now()
WHERE id = $1 AND quiz_id = $9`,
[qid, i, q.kind, q.text, q.description, q.weight, q.partial_credit, q.required, id,
q.text_match, q.accepted_answers, q.min_length, q.options_inline]
);
} else {
const ins = await client.query(
`INSERT INTO quiz_questions (quiz_id, sort_order, kind, text, description, weight, partial_credit, required, text_match, accepted_answers, min_length, options_inline)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::text[],$11,$12) RETURNING id`,
[id, i, q.kind, q.text, q.description, q.weight, q.partial_credit, q.required,
q.text_match, q.accepted_answers, q.min_length, q.options_inline]
);
qid = ins.rows[0].id;
}
keptQ.push(qid);
await saveQuestionOptions(client, id, user, qid, q, removedPaths);
await bindAssets(client, id, user, 'question', qid, q.asset_ids, removedPaths);
}
const goneQ = existingQ.map(r => r.id).filter(qid => !keptQ.includes(qid));
if (goneQ.length) {
const paths = await collectAssetPaths(
client,
'question_id = ANY($1::int[]) OR option_id IN (SELECT id FROM quiz_options WHERE question_id = ANY($1::int[]))',
[goneQ]
);
paths.forEach(p => removedPaths.push(p));
await client.query('DELETE FROM quiz_questions WHERE id = ANY($1::int[])', [goneQ]);
}
await bindAssets(client, id, user, 'quiz', id, quizAssetIds, removedPaths);
await client.query('COMMIT');
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
return { ...(await getQuiz(pool, id, user)), removed: [...new Set(removedPaths)] };
}
async function softDeleteQuiz(pool, id, user, days) {
const row = await findQuizRow(pool, id);
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Удалить тест может только автор или администратор');
if (row.deleted_at) throw httpError(400, 'Тест уже удалён');
const d = Math.max(1, Math.min(3650, Number(days) || 30));
await pool.query(
`UPDATE quizzes SET deleted_at = now(), purge_at = now() + ($2 || ' days')::interval WHERE id = $1`,
[id, d]
);
return { id, purge_days: d };
}
async function restoreQuiz(pool, id, user) {
const row = await findQuizRow(pool, id, { withDeleted: true });
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Восстановить тест может только автор или администратор');
if (!row.deleted_at) throw httpError(400, 'Тест не удалён');
await pool.query('UPDATE quizzes SET deleted_at = NULL, purge_at = NULL, updated_at = now() WHERE id = $1', [id]);
return { id };
}
async function deleteQuizPermanent(pool, id, user) {
const row = await findQuizRow(pool, id, { withDeleted: true });
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Удалить тест может только автор или администратор');
const { rows: assets } = await pool.query(
`SELECT path FROM quiz_assets
WHERE quiz_id = $1
OR question_id IN (SELECT id FROM quiz_questions WHERE quiz_id = $1)
OR option_id IN (SELECT o.id FROM quiz_options o JOIN quiz_questions q ON q.id = o.question_id WHERE q.quiz_id = $1)`,
[id]
);
const paths = assets.map(a => a.path).filter(Boolean);
if (row.cover_path) paths.push(row.cover_path);
await pool.query('DELETE FROM quizzes WHERE id = $1', [id]);
return { paths };
}
async function setCover(pool, id, user, coverPath) {
const row = await findQuizRow(pool, id);
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Изменять тест может только автор или администратор');
let next = null;
if (coverPath) {
if (typeof coverPath !== 'string' || !/^\/uploads\/[\w,.()-]+$/.test(coverPath)) {
throw httpError(400, 'Неверный путь к обложке');
}
next = coverPath;
}
await pool.query('UPDATE quizzes SET cover_path = $2, updated_at = now() WHERE id = $1', [id, next]);
return { old: row.cover_path, cover_path: next };
}
function assetPublic(a) {
return {
id: a.id,
kind: a.kind,
path: a.path,
original_name: a.original_name,
mime: a.mime,
size_bytes: a.size_bytes == null ? null : Number(a.size_bytes),
caption: a.caption,
sort_order: a.sort_order,
};
}
async function assertAssetAccess(pool, asset, user) {
if (user.role === 'admin') return;
if (asset.created_by != null && Number(asset.created_by) === Number(user.id)) return;
if (asset.quiz_id != null) {
const { rows } = await pool.query('SELECT author_id FROM quizzes WHERE id = $1', [asset.quiz_id]);
if (rows.length && Number(rows[0].author_id) === Number(user.id)) return;
}
throw httpError(403, 'Нет доступа к файлу');
}
async function addAsset(pool, user, file, meta = {}) {
if (!file || !file.path) throw httpError(400, 'Файл не загружен');
const raw = String(file.path).replace(/\\/g, '/');
const path = raw.startsWith('/') ? raw : '/' + raw;
if (!/^\/uploads\/[\w,.()-]+$/.test(path)) throw httpError(400, 'Неверный путь к файлу');
const kind = mediaKind(file.originalname || path);
const caption = textValue(meta.caption, QUIZ_CAPTION_MAX, 'Подпись', false);
const { rows } = await pool.query(
`INSERT INTO quiz_assets (kind, path, original_name, mime, size_bytes, caption, created_by)
VALUES ($1,$2,$3,$4,$5,$6,$7) RETURNING *`,
[kind, path, file.originalname || null, file.mimetype || null, file.size || null,
caption || null, user.id]
);
return assetPublic(rows[0]);
}
async function updateAsset(pool, id, user, patch = {}) {
const { rows } = await pool.query('SELECT * FROM quiz_assets WHERE id = $1', [id]);
if (!rows.length) throw httpError(404, 'Файл не найден');
const asset = rows[0];
await assertAssetAccess(pool, asset, user);
const caption = textValue(patch.caption, QUIZ_CAPTION_MAX, 'Подпись', false);
const sortOrder = intValue(patch.sort_order, 0, 1000, 'порядок');
const upd = await pool.query(
'UPDATE quiz_assets SET caption = $2, sort_order = $3 WHERE id = $1 RETURNING *',
[id, caption || null, sortOrder == null ? asset.sort_order : sortOrder]
);
return assetPublic(upd.rows[0]);
}
async function deleteAsset(pool, id, user) {
const { rows } = await pool.query('SELECT * FROM quiz_assets WHERE id = $1', [id]);
if (!rows.length) throw httpError(404, 'Файл не найден');
await assertAssetAccess(pool, rows[0], user);
await pool.query('DELETE FROM quiz_assets WHERE id = $1', [id]);
return { path: rows[0].path };
}
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 maxScore = round2(qWeight);
let ok = false;
if (question.kind === 'number') {
const answer = normalizeNumberValue(textAnswer);
ok = answer != null && accepted.some(raw => {
const value = normalizeNumberValue(raw);
return value != null && value === answer;
});
} else if (question.kind === 'date') {
const answer = normalizeDateValue(textAnswer);
ok = !!answer && accepted.some(raw => normalizeDateValue(raw) === answer);
} else {
const answer = normalizeAnswerText(textAnswer);
const mode = question.text_match === 'contains' ? 'contains' : 'exact';
ok = !!answer && accepted.some(raw => {
const key = normalizeAnswerText(raw);
if (!key) return false;
return mode === 'contains' ? answer.includes(key) : answer === key;
});
}
return { score: ok ? maxScore : 0, max_score: maxScore, is_correct: ok };
}
function scoreQuestion(question, selectedIds, textAnswer) {
const options = Array.isArray(question.options) ? question.options : [];
if (FREE_KINDS.has(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);
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 };
}
const exact = correct.length === selected.size && correct.every(o => selected.has(Number(o.id)));
if (!question.partial_credit) {
return { score: exact ? maxScore : 0, max_score: maxScore, is_correct: exact };
}
const chosen = options.filter(o => selected.has(Number(o.id)));
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 };
}
async function startAttempt(pool, quizId, user) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
if (row.is_published !== true) throw httpError(403, 'Тест не опубликован');
if (row.max_attempts != null) {
const { rows } = await pool.query(
`SELECT count(*)::int AS c FROM quiz_attempts WHERE quiz_id = $1 AND user_id = $2 AND status = 'done'`,
[quizId, user.id]
);
if (rows[0].c >= row.max_attempts) throw httpError(400, 'Попытки закончились');
}
const existing = await pool.query(
`SELECT id, started_at FROM quiz_attempts
WHERE quiz_id = $1 AND user_id = $2 AND status = 'in_progress'
ORDER BY id DESC LIMIT 1`,
[quizId, user.id]
);
let attempt = existing.rows[0] || null;
if (!attempt) {
const { rows } = await pool.query(
'INSERT INTO quiz_attempts (quiz_id, user_id) VALUES ($1, $2) RETURNING id, started_at',
[quizId, user.id]
);
attempt = rows[0];
}
return { attempt, resumed: !!existing.rows.length, quiz: await getQuiz(pool, quizId, user) };
}
async function restartAttempt(pool, quizId, user) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
if (row.is_published !== true) throw httpError(403, 'Тест не опубликован');
if (row.max_attempts != null) {
const { rows } = await pool.query(
`SELECT count(*)::int AS c FROM quiz_attempts WHERE quiz_id = $1 AND user_id = $2 AND status = 'done'`,
[quizId, user.id]
);
if (rows[0].c >= row.max_attempts) throw httpError(400, 'Попытки закончились');
}
await pool.query(`DELETE FROM quiz_attempts WHERE quiz_id = $1 AND user_id = $2 AND status = 'in_progress'`, [quizId, user.id]);
const { rows } = await pool.query(
'INSERT INTO quiz_attempts (quiz_id, user_id) VALUES ($1, $2) RETURNING id, started_at',
[quizId, user.id]
);
return { attempt: rows[0], resumed: false, quiz: await getQuiz(pool, quizId, user) };
}
async function performSubmit(pool, row, attempt, body = {}) {
const quizId = Number(row.id);
const attemptId = Number(attempt.id);
const structure = await loadQuizStructure(pool, quizId);
const answers = Array.isArray(body.answers) ? body.answers.slice(0, QUIZ_ATTEMPT_ANSWERS_MAX) : [];
const byQuestion = new Map();
for (const a of answers) {
const qid = parseInt(a && a.question_id, 10);
if (!Number.isInteger(qid)) continue;
byQuestion.set(qid, a);
}
const results = [];
let totalScore = 0;
let totalMax = 0;
const client = await pool.connect();
try {
await client.query('BEGIN');
for (const q of structure.questions) {
const a = byQuestion.get(q.id) || {};
const free = FREE_KINDS.has(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 res = row.kind === 'survey'
? { score: 0, max_score: 0, is_correct: null }
: scoreQuestion({
kind: q.kind,
weight: q.weight,
partial_credit: q.partial_credit,
text_match: q.text_match,
accepted_answers: q.accepted_answers,
options: q.options,
}, optionIds, textAnswer);
totalScore += res.score;
totalMax += res.max_score;
const snapshot = {
kind: q.kind,
text: q.text,
options: q.options.map(o => ({ id: o.id, text: o.text, is_correct: o.is_correct, weight: o.weight })),
text_match: q.text_match,
accepted_answers: q.accepted_answers,
selected: optionIds,
};
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)`,
[attemptId, q.id, q.text, optionIds, JSON.stringify(snapshot), textAnswer || null,
res.is_correct, res.score, res.max_score]
);
results.push({
question_id: q.id,
text: q.text,
kind: q.kind,
score: res.score,
max_score: res.max_score,
is_correct: res.is_correct,
option_ids: optionIds,
text_answer: textAnswer || null,
correct_option_ids: q.options.filter(o => o.is_correct).map(o => o.id),
});
}
const percent = totalMax > 0 ? round2((totalScore / totalMax) * 100) : 0;
const passed = row.kind === 'test' ? percent >= row.pass_percent : null;
const upd = await client.query(
`UPDATE quiz_attempts SET status = 'done', score = $2, max_score = $3, percent = $4, passed = $5, finished_at = now()
WHERE id = $1 RETURNING id, status, score, max_score, percent, passed, started_at, finished_at`,
[attemptId, totalScore, totalMax, percent, passed]
);
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,
grade,
answers_hidden: !showAnswers,
questions: showAnswers ? results : [],
} : null,
revealed: showAnswers,
};
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
throw e;
} finally {
client.release();
}
}
async function submitAttempt(pool, quizId, attemptId, user, body = {}) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
const { rows: attRows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, quizId]);
if (!attRows.length) throw httpError(404, 'Попытка не найдена');
const attempt = attRows[0];
if (Number(attempt.user_id) !== Number(user.id)) throw httpError(403, 'Нет доступа к попытке');
if (attempt.status === 'done') throw httpError(409, 'Попытка уже завершена');
return performSubmit(pool, row, attempt, body);
}
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.allow_anonymous !== true || row.is_published !== true) {
throw httpError(404, 'Тест не найден');
}
return row;
}
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;
delete meta.deleted_at;
delete meta.purge_at;
return {
quiz: meta,
quiz_assets: structure.quiz_assets,
questions: structure.questions,
};
}
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, 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, guest_name: guestName },
quiz: await getPublicQuiz(pool, quizId),
};
}
function anonTokenMatches(expected, given) {
const a = Buffer.from(String(expected || ''), 'utf8');
const b = Buffer.from(String(given || ''), 'utf8');
if (!a.length || a.length !== b.length) return false;
return crypto.timingSafeEqual(a, b);
}
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];
if (attempt.user_id != null) throw httpError(403, 'Нет доступа к попытке');
if (!anonTokenMatches(attempt.anon_token, token)) throw httpError(403, 'Нет доступа к попытке');
if (attempt.status === 'done') throw httpError(409, 'Попытка уже завершена');
return performSubmit(pool, row, attempt, body);
}
async function listAttempts(pool, quizId, user, params = {}) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
const editable = canEditQuiz(row, user);
if (!editable && row.is_published !== true) throw httpError(404, 'Тест не найден');
const limit = Math.min(Math.max(parseInt(params.limit, 10) || 200, 1), 500);
const offset = Math.max(parseInt(params.offset, 10) || 0, 0);
const args = [quizId];
let where = `a.quiz_id = $1 AND a.status = 'done'`;
if (!editable) {
args.push(user.id);
where += ` AND a.user_id = $${args.length}`;
}
const { rows } = await pool.query(
`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
LIMIT $${args.length + 1} OFFSET $${args.length + 2}`,
[...args, limit, offset]
);
const total = await pool.query(`SELECT count(*)::int AS c FROM quiz_attempts a WHERE ${where}`, args);
return {
items: rows.map(r => ({
...r,
score: Number(r.score),
max_score: Number(r.max_score),
percent: Number(r.percent),
})),
total: total.rows[0].c,
};
}
async function getAttempt(pool, quizId, attemptId, user) {
const row = await findQuizRow(pool, quizId);
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 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]
);
if (!rows.length) throw httpError(404, 'Попытка не найдена');
const attempt = rows[0];
delete attempt.anon_token;
if (!editable && Number(attempt.user_id) !== Number(user.id)) throw httpError(403, 'Нет доступа к попытке');
const { rows: answers } = await pool.query(
'SELECT * FROM quiz_attempt_answers WHERE attempt_id = $1 ORDER BY id ASC',
[attemptId]
);
const structure = await loadQuizStructure(pool, quizId);
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: {
...attempt,
score: Number(attempt.score),
max_score: Number(attempt.max_score),
percent: Number(attempt.percent),
},
answers: answers.map(a => {
const question = qmap.get(a.question_id) || null;
const snapshot = revealed ? a.answer_snapshot : { selected: a.option_ids };
return {
...a,
score: Number(a.score),
max_score: Number(a.max_score),
is_correct: revealed ? a.is_correct : null,
answer_snapshot: snapshot,
question: question && revealed
? question
: question
? { ...question, weight: 0, partial_credit: false, options: question.options.map(o => ({ ...o, is_correct: false, weight: 0 })) }
: null,
};
}),
revealed,
grade,
};
}
async function quizStats(pool, quizId, user) {
const row = await findQuizRow(pool, quizId);
if (!row) throw httpError(404, 'Тест не найден');
if (!canEditQuiz(row, user)) throw httpError(403, 'Статистика доступна автору и администратору');
const totals = await pool.query(
`SELECT count(*)::int AS attempts, count(DISTINCT user_id)::int AS users,
COALESCE(round(avg(percent), 2), 0) AS avg_percent,
count(*) FILTER (WHERE passed)::int AS passed
FROM quiz_attempts WHERE quiz_id = $1 AND status = 'done'`,
[quizId]
);
const { questions } = await loadQuizStructure(pool, quizId);
const answers = await pool.query(
`SELECT aa.question_id, aa.option_ids, aa.text_answer
FROM quiz_attempt_answers aa
JOIN quiz_attempts a ON a.id = aa.attempt_id
WHERE a.quiz_id = $1 AND a.status = 'done'`,
[quizId]
);
const counts = new Map();
const texts = new Map();
for (const a of answers.rows) {
if (a.question_id == null) continue;
if (!counts.has(a.question_id)) counts.set(a.question_id, new Map());
const m = counts.get(a.question_id);
for (const id of a.option_ids || []) m.set(id, (m.get(id) || 0) + 1);
if (a.text_answer) {
if (!texts.has(a.question_id)) texts.set(a.question_id, []);
texts.get(a.question_id).push(a.text_answer);
}
}
return {
totals: {
attempts: totals.rows[0].attempts,
users: totals.rows[0].users,
avg_percent: Number(totals.rows[0].avg_percent),
passed: totals.rows[0].passed,
},
questions: questions.map(q => ({
id: q.id,
kind: q.kind,
text: q.text,
text_match: q.text_match,
accepted_answers: q.accepted_answers,
options: q.options.map(o => ({
id: o.id,
text: o.text,
is_correct: o.is_correct,
count: (counts.get(q.id) || new Map()).get(o.id) || 0,
})),
texts: (texts.get(q.id) || []).slice(0, 200),
})),
};
}
async function purgeQuizzes(pool) {
const { rows } = await pool.query('SELECT id, cover_path FROM quizzes WHERE purge_at IS NOT NULL AND purge_at <= now()');
const paths = [];
for (const r of rows) {
const assets = await pool.query(
`SELECT path FROM quiz_assets
WHERE quiz_id = $1
OR question_id IN (SELECT id FROM quiz_questions WHERE quiz_id = $1)
OR option_id IN (SELECT o.id FROM quiz_options o JOIN quiz_questions q ON q.id = o.question_id WHERE q.quiz_id = $1)`,
[r.id]
);
assets.rows.forEach(a => { if (a.path) paths.push(a.path); });
if (r.cover_path) paths.push(r.cover_path);
await pool.query('DELETE FROM quizzes WHERE id = $1', [r.id]);
}
return { count: rows.length, paths };
}
async function cleanupQuizAssets(pool, maxAgeHours = 24) {
const hours = Math.max(1, Math.min(24 * 30, Number(maxAgeHours) || 24));
const { rows } = await pool.query(
`DELETE FROM quiz_assets
WHERE quiz_id IS NULL AND question_id IS NULL AND option_id IS NULL
AND created_at < now() - ($1 || ' hours')::interval
RETURNING path`,
[hours]
);
await pool.query(`DELETE FROM quiz_attempts WHERE status = 'in_progress' AND started_at < now() - interval '2 days'`);
return { count: rows.length, paths: rows.map(r => r.path).filter(Boolean) };
}
module.exports = {
QUIZ_KINDS,
QUESTION_KINDS,
OPTION_KINDS,
FREE_KINDS,
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,
QUIZ_MEDIA_EXT,
ensureQuizTables,
quizError,
httpError,
mediaKind,
canEditQuiz,
quizWriteBlocked,
listQuizzes,
createQuiz,
getQuiz,
saveQuiz,
softDeleteQuiz,
restoreQuiz,
deleteQuizPermanent,
setCover,
addAsset,
updateAsset,
deleteAsset,
scoreQuestion,
startAttempt,
restartAttempt,
submitAttempt,
getPublicQuiz,
startPublicAttempt,
submitPublicAttempt,
normalizeAnswerText,
normalizeNumberValue,
normalizeDateValue,
listAttempts,
getAttempt,
quizStats,
purgeQuizzes,
cleanupQuizAssets,
};