(function () { let items = []; let loaded = false; let deletedMode = false; let loadSeq = 0; let loadAbort = null; let aiEnabled = false; let aiBusy = false; let aiModelsCache = null; let aiJob = null; let aiPoll = null; const AI_HISTORY_LIMIT = 20; const LOAD_TIMEOUT_MS = 15000; const aiHistory = { offset: 0, total: 0, items: [], error: '', loading: false, poll: null }; let liveSource = null; let liveDebounce = null; function attr(s) { return esc(String(s == null ? '' : s)).replace(/"/g, '"'); } function mdPlain(text) { const raw = String(text || '').trim(); if (!raw) return ''; if (typeof WhatIDoMD === 'undefined' || !WhatIDoMD || typeof WhatIDoMD.render !== 'function') return raw; const box = document.createElement('div'); box.innerHTML = WhatIDoMD.render(raw); return (box.textContent || '').replace(/\s+/g, ' ').trim(); } function filters() { return { search: document.getElementById('quizSearch').value.trim(), kind: document.getElementById('quizKindFilter').value, deleted: document.getElementById('quizDeletedOnly').checked ? '1' : '', }; } function mineOnly() { return !!document.getElementById('quizMineOnly').checked; } function visibleItems() { if (!mineOnly() || !currentUser) return items; return items.filter(q => Number(q.author_id) === Number(currentUser.id)); } function kindLabel(kind) { return kind === 'survey' ? 'Опрос' : 'Тест'; } function cardHtml(q) { const cover = q.cover_path ? `` : ''; const flags = []; flags.push(`${q.is_published ? 'Опубликован' : 'Черновик'}`); if (q.allow_anonymous) flags.push('Ссылка'); if (q.deleted_at) flags.push('Удалён'); const attempts = q.kind === 'test' ? `Попыток: ${q.attempt_count}${q.my_attempt_count ? ` · моих: ${q.my_attempt_count}` : ''}` : `Ответов: ${q.attempt_count}`; const actions = []; if (q.deleted_at) { if (q.can_edit) { actions.push(``); actions.push(``); } } else { if (q.can_take) actions.push(`Пройти`); if (q.can_edit) actions.push(`Изменить`); if (q.can_edit && q.allow_anonymous && q.is_published) actions.push(``); if (q.can_edit) actions.push(``); if (q.can_edit) actions.push(``); } return `
${cover}${kindLabel(q.kind)}
${esc(q.title || 'Без названия')}
${q.description ? `
${esc(mdPlain(q.description))}
` : ''}
Вопросов: ${q.question_count} ${attempts}
${esc(q.author_name || 'Автор удалён')} ${fmtDateTime(q.updated_at)}
${flags.join('')}
${actions.join('')}
`; } function render() { const list = document.getElementById('quizList'); const empty = document.getElementById('quizEmpty'); if (!loaded) { list.innerHTML = ''; empty.hidden = true; return; } const shown = visibleItems(); if (!shown.length) { renderPlaceholder(deletedMode ? 'В корзине нет тестов и опросов' : (mineOnly() ? 'У вас пока нет своих тестов и опросов' : 'Тестов и опросов пока нет')); return; } empty.hidden = true; list.innerHTML = shown.map(cardHtml).join(''); renderIcons(); } function renderPlaceholder(text) { const list = document.getElementById('quizList'); const empty = document.getElementById('quizEmpty'); list.innerHTML = ''; empty.hidden = false; empty.className = 'quiz-empty'; empty.textContent = text; } function renderLoadError(message) { const list = document.getElementById('quizList'); const empty = document.getElementById('quizEmpty'); list.innerHTML = ''; empty.hidden = false; empty.className = 'quiz-error'; empty.innerHTML = `${esc(message)}
`; document.getElementById('quizRetry').addEventListener('click', () => load()); } function setBusy(busy) { const bar = document.getElementById('quizBusy'); if (bar) bar.classList.toggle('on', busy); const list = document.getElementById('quizList'); if (list) list.classList.toggle('quiz-busy', busy); } async function load() { const seq = ++loadSeq; const f = filters(); const nextDeleted = !!f.deleted; const params = new URLSearchParams(); if (f.search) params.set('search', f.search); if (f.kind) params.set('kind', f.kind); if (f.deleted) params.set('deleted', f.deleted); if (loadAbort) loadAbort.abort(); const controller = new AbortController(); loadAbort = controller; let expired = false; const timer = setTimeout(() => { expired = true; controller.abort(); }, LOAD_TIMEOUT_MS); setBusy(true); let failure = null; let nextItems = []; try { const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr(), signal: controller.signal }); const data = await res.json().catch(() => ({})); if (seq !== loadSeq) return; if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тесты'); nextItems = Array.isArray(data.items) ? data.items : []; aiEnabled = data.ai_enabled !== false; syncAiButton(); } catch (e) { if (seq !== loadSeq) return; if (e && e.name === 'AbortError' && !expired) return; failure = expired ? new Error('Сервер не ответил вовремя. Закройте лишние вкладки приложения и нажмите «Повторить».') : e; } finally { clearTimeout(timer); if (loadAbort === controller) loadAbort = null; if (seq === loadSeq) setBusy(false); } loaded = true; deletedMode = nextDeleted; if (failure) { items = []; renderLoadError(failure.message); return; } items = nextItems; render(); } async function createQuiz(kind) { try { const res = await fetch(API + '/api/quizzes', { method: 'POST', headers: hdrJson(), body: JSON.stringify({ kind }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось создать'); location.href = 'quiz-edit.html?id=' + data.quiz.id; } catch (e) { showToast(e.message, true); } } function syncAiButton() { const btn = document.getElementById('quizAiBtn'); if (btn) btn.style.display = aiEnabled ? '' : 'none'; } function setAiStatus(text, kind) { const el = document.getElementById('quizAiStatus'); el.textContent = text; el.className = 'quiz-ai-status' + (kind ? ' ' + kind : ''); } function setAiBusy(busy) { aiBusy = !!busy; const runBtn = document.getElementById('quizAiRun'); if (runBtn) runBtn.disabled = aiBusy; } function stopAiPoll() { if (aiPoll) { clearInterval(aiPoll); aiPoll = null; } } function syncAiResult(job) { const box = document.getElementById('quizAiResult'); const text = document.getElementById('quizAiResultText'); const edit = document.getElementById('quizAiOpenEdit'); const pub = document.getElementById('quizAiOpenPublic'); if (!box || !text) return; if (job && job.status === 'done' && job.quiz_id) { const editUrl = 'quiz-edit.html?id=' + job.quiz_id; box.hidden = false; text.textContent = `Готово: создан тест #${job.quiz_id}, вопросов: ${job.questions || 0}.`; if (edit) edit.href = editUrl; if (pub) pub.href = editUrl + '#public'; renderIcons(); } else { box.hidden = true; if (text) text.textContent = ''; if (edit) edit.removeAttribute('href'); if (pub) pub.removeAttribute('href'); } } function applyAiJob(job) { aiJob = job || null; if (!job) { setAiBusy(false); syncAiResult(null); return; } if (job.status === 'pending' || job.status === 'processing') { setAiBusy(true); syncAiResult(null); setAiStatus(job.status === 'pending' ? 'Задание в очереди… страницу можно закрыть, результат появится в списке.' : 'ИИ генерирует вопросы… страницу можно закрыть, результат появится в списке.', 'busy'); return; } setAiBusy(false); stopAiPoll(); if (job.status === 'done') { syncAiResult(job); setAiStatus('Генерация завершена. Тест создан как черновик.'); load(); } else { syncAiResult(null); setAiStatus('Ошибка: ' + (job.error || 'Не удалось сгенерировать тест'), 'error'); } } async function refreshAiJob() { try { const res = await fetch(API + '/api/quizzes/ai-jobs/active', { headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) return; if (data.job) applyAiJob(data.job); else if (aiBusy) applyAiJob(null); } catch (e) {} } function startAiPoll() { stopAiPoll(); aiPoll = setInterval(refreshAiJob, 3000); } function aiStatusLabel(status) { if (status === 'pending') return 'В очереди'; if (status === 'processing') return 'В работе'; if (status === 'done') return 'Готово'; if (status === 'error') return 'Ошибка'; return status || '—'; } function aiDifficultyLabel(value) { if (value === 'easy') return 'лёгкая'; if (value === 'hard') return 'сложная'; return 'средняя'; } function aiHistoryMeta(job) { const parts = []; parts.push(`#${job.id}`); parts.push(kindLabel(job.kind)); parts.push(`вопросов: ${job.questions != null ? job.questions : job.count}`); parts.push(`сложность: ${aiDifficultyLabel(job.difficulty)}`); if (job.attempts > 1) parts.push(`попыток: ${job.attempts}`); if (job.model) parts.push(`модель: ${esc(job.model)}`); else if (job.profile && job.profile !== 'native') parts.push(`профиль: ${esc(job.profile)}`); else parts.push('модель: нативная'); if (currentUser && currentUser.role === 'admin') { const who = job.user_name || job.user_username; if (who) parts.push(`автор: ${esc(who)}`); } return parts.join(' · '); } function aiHistoryRow(job) { const prompt = String(job.prompt || '').trim(); const created = job.created_at ? fmtDateTime(job.created_at) : ''; const finished = job.finished_at ? ' → ' + fmtDateTime(job.finished_at) : ''; const link = job.quiz_id ? `Открыть тест #${job.quiz_id}` : ''; return `
${aiStatusLabel(job.status)} ${created}${finished}
${prompt ? esc(prompt) : 'Без описания'}
${aiHistoryMeta(job)}
${job.error ? `
${esc(job.error)}
` : ''} ${link}
`; } function renderAiHistory() { const list = document.getElementById('quizAiHistoryList'); if (!list) return; if (aiHistory.loading && !aiHistory.items.length) { list.innerHTML = '
Загрузка…
'; } else if (aiHistory.error && !aiHistory.items.length) { list.innerHTML = `
${esc(aiHistory.error)}
`; } else if (!aiHistory.items.length) { list.innerHTML = '
Заданий пока нет. Сгенерируйте тест — оно появится здесь.
'; } else { list.innerHTML = aiHistory.items.map(aiHistoryRow).join(''); } const from = aiHistory.total ? aiHistory.offset + 1 : 0; const to = Math.min(aiHistory.offset + AI_HISTORY_LIMIT, aiHistory.total); document.getElementById('quizAiHistoryPage').textContent = `${from}–${to} из ${aiHistory.total}`; document.getElementById('quizAiHistoryPrev').disabled = aiHistory.loading || aiHistory.offset <= 0; document.getElementById('quizAiHistoryNext').disabled = aiHistory.loading || aiHistory.offset + AI_HISTORY_LIMIT >= aiHistory.total; renderIcons(); } async function fetchAiHistory() { const res = await fetch(API + '/api/quizzes/ai-jobs?limit=' + AI_HISTORY_LIMIT + '&offset=' + aiHistory.offset, { headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось загрузить историю'); return { items: Array.isArray(data.items) ? data.items : [], total: Number(data.total) || 0, }; } async function loadAiHistory() { aiHistory.loading = true; renderAiHistory(); try { const data = await fetchAiHistory(); aiHistory.items = data.items; aiHistory.total = data.total; aiHistory.error = ''; } catch (e) { aiHistory.error = e.message; } finally { aiHistory.loading = false; renderAiHistory(); } } async function refreshAiHistory() { if (!document.getElementById('quizAiHistoryModal').classList.contains('open')) return; if (aiHistory.loading) return; try { const data = await fetchAiHistory(); const sameSet = data.items.length === aiHistory.items.length && data.items.every((job, i) => aiHistory.items[i] && aiHistory.items[i].id === job.id); const totalChanged = data.total !== aiHistory.total; const finalChanged = data.items.some(job => { const prev = aiHistory.items.find(item => item.id === job.id); return prev && prev.status !== job.status && job.status !== 'pending' && job.status !== 'processing'; }); aiHistory.items = data.items; aiHistory.total = data.total; aiHistory.error = ''; if (!sameSet || totalChanged || finalChanged) { renderAiHistory(); return; } data.items.forEach(job => { const badge = document.querySelector('[data-job-status="' + job.id + '"]'); if (!badge) return; badge.textContent = aiStatusLabel(job.status); badge.className = 'quiz-ai-job-status ' + job.status; }); } catch (e) {} } function openQuizAiHistory() { aiHistory.offset = 0; aiHistory.items = []; aiHistory.total = 0; aiHistory.error = ''; document.getElementById('quizAiHistoryModal').classList.add('open'); renderIcons(); loadAiHistory(); if (aiHistory.poll) clearInterval(aiHistory.poll); aiHistory.poll = setInterval(refreshAiHistory, 3000); } function closeQuizAiHistory() { document.getElementById('quizAiHistoryModal').classList.remove('open'); if (aiHistory.poll) { clearInterval(aiHistory.poll); aiHistory.poll = null; } } function aiHistoryPage(delta) { const next = aiHistory.offset + delta * AI_HISTORY_LIMIT; if (next < 0 || next >= aiHistory.total) return; aiHistory.offset = next; document.getElementById('quizAiHistoryList').scrollTop = 0; loadAiHistory(); } function aiNativeOption(label) { const opt = document.createElement('option'); opt.value = 'native'; opt.textContent = label; return opt; } function aiOptgroup(label, list) { const group = document.createElement('optgroup'); group.label = label; list.forEach(m => { const opt = document.createElement('option'); opt.value = m.id; opt.textContent = [m.name, m.model].filter(Boolean).join(' — '); group.appendChild(opt); }); return group; } async function loadAiModels() { const [mineRes, optRes] = await Promise.allSettled([ fetch(API + '/api/user-settings', { headers: hdr() }), fetch(API + '/api/ai/profiles/options', { headers: hdr() }), ]); const result = { native: 'Нативная', active: 'native', profiles: [], personal: [], loaded: 0 }; if (optRes.status === 'fulfilled' && optRes.value.ok) { const d = await optRes.value.json().catch(() => ({})); result.loaded++; if (d.native && d.native.model) result.native = 'Нативная — ' + d.native.model; result.active = d.active || 'native'; if (Array.isArray(d.profiles)) result.profiles = d.profiles; } if (mineRes.status === 'fulfilled' && mineRes.value.ok) { const d = await mineRes.value.json().catch(() => ({})); let arr = []; try { arr = JSON.parse((d.settings && d.settings.feedback_models) || '[]'); } catch (e) { arr = []; } result.loaded++; if (Array.isArray(arr)) result.personal = arr.filter(m => m && m.id); } return result; } function fillAiModels(models) { const sel = document.getElementById('quizAiModel'); const keep = sel.value; sel.innerHTML = ''; sel.appendChild(aiNativeOption(models.native)); if (models.personal.length) sel.appendChild(aiOptgroup('Мои модели', models.personal)); if (models.profiles.length) sel.appendChild(aiOptgroup('Системные', models.profiles)); const wanted = keep || models.active; sel.value = [...sel.options].some(o => o.value === wanted) ? wanted : 'native'; } async function openQuizAi() { if (!aiEnabled) { showToast('ИИ-генерация отключена в настройках', true); return; } document.getElementById('quizAiPrompt').value = ''; document.getElementById('quizAiPromptCount').textContent = '0'; document.getElementById('quizAiCount').value = '10'; document.getElementById('quizAiKind').value = 'test'; document.getElementById('quizAiDifficulty').value = 'medium'; const sel = document.getElementById('quizAiModel'); sel.innerHTML = ''; if (aiModelsCache) fillAiModels(aiModelsCache); syncAiResult(aiJob && aiJob.status === 'done' ? aiJob : null); if (!aiBusy) setAiStatus('Готово к генерации'); document.getElementById('quizAiModal').classList.add('open'); renderIcons(); document.getElementById('quizAiPrompt').focus(); try { const models = await loadAiModels(); aiModelsCache = models; fillAiModels(models); if (!models.loaded && !aiBusy) setAiStatus('Модели не загрузились — доступна нативная', 'error'); else if (!models.personal.length && !models.profiles.length && !aiBusy) { setAiStatus('Доступна только нативная модель: добавьте свою в профиле, вкладка «ИИ и модели»'); } } catch (e) { if (!aiBusy) setAiStatus('Не удалось загрузить список моделей — доступна нативная', 'error'); } refreshAiJob(); } function closeQuizAi() { document.getElementById('quizAiModal').classList.remove('open'); } async function runQuizAi() { if (aiBusy) return; const promptText = document.getElementById('quizAiPrompt').value.trim(); if (!promptText) { showToast('Опишите тему теста'); document.getElementById('quizAiPrompt').focus(); return; } const count = Math.max(1, Math.min(40, parseInt(document.getElementById('quizAiCount').value, 10) || 10)); document.getElementById('quizAiCount').value = String(count); setAiBusy(true); syncAiResult(null); setAiStatus('Отправляем задание в очередь…', 'busy'); try { const res = await fetch(API + '/api/quizzes/ai-generate', { method: 'POST', headers: hdrJson(), body: JSON.stringify({ prompt: promptText, kind: document.getElementById('quizAiKind').value === 'survey' ? 'survey' : 'test', count, difficulty: document.getElementById('quizAiDifficulty').value, profile: document.getElementById('quizAiModel').value || 'native', }), }); const data = await res.json().catch(() => ({})); if (res.status === 409 && data.job) { applyAiJob(data.job); startAiPoll(); showToast('Генерация уже идёт'); return; } if (!res.ok) throw new Error(data.error || 'Не удалось запустить генерацию'); applyAiJob(data.job); startAiPoll(); showToast('Генерация запущена'); } catch (e) { setAiBusy(false); setAiStatus('Ошибка: ' + e.message, 'error'); showToast(e.message, true); } } async function removeQuiz(id) { if (!confirm('Удалить тест? Он попадёт в корзину и будет удалён окончательно по истечении срока.')) return; try { const res = await fetch(API + '/api/quizzes/' + id, { method: 'DELETE', headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось удалить'); showToast('Тест удалён'); await load(); } catch (e) { showToast(e.message, true); } } async function restoreQuiz(id) { try { const res = await fetch(API + '/api/quizzes/' + id + '/restore', { method: 'PUT', headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось восстановить'); showToast('Тест восстановлен'); await load(); } catch (e) { showToast(e.message, true); } } async function purgeQuiz(id) { if (!confirm('Удалить тест навсегда вместе с вопросами и файлами?')) return; try { const res = await fetch(API + '/api/quizzes/' + id + '/permanent', { method: 'DELETE', headers: hdr() }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || 'Не удалось удалить'); showToast('Тест удалён навсегда'); await load(); } catch (e) { showToast(e.message, true); } } function bind() { document.getElementById('quizNewTestBtn').addEventListener('click', () => createQuiz('test')); document.getElementById('quizNewSurveyBtn').addEventListener('click', () => createQuiz('survey')); document.getElementById('quizAiBtn').addEventListener('click', openQuizAi); document.getElementById('quizAiCancel').addEventListener('click', closeQuizAi); document.getElementById('quizAiRun').addEventListener('click', runQuizAi); document.getElementById('quizAiModal').addEventListener('click', e => { if (e.target.id === 'quizAiModal') closeQuizAi(); }); document.getElementById('quizAiPrompt').addEventListener('input', e => { document.getElementById('quizAiPromptCount').textContent = String(e.target.value.length); }); document.getElementById('quizAiHistoryBtn').addEventListener('click', openQuizAiHistory); document.getElementById('quizAiHistoryClose').addEventListener('click', closeQuizAiHistory); document.getElementById('quizAiHistoryPrev').addEventListener('click', () => aiHistoryPage(-1)); document.getElementById('quizAiHistoryNext').addEventListener('click', () => aiHistoryPage(1)); document.getElementById('quizAiHistoryRefresh').addEventListener('click', loadAiHistory); document.getElementById('quizAiHistoryModal').addEventListener('click', e => { if (e.target.id === 'quizAiHistoryModal') closeQuizAiHistory(); }); document.addEventListener('keydown', e => { if (e.key !== 'Escape') return; if (document.getElementById('quizAiHistoryModal').classList.contains('open')) { closeQuizAiHistory(); return; } if (document.getElementById('quizAiModal').classList.contains('open')) closeQuizAi(); }); document.getElementById('quizSearch').addEventListener('input', () => { clearTimeout(bind.t); bind.t = setTimeout(load, 300); }); document.getElementById('quizKindFilter').addEventListener('change', load); document.getElementById('quizMineOnly').addEventListener('change', () => { if (!loaded) { load(); return; } render(); }); document.getElementById('quizDeletedOnly').addEventListener('change', load); document.addEventListener('click', e => { const del = e.target.closest('[data-del]'); if (del) { e.preventDefault(); removeQuiz(del.dataset.del); return; } const restore = e.target.closest('[data-restore]'); if (restore) { e.preventDefault(); restoreQuiz(restore.dataset.restore); return; } const perm = e.target.closest('[data-perm]'); if (perm) { e.preventDefault(); purgeQuiz(perm.dataset.perm); return; } const copyLink = e.target.closest('[data-copy-link]'); if (copyLink) { e.preventDefault(); const url = location.origin + '/quiz-public.html?id=' + copyLink.dataset.copyLink; if (navigator.clipboard && navigator.clipboard.writeText) { navigator.clipboard.writeText(url).then(() => showToast('Ссылка скопирована'), () => showToast('Не удалось скопировать ссылку', true)); } else { showToast(url); } return; } const stats = e.target.closest('[data-stats]'); if (stats) { e.preventDefault(); location.href = 'quiz.html?id=' + stats.dataset.stats + '&tab=stats'; return; } if (e.target.closest('a')) return; const card = e.target.closest('[data-open]'); if (card && card.dataset.open) location.href = 'quiz.html?id=' + card.dataset.open; }); } function connectLive() { if (liveSource) return; const es = new EventSource(API + '/api/events?token=' + encodeURIComponent(token || '')); liveSource = es; es.addEventListener('quizzes_changed', () => { clearTimeout(liveDebounce); liveDebounce = setTimeout(load, 400); }); es.addEventListener('quiz_ai_status', e => { let payload = null; try { payload = JSON.parse(e.data); } catch (err) { return; } const job = payload && payload.job ? payload.job : null; if (!job) return; if (currentUser && Number(job.user_id) !== Number(currentUser.id)) return; applyAiJob(job); if (job.status === 'pending' || job.status === 'processing') startAiPoll(); if (document.getElementById('quizAiHistoryModal').classList.contains('open')) refreshAiHistory(); }); } function disconnectLive() { if (liveDebounce) { clearTimeout(liveDebounce); liveDebounce = null; } if (!liveSource) return; liveSource.close(); liveSource = null; } function bindVisibility() { document.addEventListener('visibilitychange', () => { if (document.hidden) { disconnectLive(); return; } connectLive(); load(); }); } async function init() { if (!(await checkAuth())) return; buildSidebar(document.body.dataset.page); const scalesBtn = document.getElementById('quizScalesBtn'); if (scalesBtn) scalesBtn.hidden = !(currentUser && currentUser.role === 'admin'); bind(); bindVisibility(); renderIcons(); await load(); connectLive(); await refreshAiJob(); if (aiJob && (aiJob.status === 'pending' || aiJob.status === 'processing')) startAiPoll(); } init(); })();