Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0

- ИИ-генерация черновиков тестов (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 под новый функционал тестов/опросов
This commit is contained in:
dev
2026-12-02 14:27:57 +03:00
parent 664f76d820
commit ef4d7cc472
22 changed files with 2884 additions and 130 deletions
+302
View File
@@ -0,0 +1,302 @@
(function () {
const state = { items: [], draft: null, imageTarget: -1 };
function el(id) {
return document.getElementById(id);
}
function a(s) {
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
}
function openModal(id) {
const node = el(id);
if (node) node.classList.add('open');
}
function closeModal(id) {
const node = el(id);
if (node) node.classList.remove('open');
}
function showList() {
el('qsEditorView').hidden = true;
el('qsListView').hidden = false;
}
function showEditor() {
el('qsListView').hidden = true;
el('qsEditorView').hidden = false;
}
async function fetchScales() {
const res = await fetch(API + '/api/grade-scales', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить критерии');
state.items = Array.isArray(data.items) ? data.items : [];
}
function renderList() {
const list = el('qsList');
if (!state.items.length) {
list.innerHTML = '<div class="qs-empty">Критериев пока нет. Создайте первый — например «Шкала на 15 баллов».</div>';
return;
}
list.innerHTML = state.items.map(s => {
const ranges = (s.ranges || []).map(r =>
`<span class="qs-range-chip">${esc(String(r.min_score))}–${esc(String(r.max_score))}: ${esc(r.label || '')}</span>`
).join('');
return `<div class="qs-item">
<div class="qs-item-head">
<div class="qs-item-main">
<div class="qs-item-name">${esc(s.name || '')}</div>
${s.description ? `<div class="qs-item-desc">${esc(s.description)}</div>` : ''}
</div>
<div class="qs-item-acts">
<button type="button" class="btn-link" data-qs-edit="${s.id}">Изменить</button>
<button type="button" class="btn-link danger" data-qs-del="${s.id}">Удалить</button>
</div>
</div>
<div class="qs-item-ranges">${ranges || '<span class="qs-range-chip">нет диапазонов</span>'}</div>
</div>`;
}).join('');
}
function blankDraft() {
return {
id: null,
name: '',
description: '',
sort_order: 0,
ranges: [{ min_score: 0, max_score: '', label: '', image_path: null }],
};
}
function renderRanges() {
const d = state.draft;
el('qsRanges').innerHTML = d.ranges.map((r, i) => `<div class="qs-range" data-ri="${i}">
<input type="number" min="0" step="0.01" class="settings-input qs-min" data-field="min_score" value="${a(r.min_score)}" placeholder="Мин. балл">
<input type="number" min="0" step="0.01" class="settings-input qs-max" data-field="max_score" value="${a(r.max_score)}" placeholder="Макс. балл">
<input class="settings-input qs-label" data-field="label" maxlength="200" value="${a(r.label)}" placeholder="Результат, напр. Отлично">
<div class="qs-range-img">
${r.image_path ? `<img src="${a(thumbSrc(r.image_path))}" alt="">` : '<span class="qs-noimg">нет</span>'}
<button type="button" class="btn-link" data-qs-img="${i}">${r.image_path ? 'Заменить' : 'Картинка'}</button>
${r.image_path ? `<button type="button" class="btn-link danger" data-qs-imgdel="${i}">Убрать</button>` : ''}
</div>
<button type="button" class="btn-link danger" data-qs-rmrange="${i}" title="Удалить диапазон">✕</button>
</div>`).join('');
renderIcons();
}
function renderEditor() {
const d = state.draft;
el('qsName').value = d.name;
el('qsDesc').value = d.description;
el('qsSort').value = d.sort_order;
el('qsEditorTitle').textContent = d.id ? 'Изменить критерий' : 'Новый критерий оценки';
renderRanges();
}
function startCreate() {
state.draft = blankDraft();
renderEditor();
showEditor();
}
function startEdit(id) {
const s = state.items.find(x => Number(x.id) === Number(id));
if (!s) return;
state.draft = {
id: s.id,
name: s.name || '',
description: s.description || '',
sort_order: Number(s.sort_order) || 0,
ranges: (s.ranges || []).map(r => ({
min_score: Number(r.min_score),
max_score: Number(r.max_score),
label: r.label || '',
image_path: r.image_path || null,
})),
};
if (!state.draft.ranges.length) state.draft.ranges.push({ min_score: 0, max_score: '', label: '', image_path: null });
renderEditor();
showEditor();
}
async function save() {
const d = state.draft;
if (!d) return;
const name = el('qsName').value.trim();
if (!name) return showToast('Укажите название критерия', true);
if (!d.ranges.length) return showToast('Добавьте хотя бы один диапазон', true);
const ranges = [];
for (const r of d.ranges) {
const min = Number(r.min_score);
const max = Number(r.max_score);
const label = String(r.label || '').trim();
if (!label) return showToast('У каждого диапазона должен быть результат', true);
if (r.max_score === '' || !Number.isFinite(min) || !Number.isFinite(max)) return showToast('Укажите минимальный и максимальный балл', true);
if (max < min) return showToast('Максимальный балл меньше минимального', true);
ranges.push({ min_score: min, max_score: max, label, image_path: r.image_path || null });
}
const payload = {
name,
description: el('qsDesc').value.trim(),
sort_order: Number(el('qsSort').value) || 0,
ranges,
};
const btn = el('qsSaveBtn');
btn.disabled = true;
try {
const res = await fetch(API + '/api/grade-scales' + (d.id ? '/' + d.id : ''), {
method: d.id ? 'PUT' : 'POST',
headers: hdrJson(),
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось сохранить критерий');
await fetchScales();
renderList();
showList();
showToast('Критерий сохранён');
} catch (e) {
showToast(e.message, true);
} finally {
btn.disabled = false;
}
}
async function remove(id) {
const item = state.items.find(x => Number(x.id) === Number(id));
if (!item) return;
if (!confirm(`Удалить критерий «${item.name}»? Тесты, где он выбран, останутся без градации.`)) return;
try {
const res = await fetch(API + '/api/grade-scales/' + id, { method: 'DELETE', headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось удалить критерий');
await fetchScales();
renderList();
showToast('Критерий удалён');
} catch (e) {
showToast(e.message, true);
}
}
async function openImagePicker(index) {
state.imageTarget = Number(index);
openModal('qsImageModal');
el('qsImgGrid').innerHTML = '<div class="qs-empty">Загрузка…</div>';
try {
const res = await fetch(API + '/api/grade-scales/images', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить картинки');
const items = Array.isArray(data.items) ? data.items : [];
el('qsImgGrid').innerHTML = items.length
? items.map(p => `<button type="button" class="qs-img-cell" data-qs-pickimg="${a(p)}"><img src="${a(thumbSrc(p))}" alt=""></button>`).join('')
: '<div class="qs-empty">Картинок пока нет — загрузите первую.</div>';
} catch (e) {
el('qsImgGrid').innerHTML = `<div class="qs-empty">${esc(e.message)}</div>`;
}
}
async function loadScales() {
el('qsList').innerHTML = '<div class="qs-empty">Загрузка…</div>';
try {
await fetchScales();
renderList();
} catch (e) {
el('qsList').innerHTML = `<div class="qs-empty">${esc(e.message)}</div>`;
}
}
function bind() {
const btn = el('quizScalesBtn');
if (!btn) return;
btn.addEventListener('click', () => {
showList();
openModal('quizScalesModal');
loadScales();
});
el('qsCloseBtn').addEventListener('click', () => closeModal('quizScalesModal'));
el('qsNewBtn').addEventListener('click', startCreate);
el('qsCancelBtn').addEventListener('click', showList);
el('qsSaveBtn').addEventListener('click', save);
el('qsAddRange').addEventListener('click', () => {
state.draft.ranges.push({ min_score: 0, max_score: '', label: '', image_path: null });
renderRanges();
});
el('qsList').addEventListener('click', e => {
const edit = e.target.closest('[data-qs-edit]');
if (edit) { startEdit(edit.dataset.qsEdit); return; }
const del = e.target.closest('[data-qs-del]');
if (del) { remove(del.dataset.qsDel); return; }
});
el('qsRanges').addEventListener('input', e => {
const input = e.target.closest('[data-field]');
if (!input) return;
const row = input.closest('[data-ri]');
if (!row) return;
const i = Number(row.dataset.ri);
if (!state.draft || !state.draft.ranges[i]) return;
state.draft.ranges[i][input.dataset.field] = input.value;
});
el('qsRanges').addEventListener('click', e => {
const img = e.target.closest('[data-qs-img]');
if (img) { openImagePicker(img.dataset.qsImg); return; }
const delImg = e.target.closest('[data-qs-imgdel]');
if (delImg) {
state.draft.ranges[Number(delImg.dataset.qsImgdel)].image_path = null;
renderRanges();
return;
}
const rm = e.target.closest('[data-qs-rmrange]');
if (rm) {
state.draft.ranges.splice(Number(rm.dataset.qsRmrange), 1);
renderRanges();
}
});
el('qsImgGrid').addEventListener('click', e => {
const cell = e.target.closest('[data-qs-pickimg]');
if (!cell) return;
const target = state.draft && state.draft.ranges[state.imageTarget];
if (target) target.image_path = cell.dataset.qsPickimg;
closeModal('qsImageModal');
renderRanges();
});
el('qsImgCancel').addEventListener('click', () => closeModal('qsImageModal'));
el('qsImgFile').addEventListener('change', async e => {
const file = e.target.files && e.target.files[0];
e.target.value = '';
if (!file) return;
const fd = new FormData();
fd.append('photo', file);
try {
const res = await fetch(API + '/api/grade-scales/upload', { method: 'POST', headers: hdr(), body: fd });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить картинку');
const target = state.draft && state.draft.ranges[state.imageTarget];
if (target) target.image_path = data.path;
closeModal('qsImageModal');
renderRanges();
} catch (err) {
showToast(err.message, true);
}
});
el('quizScalesModal').addEventListener('click', e => {
if (e.target.id === 'quizScalesModal') closeModal('quizScalesModal');
});
el('qsImageModal').addEventListener('click', e => {
if (e.target.id === 'qsImageModal') closeModal('qsImageModal');
});
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
if (el('qsImageModal').classList.contains('open')) {
closeModal('qsImageModal');
return;
}
if (el('quizScalesModal').classList.contains('open')) closeModal('quizScalesModal');
});
}
bind();
})();
+61 -9
View File
@@ -1,6 +1,6 @@
(function () {
const quizId = parseInt(new URLSearchParams(location.search).get('id'), 10);
const state = { quiz: null, assets: [], questions: [] };
const state = { quiz: null, assets: [], questions: [], gradeScales: [] };
let dirty = false;
let saving = false;
let dragState = null;
@@ -68,6 +68,8 @@
shuffle_questions: quiz.shuffle_questions === true,
shuffle_options: quiz.shuffle_options === true,
show_results: quiz.show_results !== false,
show_answers: quiz.show_answers !== false,
grade_scale_id: quiz.grade_scale_id == null ? '' : quiz.grade_scale_id,
allow_anonymous: quiz.allow_anonymous === true,
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
time_limit_min: quiz.time_limit_min || 0,
@@ -109,6 +111,8 @@
shuffle_questions: q.shuffle_questions,
shuffle_options: q.shuffle_options,
show_results: q.show_results,
show_answers: q.show_answers,
grade_scale_id: q.grade_scale_id === '' ? null : q.grade_scale_id,
allow_anonymous: q.allow_anonymous,
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
@@ -301,18 +305,23 @@
function renderAnon() {
const wrap = document.getElementById('qeAnonWrap');
if (!wrap) return;
const isSurvey = state.quiz.kind === 'survey';
wrap.hidden = !isSurvey;
if (!isSurvey) return;
wrap.hidden = false;
const isTest = state.quiz.kind === 'test';
document.getElementById('qeAnonymous').checked = state.quiz.allow_anonymous;
const link = document.getElementById('qeAnonLink');
const hint = document.getElementById('qeAnonPublishHint');
const desc = document.getElementById('qeAnonDesc');
if (desc) {
desc.textContent = isTest
? 'По ссылке можно пройти тест без входа в систему. Перед началом ученик может указать имя; если оставить пустым, результат будет анонимным.'
: 'По ссылке можно пройти опрос без входа в систему. Ответы сохраняются без имени.';
}
const ready = state.quiz.allow_anonymous && state.quiz.is_published;
const visible = ready && !dirty;
link.hidden = !visible;
let text = '';
if (state.quiz.allow_anonymous && !state.quiz.is_published) text = 'Опубликуйте опрос, чтобы ссылка заработала.';
else if (ready && dirty) text = 'Сохраните опрос, чтобы ссылка заработала.';
if (state.quiz.allow_anonymous && !state.quiz.is_published) text = 'Опубликуйте, чтобы ссылка заработала.';
else if (ready && dirty) text = 'Сохраните изменения, чтобы ссылка заработала.';
hint.hidden = !text;
hint.textContent = text;
if (visible) {
@@ -322,6 +331,33 @@
}
}
function renderGradeSelect() {
const sel = document.getElementById('qeGradeScale');
if (!sel) return;
const current = state.quiz.grade_scale_id === '' || state.quiz.grade_scale_id == null
? ''
: String(state.quiz.grade_scale_id);
let known = current === '';
const opts = ['<option value="">Без градации</option>'];
for (const s of state.gradeScales) {
if (String(s.id) === current) known = true;
opts.push(`<option value="${s.id}">${at(s.name)}</option>`);
}
if (!known) opts.push(`<option value="${at(current)}">Критерий не найден</option>`);
sel.innerHTML = opts.join('');
sel.value = current;
}
async function loadGradeScales() {
try {
const res = await fetch(API + '/api/grade-scales', { headers: hdr() });
const data = await res.json().catch(() => ({}));
state.gradeScales = res.ok && Array.isArray(data.items) ? data.items : [];
} catch (e) {
state.gradeScales = [];
}
}
function renderSide() {
const q = state.quiz;
document.getElementById('qeName').value = q.title;
@@ -333,15 +369,26 @@
document.getElementById('qeShuffleQ').checked = q.shuffle_questions;
document.getElementById('qeShuffleO').checked = q.shuffle_options;
document.getElementById('qeShowResults').checked = q.show_results;
document.getElementById('qeShowAnswers').checked = q.show_answers;
document.getElementById('qeShowAnswersWrap').hidden = q.kind !== 'test';
document.getElementById('qeGradeWrap').hidden = q.kind !== 'test';
renderGradeSelect();
document.querySelectorAll('#qeKindSeg .qe-seg-btn').forEach(b => {
b.classList.toggle('on', b.dataset.kind === q.kind);
});
document.getElementById('qePassWrap').hidden = q.kind !== 'test';
document.getElementById('qeBarTitle').textContent = q.title || 'Без названия';
document.getElementById('qePreviewBtn').href = 'quiz.html?id=' + q.id;
const previewBtn = document.getElementById('qePreviewBtn');
if (previewBtn) previewBtn.href = 'quiz.html?id=' + q.id;
renderCover();
renderQuizAssets();
renderAnon();
if (location.hash === '#public') {
const wrap = document.getElementById('qeAnonWrap');
if (wrap) wrap.scrollIntoView({ block: 'center', behavior: 'smooth' });
const url = document.getElementById('qeAnonUrl');
if (url && !document.getElementById('qeAnonLink').hidden) url.focus();
}
}
function renderAll() {
@@ -740,13 +787,14 @@
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
markDirty();
});
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeAnonymous'].forEach(id => {
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeShowAnswers', 'qeAnonymous'].forEach(id => {
document.getElementById(id).addEventListener('change', e => {
const map = {
qePublished: 'is_published',
qeShuffleQ: 'shuffle_questions',
qeShuffleO: 'shuffle_options',
qeShowResults: 'show_results',
qeShowAnswers: 'show_answers',
qeAnonymous: 'allow_anonymous',
};
state.quiz[map[id]] = e.target.checked;
@@ -754,12 +802,15 @@
if (id === 'qePublished' || id === 'qeAnonymous') renderAnon();
});
});
document.getElementById('qeGradeScale').addEventListener('change', e => {
state.quiz.grade_scale_id = e.target.value === '' ? '' : Number(e.target.value);
markDirty();
});
document.getElementById('qeKindSeg').addEventListener('click', e => {
const btn = e.target.closest('[data-kind]');
if (!btn) return;
if (state.quiz.kind === btn.dataset.kind) return;
state.quiz.kind = btn.dataset.kind;
if (state.quiz.kind !== 'survey') state.quiz.allow_anonymous = false;
markDirty();
renderSide();
renderQuestions();
@@ -832,6 +883,7 @@
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
bind();
await loadGradeScales();
await load();
}
+59 -16
View File
@@ -122,15 +122,16 @@
function introHtml() {
const q = state.quiz;
const isTest = q.kind === 'test';
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>
<div class="qp-title">${esc2(q.title || (isTest ? 'Тест' : 'Опрос'))}</div>
<div class="qp-sub"><span>Вопросов: ${state.questions.length}</span>${q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : ''}${isTest ? `<span>${q.show_results === false ? 'Результат виден автору' : 'Результат после отправки'}</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>
<span class="qp-hint">${isTest ? 'Вход в систему не нужен.' : 'Ответы сохраняются без имени и входа в систему.'}</span>
</div>
</div>`;
}
@@ -206,10 +207,18 @@
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 res = await fetch(API + '/api/public-quizzes/' + quizId + '/attempts', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
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 };
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;
@@ -223,6 +232,44 @@
}
}
function renderDone(data) {
const isTest = state.quiz && state.quiz.kind === 'test';
const result = data && data.result ? data.result : null;
const score = result ? `${result.score} / ${result.max_score} (${result.percent}%)` : '';
const passText = result && result.passed === true ? 'Тест сдан' : (result && result.passed === false ? 'Тест не сдан' : '');
const grade = result && result.grade ? result.grade : null;
const gradeHtml = grade
? `<div class="qp-grade">${grade.image_path ? `<img src="${at(thumb(grade.image_path))}" data-img="${at(API + grade.image_path)}" alt="">` : ''}<div class="qp-grade-label">${esc2(grade.label || '')}</div></div>`
: '';
const hiddenAnswers = !!(result && result.answers_hidden);
const details = result && Array.isArray(result.questions) && result.questions.length
? `<div class="qp-result">${result.questions.map(q => {
const ok = q.is_correct === true;
const bad = q.is_correct === false;
return `<div class="qp-result-item ${ok ? 'ok' : (bad ? 'bad' : '')}">
<div class="qp-result-q">${esc2(q.text || '')}</div>
<div class="qp-result-a">${ok ? 'Верно' : (bad ? 'Неверно' : 'Ответ сохранён')}${q.max_score ? ` · ${q.score} / ${q.max_score}` : ''}</div>
</div>`;
}).join('')}</div>`
: '';
let hint = 'Ответы сохранены.';
if (isTest) {
if (!result) hint = 'Ответы сохранены. Подробный результат автор скрыл.';
else if (hiddenAnswers) hint = 'Ответы сохранены. Автор скрыл разбор ответов.';
}
document.getElementById('qpBody').innerHTML = `<div class="qp-card qp-done">
<div class="qp-done-ic">${isTest && result && result.passed === false ? '•' : '✓'}</div>
<div class="qp-title">${isTest ? 'Тест завершён' : 'Спасибо!'}</div>
${isTest && score ? `<p style="margin-top:8px;font-size:1rem"><b>${esc2(score)}</b>${passText ? ` · ${esc2(passText)}` : ''}</p>` : ''}
${gradeHtml}
<p class="qp-hint" style="margin-top:8px">${esc2(hint)}</p>
${details}
<div class="qp-actions" style="justify-content:center">
<button type="button" class="btn-primary ghost" data-act="again">Пройти ещё раз</button>
</div>
</div>`;
}
async function submit(auto) {
if (!state.attempt) return;
if (!auto) {
@@ -260,14 +307,7 @@
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>`;
renderDone(data);
} catch (e) {
toast(e.message, true);
if (btn) btn.disabled = false;
@@ -332,18 +372,21 @@
async function init() {
if (!Number.isInteger(quizId) || quizId < 1) {
document.getElementById('qpBody').innerHTML = '<div class="qp-error">Неверная ссылка на опрос</div>';
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 || 'Опрос не найден');
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 || 'Опрос') + ' — опрос';
const kindLabel = state.quiz.kind === 'survey' ? 'Опрос' : 'Тест';
document.title = (state.quiz.title || kindLabel) + ' — ' + kindLabel.toLowerCase();
const brand = document.getElementById('qpBrand');
if (brand) brand.textContent = kindLabel;
render();
} catch (e) {
document.getElementById('qpBody').innerHTML = `<div class="qp-error">${esc2(e.message)}</div>`;
+19 -4
View File
@@ -86,7 +86,7 @@
`<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">${renderMd(q.description)}</div>` : '',
q.description ? `<div class="qz-desc qz-q">${renderMd(q.description)}</div>` : '',
`</div>`,
`</div>`,
];
@@ -240,21 +240,35 @@
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>`
<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)) {
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>'
@@ -291,7 +305,8 @@
<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>`
<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) => {
+544 -33
View File
@@ -1,8 +1,19 @@
(function () {
let items = [];
let loading = false;
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, '&quot;');
@@ -12,11 +23,19 @@
return {
search: document.getElementById('quizSearch').value.trim(),
kind: document.getElementById('quizKindFilter').value,
mine: document.getElementById('quizMineOnly').checked ? '1' : '',
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' ? 'Опрос' : 'Тест';
}
@@ -27,7 +46,7 @@
: '<span class="quiz-cover-ic"><i data-lucide="clipboard-list"></i></span>';
const flags = [];
flags.push(`<span class="quiz-flag${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`);
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Анонимный</span>');
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Ссылка</span>');
if (q.deleted_at) flags.push('<span class="quiz-flag del">Удалён</span>');
const attempts = q.kind === 'test'
? `Попыток: <b>${q.attempt_count}</b>${q.my_attempt_count ? ` · моих: <b>${q.my_attempt_count}</b>` : ''}`
@@ -41,6 +60,7 @@
} else {
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}">Пройти</a>`);
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}">Изменить</a>`);
if (q.can_edit && q.allow_anonymous && q.is_published) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.id}">Ссылку</button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}">Статистика</button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}">Удалить</button>`);
}
@@ -66,58 +86,95 @@
function render() {
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
if (loading) {
if (!loaded) {
list.innerHTML = '';
empty.hidden = true;
return;
}
if (!items.length) {
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-empty';
empty.textContent = deletedMode ? 'В корзине нет тестов и опросов' : 'Тестов и опросов пока нет';
const shown = visibleItems();
if (!shown.length) {
renderPlaceholder(deletedMode
? 'В корзине нет тестов и опросов'
: (mineOnly() ? 'У вас пока нет своих тестов и опросов' : 'Тестов и опросов пока нет'));
return;
}
empty.hidden = true;
list.innerHTML = items.map(cardHtml).join('');
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)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
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;
loading = true;
render();
const f = filters();
deletedMode = !!f.deleted;
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.mine) params.set('mine', f.mine);
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() });
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 || 'Не удалось загрузить тесты');
items = Array.isArray(data.items) ? data.items : [];
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 = [];
loading = false;
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-error';
empty.innerHTML = `${esc(e.message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
document.getElementById('quizRetry').addEventListener('click', () => {
empty.className = 'quiz-empty';
load();
});
renderLoadError(failure.message);
return;
}
if (seq !== loadSeq) return;
loading = false;
items = nextItems;
render();
}
@@ -136,6 +193,381 @@
}
}
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(`вопросов: <b>${job.questions != null ? job.questions : job.count}</b>`);
parts.push(`сложность: ${aiDifficultyLabel(job.difficulty)}`);
if (job.attempts > 1) parts.push(`попыток: <b>${job.attempts}</b>`);
if (job.model) parts.push(`модель: <b>${esc(job.model)}</b>`);
else if (job.profile && job.profile !== 'native') parts.push(`профиль: <b>${esc(job.profile)}</b>`);
else parts.push('модель: <b>нативная</b>');
if (currentUser && currentUser.role === 'admin') {
const who = job.user_name || job.user_username;
if (who) parts.push(`автор: <b>${esc(who)}</b>`);
}
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
? `<a class="btn-link quiz-ai-job-link" href="quiz-edit.html?id=${job.quiz_id}">Открыть тест #${job.quiz_id}</a>`
: '';
return `<div class="quiz-ai-job">
<div class="quiz-ai-job-head">
<span class="quiz-ai-job-status ${attr(job.status)}" data-job-status="${job.id}">${aiStatusLabel(job.status)}</span>
<span class="quiz-ai-job-meta">${created}${finished}</span>
</div>
<div class="quiz-ai-job-prompt" title="${attr(prompt.slice(0, 300))}">${prompt ? esc(prompt) : '<span style="color:var(--muted)">Без описания</span>'}</div>
<div class="quiz-ai-job-meta">${aiHistoryMeta(job)}</div>
${job.error ? `<div class="quiz-ai-job-error">${esc(job.error)}</div>` : ''}
${link}
</div>`;
}
function renderAiHistory() {
const list = document.getElementById('quizAiHistoryList');
if (!list) return;
if (aiHistory.loading && !aiHistory.items.length) {
list.innerHTML = '<div class="quiz-ai-history-empty">Загрузка…</div>';
} else if (aiHistory.error && !aiHistory.items.length) {
list.innerHTML = `<div class="quiz-ai-history-empty">${esc(aiHistory.error)}</div>`;
} else if (!aiHistory.items.length) {
list.innerHTML = '<div class="quiz-ai-history-empty">Заданий пока нет. Сгенерируйте тест — оно появится здесь.</div>';
} 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 = '<option value="native">Нативная</option>';
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 {
@@ -177,12 +609,43 @@
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', load);
document.getElementById('quizMineOnly').addEventListener('change', () => {
if (!loaded) {
load();
return;
}
render();
});
document.getElementById('quizDeletedOnly').addEventListener('change', load);
document.addEventListener('click', e => {
@@ -192,6 +655,17 @@
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;
@@ -201,21 +675,58 @@
}
function connectLive() {
let t = null;
if (liveSource) return;
const es = new EventSource(API + '/api/events?token=' + encodeURIComponent(token || ''));
liveSource = es;
es.addEventListener('quizzes_changed', () => {
clearTimeout(t);
t = setTimeout(load, 400);
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();
+4 -2
View File
@@ -1,6 +1,6 @@
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'calWeekStart', 'calDayStart', 'calDayEnd', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey', 'facesBrokenScanEnabled', 'facesBrokenScanInterval'];
const DIRTY_FIELDS = ['systemName', 'timezone', 'timeFormat', 'calWeekStart', 'calDayStart', 'calDayEnd', 'spamInterval', 'footerLeft', 'footerRight', 'aiPrompt', 'aiAutoCheck', 'lessonAiPrompt', 'lessonAiEnabled', 'notesAiEnabled', 'quizAiEnabled', 'shareShowMessage', 'shareShowDate', 'shareShowNames', 'shareShowPhotos', 'cookieNoticeText', 'photoResolution', 'photoQuality', 'photoEngine', 'camEnabled', 'photoAiFaceMode', 'photoAiFaceModel', 'photoAiDevicePref', 'trashPurgeDays', 'notifyEnabled', 'notifyRetentionDays', 'imgbbUrl', 'imgbbKey', 'facesBrokenScanEnabled', 'facesBrokenScanInterval'];
const NOTIFY_IDS = [];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-calendar', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans', 'sec-face-broken'];
const SECTION_IDS = ['sec-system', 'sec-stack', 'sec-brand', 'sec-datetime', 'sec-calendar', 'sec-antispam', 'sec-share', 'sec-ai', 'sec-lesson-ai', 'sec-notes-ai', 'sec-quiz-ai', 'sec-achievements', 'sec-tls', 'sec-backup', 'sec-trash', 'sec-form', 'sec-notify', 'sec-photo', 'sec-photo-ai', 'sec-external-services', 'sec-bans', 'sec-face-broken'];
const SPAM_MAX = 10080;
const BAN_REASONS = {
'honeypot': 'Антиспам-поле',
@@ -312,6 +312,7 @@ async function loadSettings() {
document.getElementById('lessonAiEnabled').checked = s.lesson_ai_enabled !== 'false';
document.getElementById('lessonAiPrompt').value = s.lesson_ai_prompt || '';
document.getElementById('notesAiEnabled').checked = s.notes_ai_enabled !== 'false';
document.getElementById('quizAiEnabled').checked = s.quiz_ai_enabled !== 'false';
const fe = document.getElementById('faceIdEnabled');
const fsu = document.getElementById('faceScanOnUpload');
const fth = document.getElementById('faceIdThreshold');
@@ -956,6 +957,7 @@ async function saveSettings() {
lesson_ai_enabled: document.getElementById('lessonAiEnabled').checked ? 'true' : 'false',
lesson_ai_prompt: document.getElementById('lessonAiPrompt').value.trim(),
notes_ai_enabled: document.getElementById('notesAiEnabled').checked ? 'true' : 'false',
quiz_ai_enabled: document.getElementById('quizAiEnabled').checked ? 'true' : 'false',
face_id_enabled: (document.getElementById('faceIdEnabled') || {}).checked ? 'true' : 'false',
face_scan_on_upload: (document.getElementById('faceScanOnUpload') || {}).checked ? 'true' : 'false',
face_id_threshold: String((document.getElementById('faceIdThreshold') || {}).value || '0.6').trim(),