'use strict'; const crypto = require('crypto'); 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', '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; 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_RETRY_COOLDOWN_MAX = 10080; 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 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() .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, 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, stats_public BOOLEAN NOT NULL DEFAULT false, access_code VARCHAR(64), public_token VARCHAR(32), 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 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 stats_public 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 public_token VARCHAR(32)'); await pool.query(`UPDATE quizzes SET public_token = md5(random()::text || clock_timestamp()::text || id::text) WHERE public_token IS NULL`); 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 0, 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, no_shuffle 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 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\''); 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('ALTER TABLE quiz_questions ADD COLUMN IF NOT EXISTS no_shuffle 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 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 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, 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, 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 UNIQUE INDEX IF NOT EXISTS idx_quizzes_public_token ON quizzes(public_token)'); 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)'); await pool.query('CREATE INDEX IF NOT EXISTS idx_quiz_attempt_answers_answer ON quiz_attempt_answers(answer_id) WHERE answer_id IS NOT NULL'); } function canEditQuiz(quiz, user) { 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, no_shuffle: q.no_shuffle === 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, public_token: row.public_token || null, 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, 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, stats_public: row.stats_public === 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, 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 => { const canEdit = canEditQuiz(r, user); return { ...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: canEdit, stats_available: canEdit || (r.stats_public === true && r.is_published === true && !r.deleted_at), can_take: r.is_published === true && !r.deleted_at, }; }); return { items, total: totalRes.rows[0].c }; } function publicToken() { return crypto.randomBytes(QUIZ_ANON_TOKEN_BYTES).toString('hex'); } function normalizePublicToken(raw) { const value = typeof raw === 'string' ? raw.trim() : ''; return /^[a-f0-9]{32}$/i.test(value) ? value.toLowerCase() : null; } 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, public_token) VALUES ($1, $2, $3, $4, $5) RETURNING id', [title, null, kind, user.id, publicToken()] ); return getQuiz(pool, rows[0].id, user); } async function rotatePublicToken(pool, id, user) { const row = await findQuizRow(pool, id); if (!row) throw httpError(404, 'Тест не найден'); if (!canEditQuiz(row, user)) throw httpError(403, 'Изменять тест может только автор или администратор'); const token = publicToken(); await pool.query('UPDATE quizzes SET public_token = $2, updated_at = now() WHERE id = $1', [id, token]); return { id, public_token: token }; } 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, access_code: editable ? (row.access_code || '') : null, }, 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, stats_available: editable || (row.stats_public === true && row.is_published === true && !row.deleted_at), 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 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; 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, 'Неверный путь к обложке'); } const accessCode = body.access_code === undefined ? (current.access_code == null ? null : accessCodeValue(current.access_code)) : accessCodeValue(body.access_code); 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), stats_public: asBool(body.stats_public, current.stats_public === 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, 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, }; } 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, 0) : 1; const required = asBool(q.required, true); 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 = 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); 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, 0) : 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, no_shuffle: asBool(q.no_shuffle, false), 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 = 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; 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 && !(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(); 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, access_code = $16, retry_cooldown_min = $17, stats_public = $18, 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.access_code, meta.retry_cooldown_min, meta.stats_public] ); 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, no_shuffle = $14, 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, q.no_shuffle] ); } 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, no_shuffle) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10::text[],$11,$12,$13) 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, q.no_shuffle] ); 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 ? 0 : 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 (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 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)) : 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), 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 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) { 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 = isFreeKind(q.kind); const optionIds = free ? [] : normalizeIdList(a.option_ids, QUIZ_OPTIONS_MAX); const textAnswer = free ? textValue(a.text, QUIZ_ANSWER_MAX, 'Ответ', false) : ''; 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 } : 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, }; 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, 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, answerId, 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, token) { const value = normalizePublicToken(token); if (!value) throw httpError(404, 'Тест не найден'); const { rows } = await pool.query('SELECT * FROM quizzes WHERE public_token = $1 AND deleted_at IS NULL', [value]); if (!rows.length) throw httpError(404, 'Тест не найден'); const row = rows[0]; if (row.allow_anonymous !== true || row.is_published !== true) { throw httpError(404, 'Тест не найден'); } return row; } async function getPublicQuiz(pool, token) { const row = await findPublicQuiz(pool, token); const structure = stripAnswers(await loadQuizStructure(pool, row.id)); const meta = quizMeta(row); delete meta.id; delete meta.public_token; delete meta.author_id; delete meta.deleted_at; delete meta.purge_at; delete meta.stats_public; return { quiz: { ...meta, has_system_fields: structure.questions.some(q => SYSTEM_FIELD_KINDS.has(q.kind)), }, quiz_assets: structure.quiz_assets, questions: structure.questions, }; } async function startPublicAttempt(pool, token, opts = {}) { const row = await findPublicQuiz(pool, token); if (!accessCodeMatches(row.access_code, opts.code)) throw httpError(403, 'Неверный код доступа'); const guestName = row.kind === 'test' ? guestNameValue(opts.name) : null; const attemptToken = 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', [row.id, attemptToken, guestName] ); return { attempt: { id: rows[0].id, started_at: rows[0].started_at, anon_token: attemptToken, guest_name: guestName }, quiz: await getPublicQuiz(pool, token), }; } 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, token, attemptId, attemptToken, body = {}) { const row = await findPublicQuiz(pool, token); const { rows } = await pool.query('SELECT * FROM quiz_attempts WHERE id = $1 AND quiz_id = $2', [attemptId, row.id]); if (!rows.length) throw httpError(404, 'Попытка не найдена'); const attempt = rows[0]; if (attempt.user_id != null) throw httpError(403, 'Нет доступа к попытке'); if (!anonTokenMatches(attempt.anon_token, attemptToken)) throw httpError(403, 'Нет доступа к попытке'); if (attempt.status === 'done') throw httpError(409, 'Попытка уже завершена'); 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, token, opts = {}) { const row = await findPublicQuiz(pool, token); 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, 'Тест не найден'); 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, }; } function quizAnswerPayload(a, graded, revealed, optionText) { const snapshot = a.answer_snapshot && typeof a.answer_snapshot === 'object' ? a.answer_snapshot : {}; const snapOptions = Array.isArray(snapshot.options) ? snapshot.options : []; const selectedIds = Array.isArray(a.option_ids) ? a.option_ids.map(Number).filter(n => Number.isInteger(n) && n > 0) : []; const optionMap = new Map(); for (const o of snapOptions) { const oid = Number(o && o.id); if (!Number.isInteger(oid) || oid <= 0) continue; optionMap.set(oid, { id: oid, text: String(o.text || ''), is_correct: o.is_correct === true }); } for (const [oid, text] of optionText) { if (!optionMap.has(oid)) optionMap.set(oid, { id: oid, text, is_correct: false }); } const selected = selectedIds.map(oid => { const o = optionMap.get(oid) || { id: oid, text: '', is_correct: false }; return { id: oid, text: o.text, is_correct: graded && revealed ? o.is_correct : null }; }); const correct = graded && revealed ? [...optionMap.values()].filter(o => o.is_correct).map(o => ({ id: o.id, text: o.text })) : []; return { question_id: a.question_id, text: a.text, kind: a.kind, text_answer: a.text_answer || '', answer_id: a.answer_id == null ? null : Number(a.answer_id), selected, correct, is_correct: graded && revealed ? a.is_correct : null, score: graded && revealed ? Number(a.score) : null, max_score: graded && revealed ? Number(a.max_score) : null, }; } async function studentQuizResults(pool, studentId, user, opts = {}) { const limit = Math.min(Math.max(Number(opts.limit) || 200, 1), 500); const base = `FROM quiz_attempts a JOIN quizzes q ON q.id = a.quiz_id WHERE a.status = 'done' AND q.deleted_at IS NULL AND EXISTS ( SELECT 1 FROM quiz_attempt_answers aa LEFT JOIN quiz_questions qq ON qq.id = aa.question_id WHERE aa.attempt_id = a.id AND aa.answer_id = $1 AND (qq.kind = 'student' OR aa.answer_snapshot->>'field' = 'student'))`; const [totalRes, listRes] = await Promise.all([ pool.query(`SELECT count(*)::int AS n ${base}`, [studentId]), pool.query( `SELECT a.id, a.quiz_id, a.score, a.max_score, a.percent, a.passed, a.started_at, a.finished_at, q.title, q.kind, q.show_results, q.show_answers, q.pass_percent, q.author_id, q.grade_scale_id ${base} ORDER BY a.finished_at DESC NULLS LAST, a.id DESC LIMIT $2`, [studentId, limit] ), ]); const attempts = listRes.rows; const attemptIds = attempts.map(r => r.id); let answerRows = []; if (attemptIds.length) { const { rows } = await pool.query( `SELECT aa.attempt_id, aa.question_id, aa.option_ids, aa.answer_snapshot, aa.text_answer, aa.answer_id, aa.is_correct, aa.score, aa.max_score, COALESCE(aa.answer_snapshot->>'kind', qq.kind, 'line') AS kind, COALESCE(NULLIF(aa.question_text, ''), qq.text, '') AS text FROM quiz_attempt_answers aa LEFT JOIN quiz_questions qq ON qq.id = aa.question_id WHERE aa.attempt_id = ANY($1::int[]) ORDER BY aa.attempt_id, COALESCE(qq.sort_order, 0), aa.id`, [attemptIds] ); answerRows = rows; } const optionIds = new Set(); for (const a of answerRows) { if (Array.isArray(a.option_ids)) a.option_ids.forEach((oid) => { if (Number(oid) > 0) optionIds.add(Number(oid)); }); const snapOptions = a.answer_snapshot && Array.isArray(a.answer_snapshot.options) ? a.answer_snapshot.options : []; snapOptions.forEach((o) => { if (Number(o && o.id) > 0) optionIds.add(Number(o.id)); }); } const optionText = new Map(); if (optionIds.size) { const { rows } = await pool.query('SELECT id, text FROM quiz_options WHERE id = ANY($1::int[])', [[...optionIds]]); rows.forEach(o => optionText.set(Number(o.id), String(o.text || ''))); } const scaleIds = [...new Set(attempts .filter(r => r.kind === 'test' && r.grade_scale_id != null) .map(r => Number(r.grade_scale_id)))]; const rangesByScale = new Map(); if (scaleIds.length) { const { rows } = await pool.query( 'SELECT scale_id, min_score, max_score, label, image_path FROM quiz_grade_ranges WHERE scale_id = ANY($1::int[]) ORDER BY min_score ASC, id ASC', [scaleIds] ); for (const r of rows) { const key = Number(r.scale_id); if (!rangesByScale.has(key)) rangesByScale.set(key, []); rangesByScale.get(key).push(r); } } const byAttempt = new Map(); for (const a of answerRows) { if (!byAttempt.has(a.attempt_id)) byAttempt.set(a.attempt_id, []); byAttempt.get(a.attempt_id).push(a); } const items = attempts.map(row => { const editable = canEditQuiz(row, user); const showResults = editable || row.show_results !== false; const revealed = editable || (row.show_results !== false && row.show_answers !== false); const graded = row.kind === 'test'; const answers = (byAttempt.get(row.id) || []) .filter(a => !SYSTEM_FIELD_KINDS.has(a.kind)) .map(a => quizAnswerPayload(a, graded, revealed, optionText)); const grade = graded && row.grade_scale_id != null ? gradeForScore(rangesByScale.get(Number(row.grade_scale_id)) || [], Number(row.score)) : null; return { id: row.id, quiz_id: row.quiz_id, title: row.title, kind: row.kind, show_results: showResults, revealed, score: showResults ? Number(row.score) : null, max_score: showResults ? Number(row.max_score) : null, percent: showResults ? Number(row.percent) : null, passed: showResults ? row.passed : null, grade: showResults ? grade : null, started_at: row.started_at, finished_at: row.finished_at, answers, }; }); return { items, total: totalRes.rows[0].n }; } function statsId(v) { const n = Number(v); return Number.isInteger(n) && n > 0 ? n : null; } function statsDate(v) { const s = typeof v === 'string' ? v.trim() : ''; if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null; const d = new Date(`${s}T00:00:00Z`); if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== s) return null; return s; } function statsFilterRows(rows, filters) { return rows.filter(r => (!filters.date_from || (r.day && r.day >= filters.date_from)) && (!filters.date_to || (r.day && r.day <= filters.date_to)) && (!filters.student_id || Number(r.student_id) === filters.student_id) && (!filters.group_id || Number(r.group_id) === filters.group_id) && (!filters.branch_id || Number(r.branch_id) === filters.branch_id) && (!filters.module_id || Number(r.module_id) === filters.module_id) ); } function statsBucket(rows, idKey, nameKey) { const map = new Map(); for (const r of rows) { const id = r[idKey]; if (id == null) continue; const key = String(id); const name = r[nameKey] || ''; let item = map.get(key); if (!item) { item = { id: Number(id), name, attempts: 0, percent_sum: 0, passed: 0 }; map.set(key, item); } item.attempts += 1; item.percent_sum += Number(r.percent) || 0; if (r.passed === true) item.passed += 1; if (!item.name && name) item.name = name; } return [...map.values()] .map(x => ({ id: x.id, name: x.name, attempts: x.attempts, avg_percent: x.attempts ? round2(x.percent_sum / x.attempts) : 0, passed: x.passed, })) .sort((a, b) => (a.name || '').localeCompare(b.name || '', 'ru') || a.id - b.id); } function statsSummary(rows) { const attempts = rows.length; const users = new Set(); let anonymous = 0; let percentSum = 0; let passed = 0; for (const r of rows) { if (r.user_id == null) anonymous += 1; else users.add(String(r.user_id)); percentSum += Number(r.percent) || 0; if (r.passed === true) passed += 1; } const days = new Map(); for (const r of rows) { if (!r.day) continue; let item = days.get(r.day); if (!item) { item = { date: r.day, attempts: 0, percent_sum: 0, passed: 0 }; days.set(r.day, item); } item.attempts += 1; item.percent_sum += Number(r.percent) || 0; if (r.passed === true) item.passed += 1; } return { totals: { attempts, users: users.size, anonymous, avg_percent: attempts ? round2(percentSum / attempts) : 0, passed, pass_rate: attempts ? round2((passed / attempts) * 100) : 0, }, dates: [...days.values()] .sort((a, b) => a.date.localeCompare(b.date)) .map(x => ({ date: x.date, attempts: x.attempts, avg_percent: round2(x.percent_sum / x.attempts), passed: x.passed, })), students: statsBucket(rows, 'student_id', 'student_name'), groups: statsBucket(rows, 'group_id', 'group_name'), branches: statsBucket(rows, 'branch_id', 'branch_name'), modules: statsBucket(rows, 'module_id', 'module_name'), }; } function statsOptions(rows) { const pick = list => list.map(x => ({ id: x.id, name: x.name })); return { students: pick(statsBucket(rows, 'student_id', 'student_name')), groups: pick(statsBucket(rows, 'group_id', 'group_name')), branches: pick(statsBucket(rows, 'branch_id', 'branch_name')), modules: pick(statsBucket(rows, 'module_id', 'module_name')), }; } async function quizStats(pool, quizId, user, params = {}) { const row = await findQuizRow(pool, quizId); if (!row) throw httpError(404, 'Тест не найден'); const editable = canEditQuiz(row, user); const statsPublic = row.stats_public === true && row.is_published === true && !row.deleted_at; if (!editable && !statsPublic) throw httpError(403, 'Статистика доступна автору и администратору'); const tz = typeof params.tz === 'string' && params.tz ? params.tz : 'UTC'; const filters = { date_from: statsDate(params.date_from), date_to: statsDate(params.date_to), student_id: statsId(params.student_id), group_id: statsId(params.group_id), branch_id: statsId(params.branch_id), module_id: statsId(params.module_id), }; const { rows } = await pool.query( `WITH ans AS ( SELECT aa.attempt_id, MAX(aa.answer_id) FILTER (WHERE qq.kind = 'student') AS student_id, MAX(aa.answer_id) FILTER (WHERE qq.kind = 'group') AS group_id, MAX(aa.answer_id) FILTER (WHERE qq.kind = 'branch') AS branch_id, MAX(aa.answer_id) FILTER (WHERE qq.kind = 'module') AS module_id FROM quiz_attempt_answers aa JOIN quiz_attempts a2 ON a2.id = aa.attempt_id JOIN quiz_questions qq ON qq.id = aa.question_id WHERE a2.quiz_id = $1 AND a2.status = 'done' AND aa.answer_id IS NOT NULL GROUP BY aa.attempt_id ), base AS ( SELECT a.id, a.user_id, a.percent, a.passed, to_char(a.finished_at AT TIME ZONE $2, 'YYYY-MM-DD') AS day, an.student_id, s.name AS student_name, s.group_id AS student_group_id, an.group_id AS answer_group_id, an.branch_id AS answer_branch_id, an.module_id FROM quiz_attempts a LEFT JOIN ans an ON an.attempt_id = a.id LEFT JOIN students s ON s.id = an.student_id WHERE a.quiz_id = $1 AND a.status = 'done' ), resolved AS ( SELECT b.*, COALESCE(b.answer_group_id, b.student_group_id) AS group_id FROM base b ) SELECT r.id, r.user_id, r.percent, r.passed, r.day, r.student_id, COALESCE(r.student_name, '') AS student_name, r.group_id, COALESCE(g.name, '') AS group_name, COALESCE(r.answer_branch_id, g.branch_id) AS branch_id, COALESCE(b2.name, '') AS branch_name, r.module_id, COALESCE(m.name, '') AS module_name FROM resolved r LEFT JOIN groups g ON g.id = r.group_id LEFT JOIN branches b2 ON b2.id = COALESCE(r.answer_branch_id, g.branch_id) LEFT JOIN modules m ON m.id = r.module_id ORDER BY r.id`, [quizId, tz] ); const filtered = statsFilterRows(rows, filters); const summary = statsSummary(filtered); const revealKeys = editable || row.show_answers !== false; const attemptIds = filtered.map(r => r.id); const structure = await loadQuizStructure(pool, quizId); const answers = attemptIds.length ? await pool.query( `SELECT aa.question_id, aa.option_ids, aa.text_answer, aa.is_correct FROM quiz_attempt_answers aa WHERE aa.attempt_id = ANY($1::int[])`, [attemptIds] ) : { rows: [] }; const counts = new Map(); const texts = new Map(); const answered = new Map(); const correct = 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); answered.set(a.question_id, (answered.get(a.question_id) || 0) + 1); if (a.is_correct === true) correct.set(a.question_id, (correct.get(a.question_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 { can_edit: editable, reveal_keys: revealKeys, filters, all_attempts: rows.length, available: statsOptions(rows), totals: summary.totals, dates: summary.dates, students: summary.students, groups: summary.groups, branches: summary.branches, modules: summary.modules, questions: structure.questions.map(q => ({ id: q.id, kind: q.kind, text: q.text, text_match: q.text_match, accepted_answers: revealKeys ? q.accepted_answers : [], answered: answered.get(q.id) || 0, correct: revealKeys ? (correct.get(q.id) || 0) : null, options: q.options.map(o => ({ id: o.id, text: o.text, is_correct: revealKeys ? o.is_correct : false, 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, SYSTEM_FIELD_KINDS, SYSTEM_FIELD_LABELS, QUIZ_ACCESS_CODE_MAX, 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, rotatePublicToken, publicToken, normalizePublicToken, getQuiz, saveQuiz, softDeleteQuiz, restoreQuiz, deleteQuizPermanent, setCover, addAsset, updateAsset, deleteAsset, scoreQuestion, startAttempt, restartAttempt, submitAttempt, getPublicQuiz, startPublicAttempt, submitPublicAttempt, lookupSystemOptions, lookupPublicQuizOptions, normalizeAnswerText, normalizeNumberValue, normalizeDateValue, listAttempts, getAttempt, studentQuizResults, quizStats, statsSummary, statsFilterRows, purgeQuizzes, cleanupQuizAssets, };