(function () { const SYSTEM_KINDS = ['student', 'group', 'branch', 'module']; const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS]; const SYSTEM_LABELS = { student: 'ученика', group: 'группы', branch: 'филиала', module: 'темы модуля' }; 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(), systemIds: new Map(), sugTimers: new Map(), timer: null, retryTimer: null, result: null, revealed: false, tab: params.get('tab') === 'stats' ? 'stats' : params.get('tab') === 'attempts' ? 'attempts' : 'take', statsFilters: { date_from: '', date_to: '', student_id: '', group_id: '', branch_id: '', module_id: '' }, }; 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 = `${at(a.original_name || '')}`; } else if (a.kind === 'audio') { inner = ``; } else if (a.kind === 'video') { inner = ``; } else { inner = ` ${esc(a.original_name || 'Файл')}`; } return `
${inner}${a.caption ? `
${esc(a.caption)}
` : ''}
`; }); return `
${cards.join('')}
`; } 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 retryKey() { return 'whatido_quiz_retry_' + quizId; } function retryUntil() { const min = Number(state.quiz && state.quiz.retry_cooldown_min) || 0; if (min <= 0) return 0; let raw = null; try { raw = localStorage.getItem(retryKey()); } catch (e) { raw = null; } const at = parseInt(raw, 10); if (!Number.isFinite(at)) return 0; const until = at + min * 60000; if (Date.now() >= until) { try { localStorage.removeItem(retryKey()); } catch (e) { /* ignore */ } return 0; } return until; } function markRetry() { if (!(Number(state.quiz && state.quiz.retry_cooldown_min) > 0)) return; try { localStorage.setItem(retryKey(), String(Date.now())); } catch (e) { /* ignore */ } } function retryLeftText(until) { const left = Math.max(0, until - Date.now()); const min = Math.floor(left / 60000); const sec = Math.floor((left % 60000) / 1000); return `Повторно пройти можно через ${min} мин ${sec} сек`; } function stopRetryTimer() { if (state.retryTimer) clearInterval(state.retryTimer); state.retryTimer = null; } function startRetryTimer(until) { stopRetryTimer(); const tick = () => { const el = document.getElementById('qzRetryTimer'); if (!el) { stopRetryTimer(); return; } if (Date.now() >= until) { stopRetryTimer(); renderTab(); return; } el.textContent = retryLeftText(until); }; tick(); state.retryTimer = setInterval(tick, 1000); } 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 renderMdInline(text) { if (typeof WhatIDoMD !== 'undefined' && WhatIDoMD && typeof WhatIDoMD.inline === 'function') { return WhatIDoMD.inline(String(text || '')); } return esc(text); } function renderHead() { const q = state.quiz; const parts = [ `
`, q.cover_path ? `Обложка` : '', `
`, `
${esc(q.title || 'Без названия')}
`, `
`, `${kindLabel(q.kind)}`, `Вопросов: ${state.questions.length}`, q.author_name ? `Автор: ${esc(q.author_name)}` : '', q.max_attempts != null ? `Попыток: ${q.max_attempts}` : '', q.time_limit_min ? `Время: ${q.time_limit_min} мин` : '', q.retry_cooldown_min ? `Повтор: через ${q.retry_cooldown_min} мин` : '', q.kind === 'test' ? `Порог: ${q.pass_percent}%` : '', `
`, `
`, `${q.is_published ? 'Опубликован' : 'Черновик'}`, state.quiz.can_edit ? 'Редактирование доступно' : '', `
`, q.description ? `
${renderMd(q.description)}
` : '', `
`, `
`, ]; if (state.quizAssets.length) { parts.push(`
Материалы
${assetsHtml(state.quizAssets)}
`); } 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.stats_available; 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 `

Попытки закончились.

${state.quiz.my_attempts.length ? `Посмотреть последний результат` : ''}
`; } if (!q.is_published) { return '

Тест не опубликован. Пройти его может только автор после публикации.

'; } const until = retryUntil(); if (until) { return `

Вы уже прошли ${q.kind === 'survey' ? 'этот опрос' : 'этот тест'} в этом браузере.

${retryLeftText(until)}

`; } return `
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'} ${q.time_limit_min ? ` На прохождение отводится ${q.time_limit_min} мин.` : ''}
`; } function isFree(kind) { return FREE_KINDS.includes(kind); } function isSystemKind(kind) { return SYSTEM_KINDS.includes(kind); } function systemAnswerHtml(q) { const value = state.texts.get(q.id) || ''; const picked = state.systemIds.get(q.id) || ''; const label = SYSTEM_LABELS[q.kind] || 'названия'; return `
`; } function freeAnswerHtml(q) { if (isSystemKind(q.kind)) return systemAnswerHtml(q); const value = state.texts.get(q.id) || ''; const hint = q.required !== false && q.min_length > 0 ? `
Минимум ${q.min_length} символов
` : ''; if (q.kind === 'text') { return `${hint}`; } if (q.kind === 'number') { return ``; } if (q.kind === 'date') { return ``; } return `${hint}`; } async function systemLookup(qid, kind, term) { const box = document.querySelector('[data-sug="' + qid + '"]'); if (!box) return; const text = String(term || '').trim(); if (!text) { box.hidden = true; box.innerHTML = ''; return; } try { const res = await fetch(API + '/api/quizzes/system-options?field=' + encodeURIComponent(kind) + '&q=' + encodeURIComponent(text), { headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) { box.hidden = true; return; } const items = Array.isArray(data.items) ? data.items : []; box.innerHTML = items.length ? items.map(it => ``).join('') : '
Ничего не найдено
'; box.hidden = false; } catch (e) { box.hidden = true; } } 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 = `${opts.map(o => o.description ? `
${esc(o.text)} — ${renderMdInline(o.description)}
` : '').join('')}`; } else { const items = opts.map(o => { const checked = chosen.has(Number(o.id)) ? ' checked' : ''; const input = q.kind === 'multiple' ? `` : ``; return ``; }).join(''); body = `
${items}
`; } return `
${index + 1} ${esc(q.text)}
${q.description ? `
${renderMd(q.description)}
` : ''} ${assetsHtml(q.assets)}
${body}
`; } function renderTake() { const body = document.getElementById('qzBody'); if (!state.attempt) { body.innerHTML = takeIntroHtml(); renderIcons(); const until = retryUntil(); if (until) startRetryTimer(until); else stopRetryTimer(); return; } stopRetryTimer(); 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 = `
— Отвечено: 0 из ${state.questions.length}
${list}
`; 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 ? `` : ''; return `
${img}
Оценка
${esc(grade.label || '')}
`; } 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 = `
${kindLabel(state.quiz.kind)} · ${fmtDateTime(attempt.finished_at || attempt.started_at)}
${state.quiz.kind === 'test' ? `
${Number(attempt.score || 0).toFixed(2)} из ${Number(attempt.max_score || 0).toFixed(2)} · ${pct.toFixed(1)}%
${attempt.passed ? 'Сдано' : 'Не сдано'}
${gradeBlock(grade)}` : '
Ответы сохранены. Опрос не оценивается.
'}
`; 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 ? 'верно' : 'неверно'; 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 ? `
Ответ: ${esc(picked.join(', '))}
` : ''; return `
${i + 1}${esc(r.text || '')} ${mark} ${state.quiz.kind === 'test' && r.max_score ? `${Number(r.score).toFixed(2)} / ${Number(r.max_score).toFixed(2)}` : ''}
${pickedHtml} ${r.text_answer ? `
Ответ: ${esc(r.text_answer)}
` : ''}
`; }).join(''); } else if (state.quiz.kind === 'test') { details = '

Автор теста скрыл разбор ответов.

'; } 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 = `
${esc(a.user_name || '')} · ${fmtDateTime(a.finished_at || a.started_at)}
${state.quiz.kind === 'test' ? `
${Number(a.score).toFixed(2)} из ${Number(a.max_score).toFixed(2)} · ${pct.toFixed(1)}%
${gradeBlock(data.grade)}` : '
Опрос не оценивается.
'}
`; 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 `
${esc(o.text)}${tag}${data.revealed && o.weight ? `балл ${o.weight}` : ''}
`; }).join('') : ''; return `
${i + 1}${esc(row.question_text || '')} ${data.revealed && row.is_correct !== null ? `${row.is_correct ? 'верно' : 'неверно'}` : ''} ${data.revealed && state.quiz.kind === 'test' ? `${Number(row.score).toFixed(2)} / ${Number(row.max_score).toFixed(2)}` : ''}
${row.text_answer ? `
Ответ: ${esc(row.text_answer)}
` : ''} ${opts}
`; }).join(''); body.innerHTML = head + (rows || '

Ответов нет.

') + '
'; renderIcons(); } async function renderAttempts() { const body = document.getElementById('qzBody'); body.innerHTML = '

Загрузка...

'; 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 = '
Попыток пока нет
'; return; } const rows = items.map(a => ` ${esc(a.user_name || '—')} ${fmtDateTime(a.finished_at || a.started_at)} ${state.quiz.kind === 'test' ? `${Number(a.score).toFixed(2)} / ${Number(a.max_score).toFixed(2)} ${Number(a.percent).toFixed(1)}% ${a.passed ? 'сдано' : 'не сдано'}` : '—'} `).join(''); body.innerHTML = `
${state.quiz.kind === 'test' ? '' : ''}${rows}
ПользовательДатаБаллыПроцентИтогОценка
Всего попыток: ${data.total}
`; } catch (e) { body.innerHTML = `
${esc(e.message)}
`; } } function statsFilterSelect(key, label, items) { if (!Array.isArray(items) || !items.length) return ''; const cur = String(state.statsFilters[key] || ''); const opts = [''].concat(items.map(x => { const id = String(x.id); return ``; })).join(''); return ``; } function statsResetFilters() { Object.keys(state.statsFilters).forEach(k => { state.statsFilters[k] = ''; }); renderStats(); } function statsBlock(title, rows, nameLabel) { if (!rows.length) return ''; const isTest = state.quiz.kind === 'test'; const shown = rows.slice(0, 300); const trs = shown.map(r => ` ${esc(r.name || '—')} ${r.attempts} ${isTest ? `${Number(r.avg_percent || 0).toFixed(1)}%${Number(r.passed || 0)}` : ''} `).join(''); return `
${title}${rows.length}
${isTest ? '' : ''}${trs}
${nameLabel}ПопытокСредний %Сдали
${rows.length > 300 ? `
Показаны первые 300 из ${rows.length}
` : ''}
`; } async function renderStats() { const body = document.getElementById('qzBody'); body.innerHTML = '

Загрузка...

'; try { const f = state.statsFilters; const qs = new URLSearchParams(); ['date_from', 'date_to', 'student_id', 'group_id', 'branch_id', 'module_id'].forEach(k => { if (f[k]) qs.set(k, f[k]); }); const res = await fetch(API + '/api/quizzes/' + quizId + '/stats' + (qs.toString() ? '?' + qs.toString() : ''), { headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось загрузить статистику'); const t = data.totals || {}; const isTest = state.quiz.kind === 'test'; const totalAttempts = Number(t.attempts || 0); const allAttempts = Number(data.all_attempts || 0); const filtered = Object.keys(f).some(k => f[k]); const stats = [ `Попыток: ${totalAttempts}${filtered ? ` из ${allAttempts}` : ''}`, `Участников: ${Number(t.users || 0)}`, ]; if (Number(t.anonymous || 0) > 0) stats.push(`Анонимных: ${Number(t.anonymous)}`); if (isTest) { stats.push(`Средний результат: ${Number(t.avg_percent || 0).toFixed(1)}%`); stats.push(`Сдали: ${Number(t.passed || 0)} (${Number(t.pass_rate || 0).toFixed(1)}%)`); } const available = data.available || {}; const filtersHtml = `
${statsFilterSelect('group_id', 'Группа', available.groups)} ${statsFilterSelect('student_id', 'Ученик', available.students)} ${statsFilterSelect('branch_id', 'Филиал', available.branches)} ${statsFilterSelect('module_id', 'Тема модуля', available.modules)} ${filtered ? '' : ''}
Разрезы строятся по ответам на системные поля «Ученик», «Группа», «Филиал», «Тема модуля» и по дате завершения попытки.
`; const head = `
${stats.join('')}
`; const dates = (data.dates || []).map(d => ({ ...d, name: fmtDateOnlyIso(d.date) })); const blocks = [ statsBlock('По дням', dates, 'Дата'), statsBlock('По группам', data.groups || [], 'Группа'), statsBlock('По ученикам', data.students || [], 'Ученик'), statsBlock('По филиалам', data.branches || [], 'Филиал'), statsBlock('По темам модулей', data.modules || [], 'Тема'), ].join(''); const questions = (data.questions || []).map((q, i) => { const answered = Number(q.answered || 0); const denom = answered || totalAttempts; const opts = (q.options || []).map(o => { const share = denom ? (o.count / denom) * 100 : 0; return `
${esc(o.text)}${o.is_correct ? ' ✓' : ''}${o.count} · ${share.toFixed(0)}%
`; }).join(''); const texts = (q.texts || []).length ? `
Текстовые ответы (${q.texts.length}): ${q.texts.slice(0, 20).map(x => `«${esc(x)}»`).join(', ')}${q.texts.length > 20 ? ' …' : ''}
` : ''; const meta = [`Ответов: ${answered}`]; if (q.correct != null) meta.push(`Верно: ${q.correct}`); return `
${i + 1}${esc(q.text)} ${meta.join(' · ')}
${opts}${texts}
`; }).join(''); body.innerHTML = head + filtersHtml + blocks + (questions || '
Вопросов нет
'); renderIcons(); } catch (e) { body.innerHTML = `
${esc(e.message)}
`; } } 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() { const until = retryUntil(); if (until) { showToast(retryLeftText(until), true); return; } 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.systemIds = new Map(); state.sugTimers = 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 (q.required === false) continue; const answered = isFree(q.kind) ? !!String(state.texts.get(q.id) || '').trim() : !!(state.selection.get(q.id) || new Set()).size; if (!answered) { showToast(`Вопрос ${i + 1}: ответ обязателен`, true); const qEl = document.querySelectorAll('#qzQuestions .qz-q')[i]; if (qEl) qEl.scrollIntoView({ behavior: 'smooth', block: 'center' }); return; } } 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 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) || '') : '', answer_id: isSystemKind(q.kind) ? (state.systemIds.get(q.id) || null) : null, })); try { const res = await fetch(API + '/api/quizzes/' + quizId + '/attempts/' + state.attempt.id, { method: 'PUT', headers: hdrJson(), body: JSON.stringify({ answers, time_up: auto === true }), }); 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'; markRetry(); renderTab(); await loadQuiz(true); showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены'); } catch (e) { showToast(e.message, true); if (btn) btn.disabled = false; } } async function restart() { const until = retryUntil(); if (until) { showToast(retryLeftText(until), true); return; } 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(); state.systemIds = new Map(); state.sugTimers = 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) { const qid = Number(el.dataset.qtext); state.texts.set(qid, el.value); updateProgress(); if (el.dataset.qsys) { state.systemIds.delete(qid); const kind = el.dataset.qsys; clearTimeout(state.sugTimers.get(qid)); state.sugTimers.set(qid, setTimeout(() => systemLookup(qid, kind, el.value), 250)); } } }); document.addEventListener('click', e => { const sug = e.target.closest('[data-sug-id]'); if (sug) { e.preventDefault(); const qid = Number(sug.dataset.sugQ); const name = sug.dataset.sugName || ''; state.systemIds.set(qid, Number(sug.dataset.sugId)); state.texts.set(qid, name); const input = document.querySelector('[data-qsys][data-qtext="' + qid + '"]'); if (input) input.value = name; const box = document.querySelector('[data-sug="' + qid + '"]'); if (box) { box.hidden = true; box.innerHTML = ''; } updateProgress(); return; } if (!e.target.closest('.qz-suggest-wrap')) { document.querySelectorAll('.qz-suggest').forEach(box => { box.hidden = true; }); } 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 statsReset = e.target.closest('[data-act="stats-reset"]'); if (statsReset) { e.preventDefault(); statsResetFilters(); return; } const tab = e.target.closest('.qz-tab'); if (tab) { state.tab = tab.dataset.tab; state.attemptDetail = null; renderTab(); } }); document.addEventListener('change', e => { const el = e.target.closest('[data-stat-filter]'); if (!el) return; state.statsFilters[el.dataset.statFilter] = el.value || ''; renderStats(); }); 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.stats_available = data.stats_available === true; 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) { const pinned = state.questions.filter(q => q.no_shuffle); const rest = state.questions.filter(q => !q.no_shuffle); state.questions = pinned.concat(shuffle(rest)); } 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(); state.systemIds = new Map(); state.sugTimers = new Map(); } else { state.attempt = prevAttempt; state.result = prevResult; } if (!state.quiz.stats_available && state.tab === 'stats') state.tab = 'take'; } async function init() { if (!Number.isInteger(quizId) || quizId < 1) { document.getElementById('qzHead').innerHTML = '
Неверный адрес теста
'; return; } if (!(await checkAuth())) return; buildSidebar(document.body.dataset.page); bind(); try { await loadQuiz(false); renderHead(); renderTab(); } catch (e) { document.getElementById('qzHead').innerHTML = `
${esc(e.message)}
`; } } init(); })();