Тесты и опросы: модуль тестов, анонимные опросы, страницы и бэкап
- 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:
@@ -0,0 +1,354 @@
|
||||
(function () {
|
||||
const API = location.origin;
|
||||
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
const state = {
|
||||
quiz: null,
|
||||
questions: [],
|
||||
quizAssets: [],
|
||||
attempt: null,
|
||||
selection: new Map(),
|
||||
texts: new Map(),
|
||||
timer: null,
|
||||
done: false,
|
||||
};
|
||||
|
||||
function esc2(v) {
|
||||
return String(v == null ? '' : v)
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
}
|
||||
|
||||
function at(v) {
|
||||
return esc2(v);
|
||||
}
|
||||
|
||||
function thumb(p) {
|
||||
const path = String(p || '');
|
||||
if (path.startsWith('/uploads/')) return '/uploads/thumb/' + path.slice('/uploads/'.length);
|
||||
return path;
|
||||
}
|
||||
|
||||
function renderMd(text) {
|
||||
if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.render === 'function') {
|
||||
return WhatIDoMD.render(String(text || ''));
|
||||
}
|
||||
return esc2(text);
|
||||
}
|
||||
|
||||
function fileUrl(asset) {
|
||||
const name = String(asset.path || '').split('/').pop();
|
||||
const play = asset.kind === 'audio' || asset.kind === 'video' ? '&play=1' : '';
|
||||
return API + '/api/public-quizzes/files/' + encodeURIComponent(name) + '?x=1' + play;
|
||||
}
|
||||
|
||||
function toast(message, isError) {
|
||||
const el = document.getElementById('toast');
|
||||
if (!el) return;
|
||||
el.textContent = message;
|
||||
el.className = 'toast show' + (isError ? ' error' : '');
|
||||
clearTimeout(toast.t);
|
||||
toast.t = setTimeout(() => { el.className = 'toast'; }, 3200);
|
||||
}
|
||||
|
||||
function assetsHtml(list) {
|
||||
if (!Array.isArray(list) || !list.length) return '';
|
||||
const cards = list.map(a => {
|
||||
let inner;
|
||||
if (a.kind === 'image') {
|
||||
inner = `<img src="${at(thumb(a.path))}" data-img="${at(API + a.path)}" alt="${at(a.original_name || '')}">`;
|
||||
} else if (a.kind === 'audio') {
|
||||
inner = `<audio controls preload="none" src="${at(fileUrl(a))}"></audio>`;
|
||||
} else if (a.kind === 'video') {
|
||||
inner = `<video controls preload="metadata" src="${at(fileUrl(a))}"></video>`;
|
||||
} else {
|
||||
inner = `<a href="${at(fileUrl(a))}" target="_blank" rel="noopener noreferrer">${esc2(a.original_name || 'Файл')}</a>`;
|
||||
}
|
||||
return `<div class="qz-asset">${inner}${a.caption ? `<div class="qz-asset-cap">${esc2(a.caption)}</div>` : ''}</div>`;
|
||||
});
|
||||
return `<div class="qz-assets">${cards.join('')}</div>`;
|
||||
}
|
||||
|
||||
function isFree(kind) {
|
||||
return FREE_KINDS.includes(kind);
|
||||
}
|
||||
|
||||
function freeAnswerHtml(q) {
|
||||
const value = state.texts.get(q.id) || '';
|
||||
const hint = q.required !== false && q.min_length > 0
|
||||
? `<div class="qp-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
||||
: '';
|
||||
if (q.kind === 'text') {
|
||||
return `<textarea class="settings-input qz-answer" rows="3" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000">${esc2(value)}</textarea>${hint}`;
|
||||
}
|
||||
if (q.kind === 'number') {
|
||||
return `<input type="number" step="any" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Число" value="${esc2(value)}">`;
|
||||
}
|
||||
if (q.kind === 'date') {
|
||||
return `<input type="date" class="settings-input qz-answer" data-qtext="${q.id}" value="${esc2(value)}">`;
|
||||
}
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc2(value)}">${hint}`;
|
||||
}
|
||||
|
||||
function questionHtml(q, index) {
|
||||
const chosen = state.selection.get(q.id) || new Set();
|
||||
let body;
|
||||
if (isFree(q.kind)) {
|
||||
body = freeAnswerHtml(q);
|
||||
} else if (q.kind === 'select') {
|
||||
body = `<select class="settings-input qz-answer" data-q="${q.id}">
|
||||
<option value="">— выберите —</option>
|
||||
${(q.options || []).map(o => `<option value="${o.id}"${chosen.has(Number(o.id)) ? ' selected' : ''}>${esc2(o.text)}</option>`).join('')}
|
||||
</select>`;
|
||||
} else {
|
||||
const items = (q.options || []).map(o => {
|
||||
const checked = chosen.has(Number(o.id)) ? ' checked' : '';
|
||||
const input = q.kind === 'multiple'
|
||||
? `<input type="checkbox" data-q="${q.id}" data-opt="${o.id}"${checked}>`
|
||||
: `<input type="radio" name="q${q.id}" data-q="${q.id}" data-opt="${o.id}"${checked}>`;
|
||||
return `<label class="qz-opt">${input}<span class="qz-opt-text">${esc2(o.text)}${o.description ? `<div class="qz-opt-desc">${esc2(o.description)}</div>` : ''}${assetsHtml(o.assets)}</span></label>`;
|
||||
}).join('');
|
||||
body = `<div class="qz-opts${q.options_inline ? ' inline' : ''}">${items}</div>`;
|
||||
}
|
||||
return `<section class="qz-q">
|
||||
<div class="qz-q-head"><span class="qz-q-num">${index + 1}</span><span class="qz-q-text">${esc2(q.text)}</span></div>
|
||||
${q.description ? `<div class="qz-q-desc">${esc2(q.description)}</div>` : ''}
|
||||
${assetsHtml(q.assets)}
|
||||
<div style="margin-top:8px">${body}</div>
|
||||
</section>`;
|
||||
}
|
||||
|
||||
function introHtml() {
|
||||
const q = state.quiz;
|
||||
return `<div class="qp-card">
|
||||
${q.cover_path ? `<img class="qp-cover" src="${at(thumb(q.cover_path))}" data-img="${at(API + q.cover_path)}" alt="Обложка">` : ''}
|
||||
<div class="qp-title">${esc2(q.title || 'Опрос')}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}</div>
|
||||
${q.description ? `<div class="qp-desc">${renderMd(q.description)}</div>` : ''}
|
||||
${assetsHtml(state.quizAssets)}
|
||||
<div class="qp-actions">
|
||||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||||
<span class="qp-hint">Ответы сохраняются без имени и входа в систему.</span>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function renderQuestions() {
|
||||
return `<div class="qp-card">
|
||||
<div class="qp-title">${esc2(state.quiz.title || 'Опрос')}</div>
|
||||
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span></div>
|
||||
<div class="qp-actions">
|
||||
<span class="qz-timer" id="qzTimer" hidden>—</span>
|
||||
<span class="qp-hint">Отвечено: <b id="qpProgress">0</b> из ${state.questions.length}</span>
|
||||
</div>
|
||||
${state.questions.map(questionHtml).join('')}
|
||||
<div class="qp-actions">
|
||||
<button type="button" class="btn-primary" data-act="submit">Отправить ответы</button>
|
||||
</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function render() {
|
||||
const body = document.getElementById('qpBody');
|
||||
if (!state.quiz) return;
|
||||
body.innerHTML = state.attempt ? renderQuestions() : introHtml();
|
||||
if (state.attempt) {
|
||||
updateProgress();
|
||||
const deadline = state.quiz.time_limit_min > 0
|
||||
? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000
|
||||
: 0;
|
||||
startTimer(deadline);
|
||||
}
|
||||
}
|
||||
|
||||
function updateProgress() {
|
||||
const el = document.getElementById('qpProgress');
|
||||
if (!el) return;
|
||||
let done = 0;
|
||||
for (const q of state.questions) {
|
||||
if (isFree(q.kind)) {
|
||||
if (String(state.texts.get(q.id) || '').trim()) done++;
|
||||
} else if ((state.selection.get(q.id) || new Set()).size) {
|
||||
done++;
|
||||
}
|
||||
}
|
||||
el.textContent = String(done);
|
||||
}
|
||||
|
||||
function startTimer(deadline) {
|
||||
stopTimer();
|
||||
const el = document.getElementById('qzTimer');
|
||||
if (!el || !deadline) return;
|
||||
el.hidden = false;
|
||||
const tick = () => {
|
||||
const left = Math.max(0, deadline - Date.now());
|
||||
const min = Math.floor(left / 60000);
|
||||
const sec = Math.floor((left % 60000) / 1000);
|
||||
el.textContent = `Осталось: ${min}:${String(sec).padStart(2, '0')}`;
|
||||
el.classList.toggle('low', left < 60000);
|
||||
if (left <= 0) {
|
||||
stopTimer();
|
||||
submit(true);
|
||||
}
|
||||
};
|
||||
tick();
|
||||
state.timer = setInterval(tick, 1000);
|
||||
}
|
||||
|
||||
function stopTimer() {
|
||||
if (state.timer) clearInterval(state.timer);
|
||||
state.timer = null;
|
||||
}
|
||||
|
||||
async function start() {
|
||||
const btn = document.querySelector('[data-act="start"]');
|
||||
if (btn) btn.disabled = true;
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', { method: 'POST' });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
|
||||
state.attempt = { id: data.attempt.id, started_at: data.attempt.started_at, anon_token: data.attempt.anon_token };
|
||||
if (data.quiz) {
|
||||
state.quiz = data.quiz.quiz || state.quiz;
|
||||
state.questions = data.quiz.questions || state.questions;
|
||||
state.quizAssets = data.quiz.quiz_assets || state.quizAssets;
|
||||
}
|
||||
render();
|
||||
window.scrollTo({ top: 0, behavior: 'smooth' });
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function submit(auto) {
|
||||
if (!state.attempt) return;
|
||||
if (!auto) {
|
||||
for (let i = 0; i < state.questions.length; i++) {
|
||||
const q = state.questions[i];
|
||||
if (!isFree(q.kind) || q.required === false || !(q.min_length > 0)) continue;
|
||||
const value = String(state.texts.get(q.id) || '').trim();
|
||||
if (value.length < q.min_length) {
|
||||
toast(`Вопрос ${i + 1}: минимум ${q.min_length} символов`, true);
|
||||
return;
|
||||
}
|
||||
}
|
||||
const missing = state.questions.filter(q => {
|
||||
if (q.required === false) return false;
|
||||
return isFree(q.kind)
|
||||
? !String(state.texts.get(q.id) || '').trim()
|
||||
: !(state.selection.get(q.id) || new Set()).size;
|
||||
}).length;
|
||||
if (missing && !confirm(`Без ответа осталось вопросов: ${missing}. Отправить?`)) return;
|
||||
}
|
||||
const btn = document.querySelector('[data-act="submit"]');
|
||||
if (btn) btn.disabled = true;
|
||||
const answers = state.questions.map(q => ({
|
||||
question_id: q.id,
|
||||
option_ids: isFree(q.kind) ? [] : [...(state.selection.get(q.id) || new Set())],
|
||||
text: isFree(q.kind) ? (state.texts.get(q.id) || '') : '',
|
||||
}));
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ token: state.attempt.anon_token, answers }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
stopTimer();
|
||||
state.done = true;
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
|
||||
<div class="qp-done-ic">✓</div>
|
||||
<div class="qp-title">Спасибо!</div>
|
||||
<p class="qp-hint" style="margin-top:8px">Ответы сохранены.</p>
|
||||
<div class="qp-actions" style="justify-content:center">
|
||||
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
|
||||
</div>
|
||||
</div>`;
|
||||
} catch (e) {
|
||||
toast(e.message, true);
|
||||
if (btn) btn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
function bind() {
|
||||
document.addEventListener('change', e => {
|
||||
const el = e.target;
|
||||
if (el.tagName === 'SELECT' && el.dataset.q) {
|
||||
const qid = Number(el.dataset.q);
|
||||
const oid = Number(el.value);
|
||||
state.selection.set(qid, oid ? new Set([oid]) : new Set());
|
||||
updateProgress();
|
||||
return;
|
||||
}
|
||||
if (el.dataset.q && el.dataset.opt) {
|
||||
const qid = Number(el.dataset.q);
|
||||
const oid = Number(el.dataset.opt);
|
||||
let set = state.selection.get(qid);
|
||||
if (!set) { set = new Set(); state.selection.set(qid, set); }
|
||||
if (el.type === 'radio') {
|
||||
set.clear();
|
||||
set.add(oid);
|
||||
} else if (el.checked) set.add(oid);
|
||||
else set.delete(oid);
|
||||
updateProgress();
|
||||
}
|
||||
});
|
||||
document.addEventListener('input', e => {
|
||||
if (e.target.dataset.qtext) {
|
||||
state.texts.set(Number(e.target.dataset.qtext), e.target.value);
|
||||
updateProgress();
|
||||
}
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
const act = e.target.closest('[data-act]');
|
||||
if (act) {
|
||||
if (act.dataset.act === 'start') { e.preventDefault(); start(); return; }
|
||||
if (act.dataset.act === 'submit') { e.preventDefault(); submit(false); return; }
|
||||
if (act.dataset.act === 'again') { e.preventDefault(); location.reload(); return; }
|
||||
}
|
||||
const themeBtn = e.target.closest('[data-theme-toggle]');
|
||||
if (themeBtn) { e.preventDefault(); if (window.WhatIDoTheme) WhatIDoTheme.next(); return; }
|
||||
const img = e.target.closest('[data-img]');
|
||||
if (img) {
|
||||
e.preventDefault();
|
||||
const modal = document.getElementById('imgModal');
|
||||
document.getElementById('imgModalSrc').src = img.dataset.img;
|
||||
modal.classList.add('open');
|
||||
}
|
||||
});
|
||||
document.getElementById('imgModal').addEventListener('click', e => {
|
||||
if (e.target.id !== 'imgModalSrc') e.target.classList.remove('open');
|
||||
});
|
||||
window.addEventListener('beforeunload', e => {
|
||||
if (!state.attempt || state.done) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
});
|
||||
}
|
||||
|
||||
async function init() {
|
||||
if (!Number.isInteger(quizId) || quizId < 1) {
|
||||
document.getElementById('qpBody').innerHTML = '<div class="qp-error">Неверная ссылка на опрос</div>';
|
||||
return;
|
||||
}
|
||||
bind();
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-quizzes/' + quizId);
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Опрос не найден');
|
||||
state.quiz = data.quiz;
|
||||
state.questions = data.questions || [];
|
||||
state.quizAssets = data.quiz_assets || [];
|
||||
document.title = (state.quiz.title || 'Опрос') + ' — опрос';
|
||||
render();
|
||||
} catch (e) {
|
||||
document.getElementById('qpBody').innerHTML = `<div class="qp-error">${esc2(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
init();
|
||||
})();
|
||||
Reference in New Issue
Block a user