- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js) - Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js) - Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES - Обновление AGENTS.md под новый функционал тестов/опросов
628 lines
28 KiB
JavaScript
628 lines
28 KiB
JavaScript
(function () {
|
||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||
const params = new URLSearchParams(location.search);
|
||
const quizId = parseInt(params.get('id'), 10);
|
||
const state = {
|
||
quiz: null,
|
||
questions: [],
|
||
quizAssets: [],
|
||
attempt: null,
|
||
selection: new Map(),
|
||
texts: new Map(),
|
||
timer: null,
|
||
result: null,
|
||
revealed: false,
|
||
tab: params.get('tab') === 'stats' ? 'stats' : params.get('tab') === 'attempts' ? 'attempts' : 'take',
|
||
};
|
||
|
||
function at(s) {
|
||
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
|
||
}
|
||
|
||
function fileUrl(asset) {
|
||
const name = String(asset.path || '').split('/').pop();
|
||
const play = asset.kind === 'audio' || asset.kind === 'video' ? '&play=1' : '';
|
||
return API + '/api/quizzes/files/' + encodeURIComponent(name) + '?token=' + encodeURIComponent(token || '') + play;
|
||
}
|
||
|
||
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(thumbSrc(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"><i data-lucide="file"></i> ${esc(a.original_name || 'Файл')}</a>`;
|
||
}
|
||
return `<div class="qz-asset">${inner}${a.caption ? `<div class="qz-asset-cap">${esc(a.caption)}</div>` : ''}</div>`;
|
||
});
|
||
return `<div class="qz-assets">${cards.join('')}</div>`;
|
||
}
|
||
|
||
function shuffle(list) {
|
||
const arr = list.slice();
|
||
for (let i = arr.length - 1; i > 0; i--) {
|
||
const j = Math.floor(Math.random() * (i + 1));
|
||
const tmp = arr[i];
|
||
arr[i] = arr[j];
|
||
arr[j] = tmp;
|
||
}
|
||
return arr;
|
||
}
|
||
|
||
function kindLabel(kind) {
|
||
return kind === 'survey' ? 'Опрос' : 'Тест';
|
||
}
|
||
|
||
function renderMd(text) {
|
||
if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.render === 'function') {
|
||
return WhatIDoMD.render(String(text || ''));
|
||
}
|
||
return esc(text);
|
||
}
|
||
|
||
function renderHead() {
|
||
const q = state.quiz;
|
||
const parts = [
|
||
`<div class="qz-head">`,
|
||
q.cover_path
|
||
? `<img class="qz-head-cover" src="${at(thumbSrc(q.cover_path))}" data-img="${at(API + q.cover_path)}" alt="Обложка">`
|
||
: '',
|
||
`<div class="qz-head-main">`,
|
||
`<div class="qz-title">${esc(q.title || 'Без названия')}</div>`,
|
||
`<div class="qz-sub">`,
|
||
`<span>${kindLabel(q.kind)}</span>`,
|
||
`<span>Вопросов: ${state.questions.length}</span>`,
|
||
q.author_name ? `<span>Автор: ${esc(q.author_name)}</span>` : '',
|
||
q.max_attempts != null ? `<span>Попыток: ${q.max_attempts}</span>` : '',
|
||
q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : '',
|
||
q.kind === 'test' ? `<span>Порог: ${q.pass_percent}%</span>` : '',
|
||
`</div>`,
|
||
`<div class="qz-badges">`,
|
||
`<span class="qz-badge${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`,
|
||
state.quiz.can_edit ? '<span class="qz-badge on">Редактирование доступно</span>' : '',
|
||
`</div>`,
|
||
q.description ? `<div class="qz-desc qz-q">${renderMd(q.description)}</div>` : '',
|
||
`</div>`,
|
||
`</div>`,
|
||
];
|
||
if (state.quizAssets.length) {
|
||
parts.push(`<div class="qz-panel"><div class="qz-hint" style="margin-bottom:6px">Материалы</div>${assetsHtml(state.quizAssets)}</div>`);
|
||
}
|
||
const head = document.getElementById('qzHead');
|
||
head.innerHTML = parts.filter(Boolean).join('');
|
||
renderIcons();
|
||
}
|
||
|
||
function renderTabs() {
|
||
const wrap = document.getElementById('qzTabs');
|
||
wrap.hidden = false;
|
||
document.getElementById('qzStatsTab').hidden = !state.quiz.can_edit;
|
||
wrap.querySelectorAll('.qz-tab').forEach(btn => {
|
||
btn.classList.toggle('on', btn.dataset.tab === state.tab);
|
||
});
|
||
}
|
||
|
||
function takeIntroHtml() {
|
||
const q = state.quiz;
|
||
if (!q.can_take && state.quiz.attempts_left === 0) {
|
||
return `<div class="qz-panel"><p class="qz-hint" style="margin:0 0 10px">Попытки закончились.</p>
|
||
${state.quiz.my_attempts.length ? `<a class="btn-primary ghost" href="#" data-act="open-attempt" data-attempt="${state.quiz.my_attempts[0].id}">Посмотреть последний результат</a>` : ''}</div>`;
|
||
}
|
||
if (!q.is_published) {
|
||
return '<div class="qz-panel"><p class="qz-hint" style="margin:0">Тест не опубликован. Пройти его может только автор после публикации.</p></div>';
|
||
}
|
||
return `<div class="qz-panel">
|
||
<div class="qz-sub" style="margin:0 0 10px">
|
||
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
|
||
${q.time_limit_min ? ` На прохождение отводится ${q.time_limit_min} мин.` : ''}
|
||
</div>
|
||
<button type="button" class="btn-primary" data-act="start">Начать</button>
|
||
</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="qz-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">${esc(value)}</textarea>${hint}`;
|
||
}
|
||
if (q.kind === 'number') {
|
||
return `<input type="number" step="any" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Число" value="${esc(value)}">`;
|
||
}
|
||
if (q.kind === 'date') {
|
||
return `<input type="date" class="settings-input qz-answer" data-qtext="${q.id}" value="${esc(value)}">`;
|
||
}
|
||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc(value)}">${hint}`;
|
||
}
|
||
|
||
function questionTakeHtml(q, index) {
|
||
const opts = q.options || [];
|
||
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>
|
||
${opts.map(o => `<option value="${o.id}"${chosen.has(Number(o.id)) ? ' selected' : ''}>${esc(o.text)}</option>`).join('')}
|
||
</select>${opts.map(o => o.description ? `<div class="qz-opt-desc" style="margin-top:6px">${esc(o.text)} — ${esc(o.description)}</div>` : '').join('')}`;
|
||
} else {
|
||
const items = opts.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">${esc(o.text)}${o.description ? `<div class="qz-opt-desc">${esc(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">${esc(q.text)}</span>
|
||
</div>
|
||
${q.description ? `<div class="qz-q-desc">${esc(q.description)}</div>` : ''}
|
||
${assetsHtml(q.assets)}
|
||
<div style="margin-top:8px">${body}</div>
|
||
</section>`;
|
||
}
|
||
|
||
function renderTake() {
|
||
const body = document.getElementById('qzBody');
|
||
if (!state.attempt) {
|
||
body.innerHTML = takeIntroHtml();
|
||
renderIcons();
|
||
return;
|
||
}
|
||
const list = state.questions.map(questionTakeHtml).join('');
|
||
const deadline = state.quiz.time_limit_min > 0
|
||
? new Date(state.attempt.started_at).getTime() + state.quiz.time_limit_min * 60000
|
||
: 0;
|
||
body.innerHTML = `<div class="qz-actions" style="margin-bottom:12px">
|
||
<span class="qz-timer" id="qzTimer"${deadline ? '' : ' hidden'}>—</span>
|
||
<span class="qz-hint" style="margin:0">Отвечено: <b id="qzProgress">0</b> из ${state.questions.length}</span>
|
||
<span style="flex:1"></span>
|
||
<button type="button" class="btn-link" data-act="restart">Начать заново</button>
|
||
<button type="button" class="btn-primary" data-act="submit">Отправить ответы</button>
|
||
</div>
|
||
<div id="qzQuestions">${list}</div>
|
||
<div class="qz-actions"><button type="button" class="btn-primary" data-act="submit">Отправить ответы</button></div>`;
|
||
renderIcons();
|
||
updateProgress();
|
||
startTimer(deadline);
|
||
}
|
||
|
||
function updateProgress() {
|
||
const el = document.getElementById('qzProgress');
|
||
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;
|
||
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;
|
||
}
|
||
|
||
function gradeBlock(grade) {
|
||
if (!grade) return '';
|
||
const img = grade.image_path
|
||
? `<img src="${at(thumbSrc(grade.image_path))}" alt="" style="width:52px;height:52px;object-fit:cover;border-radius:10px">`
|
||
: '';
|
||
return `<div style="margin-top:10px;display:flex;align-items:center;gap:10px">
|
||
${img}
|
||
<div><div style="font-size:.76rem;color:var(--muted);text-transform:uppercase;letter-spacing:.04em">Оценка</div>
|
||
<div style="font-weight:700;font-size:1.05rem">${esc(grade.label || '')}</div></div>
|
||
</div>`;
|
||
}
|
||
|
||
function renderResult() {
|
||
const body = document.getElementById('qzBody');
|
||
const attempt = state.attempt;
|
||
if (!attempt) return;
|
||
const pct = Number(attempt.percent || 0);
|
||
const grade = state.result && state.result.grade ? state.result.grade : null;
|
||
const head = `<div class="qz-panel">
|
||
<div class="qz-sub">${kindLabel(state.quiz.kind)} · ${fmtDateTime(attempt.finished_at || attempt.started_at)}</div>
|
||
${state.quiz.kind === 'test'
|
||
? `<div class="qz-score">${Number(attempt.score || 0).toFixed(2)} <small>из ${Number(attempt.max_score || 0).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||
<div class="qz-bar ${attempt.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>
|
||
<div class="qz-badges"><span class="qz-badge ${attempt.passed ? 'on' : 'warn'}">${attempt.passed ? 'Сдано' : 'Не сдано'}</span></div>
|
||
${gradeBlock(grade)}`
|
||
: '<div class="qz-hint" style="margin-top:6px">Ответы сохранены. Опрос не оценивается.</div>'}
|
||
</div>`;
|
||
let details = '';
|
||
if (state.result && Array.isArray(state.result.questions) && state.result.questions.length) {
|
||
details = state.result.questions.map((r, i) => {
|
||
const mark = r.is_correct === null ? '' : r.is_correct
|
||
? '<span class="qz-check ok">верно</span>'
|
||
: '<span class="qz-check bad">неверно</span>';
|
||
const local = state.questions.find(q => Number(q.id) === Number(r.question_id));
|
||
const picked = (r.option_ids || [])
|
||
.map(id => (local && local.options || []).find(o => Number(o.id) === Number(id)))
|
||
.filter(Boolean)
|
||
.map(o => o.text);
|
||
const pickedHtml = picked.length ? `<div class="qz-hint">Ответ: ${esc(picked.join(', '))}</div>` : '';
|
||
return `<section class="qz-q">
|
||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(r.text || '')}</span>
|
||
<span style="flex:1"></span>${mark}
|
||
${state.quiz.kind === 'test' && r.max_score ? `<span class="qz-hint">${Number(r.score).toFixed(2)} / ${Number(r.max_score).toFixed(2)}</span>` : ''}
|
||
</div>
|
||
${pickedHtml}
|
||
${r.text_answer ? `<div class="qz-hint">Ответ: ${esc(r.text_answer)}</div>` : ''}
|
||
</section>`;
|
||
}).join('');
|
||
} else if (state.quiz.kind === 'test') {
|
||
details = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Автор теста скрыл разбор ответов.</p></div>';
|
||
}
|
||
body.innerHTML = head + details;
|
||
renderIcons();
|
||
}
|
||
|
||
function renderAttemptDetail() {
|
||
const body = document.getElementById('qzBody');
|
||
const data = state.attemptDetail;
|
||
if (!data) return;
|
||
const a = data.attempt;
|
||
const pct = Number(a.percent || 0);
|
||
const head = `<div class="qz-panel">
|
||
<div class="qz-sub">${esc(a.user_name || '')} · ${fmtDateTime(a.finished_at || a.started_at)}</div>
|
||
${state.quiz.kind === 'test'
|
||
? `<div class="qz-score">${Number(a.score).toFixed(2)} <small>из ${Number(a.max_score).toFixed(2)} · ${pct.toFixed(1)}%</small></div>
|
||
<div class="qz-bar ${a.passed ? 'ok' : ''}" style="margin-top:10px"><span style="width:${Math.max(0, Math.min(100, pct))}%"></span></div>
|
||
${gradeBlock(data.grade)}`
|
||
: '<div class="qz-hint" style="margin-top:6px">Опрос не оценивается.</div>'}
|
||
</div>`;
|
||
const rows = (data.answers || []).map((row, i) => {
|
||
const q = row.question;
|
||
const selected = new Set((row.option_ids || []).map(Number));
|
||
const opts = q && q.options
|
||
? q.options.map(o => {
|
||
const okClass = data.revealed ? (o.is_correct ? ' ok' : selected.has(Number(o.id)) ? ' bad' : '') : (selected.has(Number(o.id)) ? ' ok' : '');
|
||
const tag = data.revealed && o.is_correct ? ' ✓' : '';
|
||
return `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">вес ${o.weight}</span>` : ''}</div>`;
|
||
}).join('')
|
||
: '';
|
||
return `<section class="qz-q">
|
||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(row.question_text || '')}</span>
|
||
<span style="flex:1"></span>
|
||
${data.revealed && row.is_correct !== null ? `<span class="qz-check ${row.is_correct ? 'ok' : 'bad'}">${row.is_correct ? 'верно' : 'неверно'}</span>` : ''}
|
||
${data.revealed && state.quiz.kind === 'test' ? `<span class="qz-hint">${Number(row.score).toFixed(2)} / ${Number(row.max_score).toFixed(2)}</span>` : ''}
|
||
</div>
|
||
${row.text_answer ? `<div class="qz-hint">Ответ: ${esc(row.text_answer)}</div>` : ''}
|
||
${opts}
|
||
</section>`;
|
||
}).join('');
|
||
body.innerHTML = head + (rows || '<div class="qz-panel"><p class="qz-hint" style="margin:0">Ответов нет.</p></div>')
|
||
+ '<div class="qz-actions"><button type="button" class="btn-primary ghost" data-act="tab" data-tab="attempts">К списку попыток</button></div>';
|
||
renderIcons();
|
||
}
|
||
|
||
async function renderAttempts() {
|
||
const body = document.getElementById('qzBody');
|
||
body.innerHTML = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Загрузка...</p></div>';
|
||
try {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts?limit=200', { headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить попытки');
|
||
const items = data.items || [];
|
||
if (!items.length) {
|
||
body.innerHTML = '<div class="qz-empty">Попыток пока нет</div>';
|
||
return;
|
||
}
|
||
const rows = items.map(a => `<tr>
|
||
<td>${esc(a.user_name || '—')}</td>
|
||
<td>${fmtDateTime(a.finished_at || a.started_at)}</td>
|
||
${state.quiz.kind === 'test' ? `<td>${Number(a.score).toFixed(2)} / ${Number(a.max_score).toFixed(2)}</td>
|
||
<td>${Number(a.percent).toFixed(1)}%</td>
|
||
<td>${a.passed ? '<span class="qz-check ok">сдано</span>' : '<span class="qz-check bad">не сдано</span>'}</td>` : '<td>—</td>'}
|
||
<td><button type="button" class="btn-link" data-act="open-attempt" data-attempt="${a.id}">Открыть</button></td>
|
||
</tr>`).join('');
|
||
body.innerHTML = `<div class="qz-panel"><table class="qz-table">
|
||
<thead><tr><th>Пользователь</th><th>Дата</th>${state.quiz.kind === 'test' ? '<th>Баллы</th><th>Процент</th><th>Итог</th>' : '<th>Оценка</th>'}<th></th></tr></thead>
|
||
<tbody>${rows}</tbody></table>
|
||
<div class="qz-hint" style="margin-top:8px">Всего попыток: ${data.total}</div></div>`;
|
||
} catch (e) {
|
||
body.innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
async function renderStats() {
|
||
const body = document.getElementById('qzBody');
|
||
body.innerHTML = '<div class="qz-panel"><p class="qz-hint" style="margin:0">Загрузка...</p></div>';
|
||
try {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId + '/stats', { headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить статистику');
|
||
const t = data.totals || {};
|
||
const totalAttempts = Number(t.attempts || 0);
|
||
const head = `<div class="qz-panel">
|
||
<div class="qz-sub" style="margin:0">
|
||
<span>Попыток: <b>${totalAttempts}</b></span>
|
||
<span>Участников: <b>${Number(t.users || 0)}</b></span>
|
||
${state.quiz.kind === 'test' ? `<span>Средний результат: <b>${Number(t.avg_percent || 0).toFixed(1)}%</b></span>
|
||
<span>Сдали: <b>${Number(t.passed || 0)}</b></span>` : ''}
|
||
</div>
|
||
</div>`;
|
||
const questions = (data.questions || []).map((q, i) => {
|
||
const opts = (q.options || []).map(o => {
|
||
const share = totalAttempts ? (o.count / totalAttempts) * 100 : 0;
|
||
return `<div style="margin-top:8px">
|
||
<div class="qz-stat-row"><span>${esc(o.text)}${o.is_correct ? ' <span class="qz-check ok">✓</span>' : ''}</span><span>${o.count} · ${share.toFixed(0)}%</span></div>
|
||
<div class="qz-bar${o.is_correct ? ' ok' : ''}"><span style="width:${Math.max(0, Math.min(100, share))}%"></span></div>
|
||
</div>`;
|
||
}).join('');
|
||
const texts = (q.texts || []).length
|
||
? `<div class="qz-hint" style="margin-top:8px">Текстовые ответы (${q.texts.length}): ${q.texts.slice(0, 20).map(x => `«${esc(x)}»`).join(', ')}${q.texts.length > 20 ? ' …' : ''}</div>`
|
||
: '';
|
||
return `<section class="qz-q">
|
||
<div class="qz-q-head"><span class="qz-q-num">${i + 1}</span><span class="qz-q-text">${esc(q.text)}</span></div>
|
||
${opts}${texts}
|
||
</section>`;
|
||
}).join('');
|
||
body.innerHTML = head + (questions || '<div class="qz-empty">Вопросов нет</div>');
|
||
renderIcons();
|
||
} catch (e) {
|
||
body.innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
function renderTab() {
|
||
renderTabs();
|
||
if (state.tab === 'attempts') { renderAttempts(); return; }
|
||
if (state.tab === 'stats') { renderStats(); return; }
|
||
if (state.attemptDetail) { renderAttemptDetail(); return; }
|
||
if (state.result) { renderResult(); return; }
|
||
renderTake();
|
||
}
|
||
|
||
async function start() {
|
||
try {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts', { method: 'POST', headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось начать');
|
||
state.attempt = data.attempt;
|
||
if (data.quiz) {
|
||
state.quiz.can_take = data.quiz.can_take;
|
||
state.questions = data.quiz.questions || state.questions;
|
||
}
|
||
state.selection = new Map();
|
||
state.texts = new Map();
|
||
state.result = null;
|
||
state.attemptDetail = null;
|
||
renderTake();
|
||
} catch (e) {
|
||
showToast(e.message, true);
|
||
}
|
||
}
|
||
|
||
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) {
|
||
showToast(`Вопрос ${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/quizzes/' + quizId + '/attempts/' + state.attempt.id, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ answers }),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||
stopTimer();
|
||
state.attempt = data.attempt;
|
||
state.result = data.result;
|
||
state.revealed = data.revealed;
|
||
state.tab = 'take';
|
||
renderTab();
|
||
await loadQuiz(true);
|
||
showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены');
|
||
} catch (e) {
|
||
showToast(e.message, true);
|
||
if (btn) btn.disabled = false;
|
||
}
|
||
}
|
||
|
||
async function restart() {
|
||
if (!confirm('Начать попытку заново? Текущие ответы не сохранятся.')) return;
|
||
try {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/restart', {
|
||
method: 'POST',
|
||
headers: hdr(),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось начать заново');
|
||
stopTimer();
|
||
state.attempt = data.attempt;
|
||
state.result = null;
|
||
state.attemptDetail = null;
|
||
state.selection = new Map();
|
||
state.texts = new Map();
|
||
renderTake();
|
||
} catch (e) {
|
||
showToast(e.message, true);
|
||
}
|
||
}
|
||
|
||
async function openAttempt(id) {
|
||
try {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/' + id, { headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить попытку');
|
||
state.attemptDetail = data;
|
||
state.tab = 'take';
|
||
renderTab();
|
||
} catch (e) {
|
||
showToast(e.message, true);
|
||
}
|
||
}
|
||
|
||
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 => {
|
||
const el = e.target;
|
||
if (el.dataset.qtext) {
|
||
state.texts.set(Number(el.dataset.qtext), el.value);
|
||
updateProgress();
|
||
}
|
||
});
|
||
document.addEventListener('click', e => {
|
||
const tabBtn = e.target.closest('[data-act="tab"]');
|
||
if (tabBtn) {
|
||
e.preventDefault();
|
||
state.tab = tabBtn.dataset.tab || 'take';
|
||
state.attemptDetail = null;
|
||
renderTab();
|
||
return;
|
||
}
|
||
const startBtn = e.target.closest('[data-act="start"]');
|
||
if (startBtn) { e.preventDefault(); start(); return; }
|
||
const subBtn = e.target.closest('[data-act="submit"]');
|
||
if (subBtn) { e.preventDefault(); submit(false); return; }
|
||
const restartBtn = e.target.closest('[data-act="restart"]');
|
||
if (restartBtn) { e.preventDefault(); restart(); return; }
|
||
const open = e.target.closest('[data-act="open-attempt"]');
|
||
if (open) { e.preventDefault(); openAttempt(open.dataset.attempt); return; }
|
||
const tab = e.target.closest('.qz-tab');
|
||
if (tab) {
|
||
state.tab = tab.dataset.tab;
|
||
state.attemptDetail = null;
|
||
renderTab();
|
||
}
|
||
});
|
||
window.addEventListener('beforeunload', e => {
|
||
if (!state.attempt || state.result) return;
|
||
e.preventDefault();
|
||
e.returnValue = '';
|
||
});
|
||
}
|
||
|
||
async function loadQuiz(keepResult) {
|
||
const res = await fetch(API + '/api/quizzes/' + quizId, { headers: hdr() });
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тест');
|
||
const prevResult = keepResult ? state.result : null;
|
||
const prevAttempt = keepResult ? state.attempt : null;
|
||
state.quiz = data.quiz;
|
||
state.quiz.can_edit = data.can_edit;
|
||
state.quiz.can_take = data.can_take;
|
||
state.quiz.attempts_left = data.attempts_left;
|
||
state.quiz.my_attempts = data.my_attempts || [];
|
||
state.quizAssets = data.quiz_assets || [];
|
||
state.questions = (data.questions || []).map(q => ({ ...q }));
|
||
if (state.quiz.shuffle_questions && !prevAttempt) state.questions = shuffle(state.questions);
|
||
if (state.quiz.shuffle_options) {
|
||
state.questions = state.questions.map(q => ({ ...q, options: shuffle(q.options || []) }));
|
||
}
|
||
if (!keepResult) {
|
||
state.attempt = data.current_attempt || null;
|
||
state.result = null;
|
||
state.revealed = false;
|
||
state.selection = new Map();
|
||
state.texts = new Map();
|
||
} else {
|
||
state.attempt = prevAttempt;
|
||
state.result = prevResult;
|
||
}
|
||
if (!state.quiz.can_edit && state.tab === 'stats') state.tab = 'take';
|
||
}
|
||
|
||
async function init() {
|
||
if (!Number.isInteger(quizId) || quizId < 1) {
|
||
document.getElementById('qzHead').innerHTML = '<div class="qz-error">Неверный адрес теста</div>';
|
||
return;
|
||
}
|
||
if (!(await checkAuth())) return;
|
||
buildSidebar(document.body.dataset.page);
|
||
bind();
|
||
try {
|
||
await loadQuiz(false);
|
||
renderHead();
|
||
renderTab();
|
||
} catch (e) {
|
||
document.getElementById('qzHead').innerHTML = `<div class="qz-error">${esc(e.message)}</div>`;
|
||
}
|
||
}
|
||
|
||
init();
|
||
})();
|