Тесты и опросы: модуль тестов, анонимные опросы, страницы и бэкап

- lib/quizzes.js: таблицы quizzes*, CRUD, привязка медиа, подсчёт баллов, попытки, статистика, purge и уборка ассетов
- server.js: роуты CRUD/прохождения/статистики, отдача медиа, публичные роуты анонимного опроса, sweep и restore
- db/init.sql + db/migration.sql: схема шести таблиц, индексы и идемпотентные ALTER/CHECK
- backup-restore.js: нормализация и списки таблиц, покрытие в backup.selftest.js
- страницы quizzes/quiz-edit/quiz/quiz-public и публичный опрос без входа, пункт сайдбара «Тесты и опросы»
- quiz.selftest.js: юнит-проверки подсчёта баллов и нормализации ответов
- AGENTS.md: раздел 3t и File Map
This commit is contained in:
dev
2026-12-01 19:00:06 +03:00
parent 56f160165f
commit 7c9c6ef116
19 changed files with 5243 additions and 6 deletions
+498 -5
View File
@@ -69,6 +69,34 @@ const { groupOwnedBy } = require('./lib/groups');
const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes');
const { resolveImgbbEndpoint, friendlyApiError } = require('./lib/feedback-imgbb');
const { ensureFarewellTable, createFarewell, listFarewells, listFarewellTemplates, findFarewell, setFarewellStatus, updateFarewellText, setFarewellSent, farewellForUser, deleteFarewell, restoreFarewell, deleteFarewellPermanent, FAREWELL_AI_DEFAULT_PROMPT } = require('./lib/farewell');
const {
QUIZ_MEDIA_EXT,
mediaKind: quizMediaKind,
ensureQuizTables,
quizError,
listQuizzes,
createQuiz,
getQuiz,
saveQuiz,
softDeleteQuiz,
restoreQuiz,
deleteQuizPermanent,
setCover: setQuizCover,
addAsset: addQuizAsset,
updateAsset: updateQuizAsset,
deleteAsset: deleteQuizAsset,
startAttempt: startQuizAttempt,
restartAttempt: restartQuizAttempt,
submitAttempt: submitQuizAttempt,
getPublicSurvey,
startAnonymousAttempt,
submitAnonymousAttempt,
listAttempts: listQuizAttempts,
getAttempt: getQuizAttempt,
quizStats,
purgeQuizzes,
cleanupQuizAssets,
} = require('./lib/quizzes');
const { aiHttpErrorFromResponse, aiHttpErrorText, aiHttpErrorDetail } = require('./lib/ai-errors');
const { findBrokenFaceRefs, scanAllBrokenFaceRefs, cleanupAllBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup');
const {
@@ -305,7 +333,7 @@ function dispatchEvent(payload) {
});
return;
}
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed')) {
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed' || payload.type === 'quizzes_changed')) {
writeFrame(payload.type, { ts: Date.now() });
return;
}
@@ -344,6 +372,11 @@ function broadcastNotesChanged() {
.catch(err => console.error('Publish failed:', err.message));
}
function broadcastQuizzesChanged() {
cache.publish(EVENTS_CHANNEL, { type: 'quizzes_changed' })
.catch(err => console.error('Publish failed:', err.message));
}
function broadcastAiStatus(payload) {
cache.publish(EVENTS_CHANNEL, { type: 'ai_status', ...payload })
.catch(err => console.error('Publish failed:', err.message));
@@ -1774,6 +1807,9 @@ async function purgeScheduledDeletions() {
const fwcount = fwres.rowCount;
const calres = await pool.query('DELETE FROM calendar_events WHERE purge_at IS NOT NULL AND purge_at <= now()');
const calCount = calres.rowCount;
const quizPurge = await purgeQuizzes(pool);
quizPurge.paths.forEach(p => safeUnlink(p));
const qcount = quizPurge.count;
const bires = await pool.query('DELETE FROM broken_images WHERE purge_at IS NOT NULL AND purge_at <= now()');
const bicount = bires.rowCount;
const strefs = await pool.query('SELECT id FROM students WHERE purge_at IS NOT NULL AND purge_at <= now()');
@@ -1796,7 +1832,7 @@ async function purgeScheduledDeletions() {
if (fbcount) invalidateFeedbacks();
if (stcount) invalidateStudents();
if (bicount) invalidateAll();
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, farewell_messages: fwcount, students: stcount, broken_images: bicount, calendar_events: calCount };
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, farewell_messages: fwcount, students: stcount, broken_images: bicount, calendar_events: calCount, quizzes: qcount };
}
function safeUnlink(relPath) {
@@ -1867,7 +1903,7 @@ async function removeEntryFiles(entryId) {
async function sweepOrphanedUploads() {
const dir = UPLOADS_DIR;
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }, { rows: digestImages }, { rows: digestPreviews }] = await Promise.all([
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: userAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }, { rows: docPhotos }, { rows: docFiles }, { rows: digestImages }, { rows: digestPreviews }, { rows: quizAssets }, { rows: quizCovers }] = await Promise.all([
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
pool.query('SELECT path AS p FROM project_files'),
pool.query('SELECT photo_path AS p FROM group_photos'),
@@ -1889,9 +1925,11 @@ async function sweepOrphanedUploads() {
pool.query('SELECT path AS p FROM doc_files'),
pool.query('SELECT path AS p FROM digest_images'),
pool.query('SELECT preview_path AS p FROM digests WHERE preview_path IS NOT NULL'),
pool.query('SELECT path AS p FROM quiz_assets'),
pool.query('SELECT cover_path AS p FROM quizzes WHERE cover_path IS NOT NULL'),
]);
const refs = new Set();
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles, ...digestImages, ...digestPreviews].forEach(r => {
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...userAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs, ...docPhotos, ...docFiles, ...digestImages, ...digestPreviews, ...quizAssets, ...quizCovers].forEach(r => {
const key = storage.keyFromPath(r.p);
if (key) refs.add(key);
});
@@ -1932,6 +1970,8 @@ const BROKEN_IMAGE_SOURCES = [
{ key: 'doc_files.path', table: 'doc_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение документации' },
{ key: 'digest_images.path', table: 'digest_images', column: 'path', idColumn: 'id', kind: 'row', label: 'Картинка дайджеста' },
{ key: 'digests.preview_path', table: 'digests', column: 'preview_path', idColumn: 'id', kind: 'column', label: 'Обложка дайджеста' },
{ key: 'quiz_assets.path', table: 'quiz_assets', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл теста' },
{ key: 'quizzes.cover_path', table: 'quizzes', column: 'cover_path', idColumn: 'id', kind: 'column', label: 'Обложка теста' },
{ key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' },
{ key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' },
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
@@ -2998,6 +3038,7 @@ async function ensureUsersAndFirstAdmin() {
await ensureDigestTable(pool);
await ensureCalendarEventsTable(pool);
await ensureFarewellTable(pool);
await ensureQuizTables(pool);
await ensureFirstAdmin();
}
@@ -7594,7 +7635,7 @@ function backupUploadGuard(req, res, next) {
async function buildBackupArchive() {
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
try {
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce, cal] = await Promise.all([
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, df, si, atr, sar, dg, dgi, fm, ce, cal, qz, qq, qo, qa, qat, qaa] = await Promise.all([
pool.query('SELECT * FROM groups ORDER BY id'),
pool.query('SELECT * FROM students ORDER BY id'),
pool.query('SELECT * FROM entries ORDER BY id'),
@@ -7638,6 +7679,12 @@ async function buildBackupArchive() {
pool.query('SELECT * FROM farewell_messages ORDER BY id'),
pool.query('SELECT * FROM calendar_events ORDER BY id'),
pool.query('SELECT * FROM calendar_action_log ORDER BY id'),
pool.query('SELECT * FROM quizzes ORDER BY id'),
pool.query('SELECT * FROM quiz_questions ORDER BY id'),
pool.query('SELECT * FROM quiz_options ORDER BY id'),
pool.query('SELECT * FROM quiz_assets ORDER BY id'),
pool.query('SELECT * FROM quiz_attempts ORDER BY id'),
pool.query('SELECT * FROM quiz_attempt_answers ORDER BY id'),
]);
const settings = {};
st.rows.forEach(r => { settings[r.key] = r.value; });
@@ -7662,6 +7709,8 @@ async function buildBackupArchive() {
digests: dg.rowCount, digest_images: dgi.rowCount, farewell_messages: fm.rowCount,
calendar_events: ce.rowCount,
calendar_action_log: cal.rowCount,
quizzes: qz.rowCount, quiz_questions: qq.rowCount, quiz_options: qo.rowCount,
quiz_assets: qa.rowCount, quiz_attempts: qat.rowCount, quiz_attempt_answers: qaa.rowCount,
},
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
achievement_types: atr.rows, student_achievements: sar.rows,
@@ -7670,6 +7719,8 @@ async function buildBackupArchive() {
digests: dg.rows, digest_images: dgi.rows, farewell_messages: fm.rows,
calendar_events: ce.rows,
calendar_action_log: cal.rows,
quizzes: qz.rows, quiz_questions: qq.rows, quiz_options: qo.rows,
quiz_assets: qa.rows, quiz_attempts: qat.rows, quiz_attempt_answers: qaa.rows,
};
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
const files = await storage.downloadAll(path.join(staging, 'uploads'));
@@ -7955,6 +8006,12 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
await client.query('DELETE FROM doc_sections');
await client.query('DELETE FROM sidebar_items');
await client.query('DELETE FROM digest_images');
await client.query('DELETE FROM quiz_attempt_answers');
await client.query('DELETE FROM quiz_attempts');
await client.query('DELETE FROM quiz_assets');
await client.query('DELETE FROM quiz_options');
await client.query('DELETE FROM quiz_questions');
await client.query('DELETE FROM quizzes');
await client.query('DELETE FROM users');
await client.query('DELETE FROM branches');
for (const x of ndata.branches) {
@@ -8062,6 +8119,71 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
[x.id, x.digest_id, x.path, x.name || '', x.size || 0, x.created_at || null]
);
}
for (const x of (ndata.quizzes || [])) {
await client.query(
'INSERT INTO quizzes (id, title, description, kind, is_published, shuffle_questions, shuffle_options, show_results, max_attempts, time_limit_min, pass_percent, cover_path, allow_anonymous, author_id, created_at, updated_at, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,(SELECT id FROM users WHERE id = $14),$15,$16,$17,$18)',
[x.id, x.title, x.description, x.kind, x.is_published === true, x.shuffle_questions === true,
x.shuffle_options === true, x.show_results !== false, x.max_attempts, x.time_limit_min,
x.pass_percent, x.cover_path, x.allow_anonymous === true, x.author_id,
x.created_at || null, x.updated_at || null,
x.deleted_at || null, x.purge_at || null]
);
}
const restoredQuizIds = new Set((ndata.quizzes || []).map(x => x.id));
for (const x of (ndata.quiz_questions || [])) {
if (!restoredQuizIds.has(x.quiz_id)) continue;
await client.query(
'INSERT INTO quiz_questions (id, quiz_id, sort_order, kind, text, description, weight, partial_credit, required, text_match, accepted_answers, min_length, options_inline, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11::text[],$12,$13,$14,$15)',
[x.id, x.quiz_id, x.sort_order, x.kind, x.text, x.description, x.weight,
x.partial_credit === true, x.required !== false, x.text_match,
Array.isArray(x.accepted_answers) ? x.accepted_answers : [],
x.min_length || 0, x.options_inline === true,
x.created_at || null, x.updated_at || null]
);
}
const restoredQuestionIds = new Set((ndata.quiz_questions || [])
.filter(x => restoredQuizIds.has(x.quiz_id)).map(x => x.id));
for (const x of (ndata.quiz_options || [])) {
if (!restoredQuestionIds.has(x.question_id)) continue;
await client.query(
'INSERT INTO quiz_options (id, question_id, sort_order, text, description, is_correct, weight, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
[x.id, x.question_id, x.sort_order, x.text, x.description, x.is_correct === true, x.weight,
x.created_at || null, x.updated_at || null]
);
}
const restoredOptionIds = new Set((ndata.quiz_options || [])
.filter(x => restoredQuestionIds.has(x.question_id)).map(x => x.id));
for (const x of (ndata.quiz_assets || [])) {
const quizOk = x.quiz_id != null && restoredQuizIds.has(x.quiz_id);
const questionOk = x.question_id != null && restoredQuestionIds.has(x.question_id);
const optionOk = x.option_id != null && restoredOptionIds.has(x.option_id);
if (!quizOk && !questionOk && !optionOk) continue;
await client.query(
'INSERT INTO quiz_assets (id, quiz_id, question_id, option_id, kind, path, original_name, mime, size_bytes, caption, sort_order, created_by, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,(SELECT id FROM users WHERE id = $12),$13)',
[x.id, quizOk ? x.quiz_id : null, questionOk ? x.question_id : null, optionOk ? x.option_id : null,
x.kind, x.path, x.original_name, x.mime, x.size_bytes, x.caption, x.sort_order,
x.created_by, x.created_at || null]
);
}
const restoredAttemptIds = new Set();
for (const x of (ndata.quiz_attempts || [])) {
if (!restoredQuizIds.has(x.quiz_id)) continue;
const ins = await client.query(
'INSERT INTO quiz_attempts (id, quiz_id, user_id, status, score, max_score, percent, passed, started_at, finished_at) VALUES ($1,$2,(SELECT id FROM users WHERE id = $3),$4,$5,$6,$7,$8,$9,$10) RETURNING id',
[x.id, x.quiz_id, x.user_id, x.status, x.score, x.max_score, x.percent, x.passed,
x.started_at || null, x.finished_at || null]
);
if (ins.rowCount) restoredAttemptIds.add(x.id);
}
for (const x of (ndata.quiz_attempt_answers || [])) {
if (!restoredAttemptIds.has(x.attempt_id)) continue;
const questionOk = x.question_id != null && restoredQuestionIds.has(x.question_id);
await client.query(
'INSERT INTO quiz_attempt_answers (id, attempt_id, question_id, question_text, option_ids, answer_snapshot, text_answer, is_correct, score, max_score) VALUES ($1,$2,$3,$4,$5,$6::jsonb,$7,$8,$9,$10)',
[x.id, x.attempt_id, questionOk ? x.question_id : null, x.question_text, x.option_ids,
JSON.stringify(x.answer_snapshot || {}), x.text_answer, x.is_correct, x.score, x.max_score]
);
}
for (const x of ndata.user_branches) {
await client.query(
'INSERT INTO user_branches (user_id, branch_id) VALUES ($1,$2)',
@@ -15202,6 +15324,377 @@ app.delete('/api/broken-images/:id/permanent', requireAuth, requireAdmin, async
res.json({ ok: true, days });
});
// --- Тесты и опросы ---
const QUIZ_MEDIA_ALLOWED = new Set(QUIZ_MEDIA_EXT.map(e => '.' + e));
const quizMediaUpload = multer({
storage: multer.diskStorage({
destination: (_, __, cb) => {
fs.mkdirSync('uploads', { recursive: true });
cb(null, 'uploads');
},
filename: (_, file, cb) => {
const ext = path.extname(file.originalname || '').toLowerCase();
cb(null, `${Date.now()}-${crypto.randomBytes(3).toString('hex')}${ext}`);
},
}),
limits: { fileSize: MAX_FILE_UPLOAD_BYTES },
fileFilter: (req, file, cb) => {
const ext = path.extname(file.originalname || '').toLowerCase();
if (!QUIZ_MEDIA_ALLOWED.has(ext)) return cb(new Error('Not allowed extension'));
cb(null, true);
},
});
function unlinkQuizMedia(list) {
for (const p of list || []) {
if (!p) continue;
Promise.resolve(safeUnlink(p)).catch(() => {});
try { thumbUnlinkFor(p); } catch (e) { /* ignore */ }
}
}
app.get('/api/quizzes/files/:name', fileLimiter, async (req, res) => {
let user = null;
try {
user = await loadUserByToken(req.headers['x-auth-token'] || req.query.token);
} catch (e) {
return res.status(500).json({ error: 'Internal server error' });
}
if (!user || !user.is_active) return res.status(401).json({ error: 'Требуется вход' });
const name = req.params.name;
if (!/^[\w,.()-]+$/.test(name)) return res.status(400).end();
const key = storage.keyFromPath(`/uploads/${name}`);
try {
const size = await storage.sizeOf(key);
if (!size) return res.status(404).end();
const kind = quizMediaKind(name);
if (req.query.play === '1' && (kind === 'audio' || kind === 'video')) {
const ok = await sendPlayableFile(req, res, key, name);
if (!ok && !res.headersSent) return res.status(404).end();
return;
}
const ok = await storage.streamTo(res, key, {
cacheControl: 'private, max-age=3600',
download: kind !== 'image',
name,
contentType: mimeFor(name),
});
if (!ok && !res.headersSent) return res.status(404).end();
} catch (e) {
console.error('Quiz file stream failed:', key, e.message);
if (!res.headersSent) res.status(404).end();
}
});
app.get('/api/quizzes', requireAuth, async (req, res) => {
try {
const items = await listQuizzes(pool, req.user, {
kind: req.query.kind,
search: req.query.search,
mine: req.query.mine,
deleted: req.query.deleted,
limit: req.query.limit,
offset: req.query.offset,
});
res.json(items);
} catch (e) {
quizError(res, e, 'Не удалось загрузить тесты', 'quizzes list');
}
});
app.post('/api/quizzes', requireAuth, async (req, res) => {
try {
const result = await createQuiz(pool, req.user, req.body || {});
await logAudit(req, 'quiz.create', { id: result.quiz.id, kind: result.quiz.kind, title: result.quiz.title });
broadcastQuizzesChanged();
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось создать тест', 'quiz create');
}
});
app.post('/api/quizzes/assets', requireAuth, (req, res) => {
quizMediaUpload.single('file')(req, res, async err => {
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла' });
return res.status(400).json({ error: 'Недопустимый файл' });
}
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
try {
if (req.file.mimetype && /^image\/(jpeg|jpg|png|heic|heif|jfif)/.test(req.file.mimetype)) {
await convertPhoto(req.file);
}
const asset = await addQuizAsset(pool, req.user, req.file, {
caption: req.body && req.body.caption,
});
res.json({ item: asset });
} catch (e) {
removeUpload(req.file);
quizError(res, e, 'Не удалось загрузить файл', 'quiz asset upload');
}
});
});
app.put('/api/quizzes/assets/:id', requireAuth, async (req, res) => {
try {
const asset = await updateQuizAsset(pool, reqInt(req.params.id), req.user, req.body || {});
res.json({ item: asset });
} catch (e) {
quizError(res, e, 'Не удалось сохранить файл', 'quiz asset update');
}
});
app.delete('/api/quizzes/assets/:id', requireAuth, async (req, res) => {
try {
const removed = await deleteQuizAsset(pool, reqInt(req.params.id), req.user);
unlinkQuizMedia([removed.path]);
await logAudit(req, 'quiz.asset.delete', { path: removed.path });
res.json({ ok: true });
} catch (e) {
quizError(res, e, 'Не удалось удалить файл', 'quiz asset delete');
}
});
app.get('/api/quizzes/:id', requireAuth, async (req, res) => {
try {
const data = await getQuiz(pool, reqInt(req.params.id), req.user);
res.json(data);
} catch (e) {
quizError(res, e, 'Не удалось загрузить тест', 'quiz get');
}
});
app.put('/api/quizzes/:id', requireAuth, async (req, res) => {
try {
const result = await saveQuiz(pool, reqInt(req.params.id), req.user, req.body || {});
unlinkQuizMedia(result.removed);
await logAudit(req, 'quiz.update', {
id: result.quiz.id,
kind: result.quiz.kind,
title: result.quiz.title,
questions: result.questions.length,
published: result.quiz.is_published,
});
broadcastQuizzesChanged();
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось сохранить тест', 'quiz save');
}
});
app.delete('/api/quizzes/:id', requireAuth, async (req, res) => {
try {
const result = await softDeleteQuiz(pool, reqInt(req.params.id), req.user, await trashPurgeDays());
await logAudit(req, 'quiz.delete', { id: result.id, purge_days: result.purge_days });
broadcastQuizzesChanged();
res.json({ ok: true, purge_days: result.purge_days });
} catch (e) {
quizError(res, e, 'Не удалось удалить тест', 'quiz delete');
}
});
app.put('/api/quizzes/:id/restore', requireAuth, async (req, res) => {
try {
const result = await restoreQuiz(pool, reqInt(req.params.id), req.user);
await logAudit(req, 'quiz.restore', { id: result.id });
broadcastQuizzesChanged();
res.json({ ok: true });
} catch (e) {
quizError(res, e, 'Не удалось восстановить тест', 'quiz restore');
}
});
app.delete('/api/quizzes/:id/permanent', requireAuth, async (req, res) => {
try {
const result = await deleteQuizPermanent(pool, reqInt(req.params.id), req.user);
unlinkQuizMedia(result.paths);
await logAudit(req, 'quiz.permanent-delete', { id: reqInt(req.params.id) });
broadcastQuizzesChanged();
res.json({ ok: true });
} catch (e) {
quizError(res, e, 'Не удалось удалить тест', 'quiz permanent delete');
}
});
app.post('/api/quizzes/:id/cover', requireAuth, (req, res) => {
upload.single('photo')(req, res, async err => {
if (err) {
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
if (err.message === 'Only images') return res.status(400).json({ error: 'Допустимы только изображения' });
return res.status(400).json({ error: 'Недопустимый файл' });
}
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
try {
await convertPhoto(req.file);
const result = await setQuizCover(pool, reqInt(req.params.id), req.user, `/uploads/${req.file.filename}`);
unlinkQuizMedia([result.old]);
await logAudit(req, 'quiz.cover', { id: reqInt(req.params.id), path: result.cover_path });
broadcastQuizzesChanged();
res.json({ item: { path: result.cover_path } });
} catch (e) {
removeUpload(req.file);
quizError(res, e, 'Не удалось загрузить обложку', 'quiz cover upload');
}
});
});
app.delete('/api/quizzes/:id/cover', requireAuth, async (req, res) => {
try {
const result = await setQuizCover(pool, reqInt(req.params.id), req.user, null);
unlinkQuizMedia([result.old]);
await logAudit(req, 'quiz.cover.delete', { id: reqInt(req.params.id) });
broadcastQuizzesChanged();
res.json({ ok: true });
} catch (e) {
quizError(res, e, 'Не удалось удалить обложку', 'quiz cover delete');
}
});
app.post('/api/quizzes/:id/attempts', requireAuth, async (req, res) => {
try {
const result = await startQuizAttempt(pool, reqInt(req.params.id), req.user);
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось начать попытку', 'quiz attempt start');
}
});
app.post('/api/quizzes/:id/attempts/restart', requireAuth, async (req, res) => {
try {
const result = await restartQuizAttempt(pool, reqInt(req.params.id), req.user);
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось начать попытку заново', 'quiz attempt restart');
}
});
app.get('/api/quizzes/:id/attempts', requireAuth, async (req, res) => {
try {
const result = await listQuizAttempts(pool, reqInt(req.params.id), req.user, {
limit: req.query.limit,
offset: req.query.offset,
});
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось загрузить попытки', 'quiz attempts list');
}
});
app.get('/api/quizzes/:id/attempts/:attemptId', requireAuth, async (req, res) => {
try {
const result = await getQuizAttempt(
pool,
reqInt(req.params.id),
reqInt(req.params.attemptId),
req.user
);
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось загрузить попытку', 'quiz attempt get');
}
});
app.put('/api/quizzes/:id/attempts/:attemptId', requireAuth, async (req, res) => {
try {
const result = await submitQuizAttempt(
pool,
reqInt(req.params.id),
reqInt(req.params.attemptId),
req.user,
req.body || {}
);
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось завершить попытку', 'quiz attempt submit');
}
});
app.get('/api/quizzes/:id/stats', requireAuth, async (req, res) => {
try {
const result = await quizStats(pool, reqInt(req.params.id), req.user);
res.json(result);
} catch (e) {
quizError(res, e, 'Не удалось загрузить статистику', 'quiz stats');
}
});
app.get('/api/public-quizzes/:id', apiLimiter, async (req, res) => {
try {
res.json(await getPublicSurvey(pool, reqInt(req.params.id)));
} catch (e) {
quizError(res, e, 'Опрос не найден', 'public quiz get');
}
});
app.post('/api/public-quizzes/:id/attempts', apiLimiter, async (req, res) => {
try {
res.json(await startAnonymousAttempt(pool, reqInt(req.params.id)));
} catch (e) {
quizError(res, e, 'Не удалось начать прохождение', 'public quiz attempt start');
}
});
app.put('/api/public-quizzes/:id/attempts/:attemptId', apiLimiter, async (req, res) => {
try {
const token = typeof req.body?.token === 'string' ? req.body.token : '';
const result = await submitAnonymousAttempt(
pool,
reqInt(req.params.id),
reqInt(req.params.attemptId),
token,
req.body || {}
);
res.json({ attempt: result.attempt, anonymous: true });
} catch (e) {
quizError(res, e, 'Не удалось отправить ответы', 'public quiz attempt submit');
}
});
app.get('/api/public-quizzes/files/:name', fileLimiter, async (req, res) => {
const name = req.params.name;
if (!/^[\w,.()-]+$/.test(name)) return res.status(400).end();
try {
const { rows } = await pool.query(
`SELECT 1
FROM quiz_assets a
LEFT JOIN quiz_questions qq ON qq.id = a.question_id
LEFT JOIN quiz_options qo ON qo.id = a.option_id
LEFT JOIN quiz_questions oq ON oq.id = qo.question_id
JOIN quizzes q ON q.id = COALESCE(a.quiz_id, qq.quiz_id, oq.quiz_id)
WHERE a.path = $1
AND q.kind = 'survey' AND q.allow_anonymous = true
AND q.is_published = true AND q.deleted_at IS NULL
LIMIT 1`,
[`/uploads/${name}`]
);
if (!rows.length) return res.status(404).end();
const key = storage.keyFromPath(`/uploads/${name}`);
const kind = quizMediaKind(name);
if (req.query.play === '1' && (kind === 'audio' || kind === 'video')) {
const ok = await sendPlayableFile(req, res, key, name);
if (!ok && !res.headersSent) return res.status(404).end();
return;
}
const ok = await storage.streamTo(res, key, {
cacheControl: 'private, max-age=3600',
download: kind !== 'image',
name,
contentType: mimeFor(name),
});
if (!ok && !res.headersSent) return res.status(404).end();
} catch (e) {
console.error('Public quiz file failed:', name, e.message);
if (!res.headersSent) res.status(404).end();
}
});
setInterval(() => {
cleanupQuizAssets(pool, 24)
.then(r => unlinkQuizMedia(r.paths))
.catch(err => console.error('Quiz assets cleanup:', err.message));
}, 6 * 60 * 60 * 1000).unref();
// --- External API v1 ---
const apiV1 = express.Router();
apiV1.use(requireApiKey('read'));