Тесты и опросы: критерии оценки, génération ИИ, улучшения конструктора и прохождения
- lib/quizzes.js: система criterial-оценки (quiz_grade_scales/quiz_grade_ranges), подсчёт баллов, попытки, anon-опросы, системные поля, доступ по коду - lib/quiz-grades.js: CRUD критериев оценки, диапазоны, картинки - lib/quiz-ai.js: генерация черновика теста через ИИ - server.js: роуты тестов, критериев, медиа-ассетов, попыток - db/init.sql + db/migration.sql: таблицы quizzes*, валидация и индексы - public/: конструктор, прохождение, публичная страница, список, критерии оценки - quiz.selftest.js, quiz-ai.selftest.js: юнит-проверки
This commit is contained in:
+164
-11
@@ -1,5 +1,7 @@
|
||||
(function () {
|
||||
const FREE_KINDS = ['line', 'text', 'number', 'date'];
|
||||
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 = {
|
||||
@@ -9,7 +11,10 @@
|
||||
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',
|
||||
@@ -54,6 +59,58 @@
|
||||
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' ? 'Опрос' : 'Тест';
|
||||
}
|
||||
@@ -87,6 +144,7 @@
|
||||
q.author_name ? `<span>Автор: ${esc(q.author_name)}</span>` : '',
|
||||
q.max_attempts != null ? `<span>Попыток: ${q.max_attempts}</span>` : '',
|
||||
q.time_limit_min ? `<span>Время: ${q.time_limit_min} мин</span>` : '',
|
||||
q.retry_cooldown_min ? `<span>Повтор: через ${q.retry_cooldown_min} мин</span>` : '',
|
||||
q.kind === 'test' ? `<span>Порог: ${q.pass_percent}%</span>` : '',
|
||||
`</div>`,
|
||||
`<div class="qz-badges">`,
|
||||
@@ -123,6 +181,13 @@
|
||||
if (!q.is_published) {
|
||||
return '<div class="qz-panel"><p class="qz-hint" style="margin:0">Тест не опубликован. Пройти его может только автор после публикации.</p></div>';
|
||||
}
|
||||
const until = retryUntil();
|
||||
if (until) {
|
||||
return `<div class="qz-panel">
|
||||
<p class="qz-hint" style="margin:0 0 6px">Вы уже прошли ${q.kind === 'survey' ? 'этот опрос' : 'этот тест'} в этом браузере.</p>
|
||||
<p class="qz-hint" id="qzRetryTimer" style="margin:0">${retryLeftText(until)}</p>
|
||||
</div>`;
|
||||
}
|
||||
return `<div class="qz-panel">
|
||||
<div class="qz-sub" style="margin:0 0 10px">
|
||||
${q.kind === 'test' ? 'После отправки ответов будет показан результат.' : 'Ответы сохранятся без оценки.'}
|
||||
@@ -136,7 +201,23 @@
|
||||
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 `<div class="qz-suggest-wrap">
|
||||
<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" data-qsys="${q.kind}" placeholder="Начните вводить название ${label}" autocomplete="off" maxlength="200" value="${esc(value)}">
|
||||
<input type="hidden" data-qsysid="${q.id}" value="${picked}">
|
||||
<div class="qz-suggest" data-sug="${q.id}" hidden></div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
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
|
||||
? `<div class="qz-hint" style="margin-top:4px">Минимум ${q.min_length} символов</div>`
|
||||
@@ -153,6 +234,32 @@
|
||||
return `<input type="text" class="settings-input qz-answer" data-qtext="${q.id}" placeholder="Ваш ответ" maxlength="2000" value="${esc(value)}">${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 => `<button type="button" class="qz-sug-item" data-sug-q="${qid}" data-sug-id="${it.id}" data-sug-name="${at(it.name)}"><span>${esc(it.name)}</span>${it.sub ? `<small>${esc(it.sub)}</small>` : ''}</button>`).join('')
|
||||
: '<div class="qz-sug-empty">Ничего не найдено</div>';
|
||||
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();
|
||||
@@ -189,8 +296,12 @@
|
||||
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
|
||||
@@ -323,7 +434,7 @@
|
||||
? q.options.map(o => {
|
||||
const okClass = data.revealed ? (o.is_correct ? ' ok' : selected.has(Number(o.id)) ? ' bad' : '') : (selected.has(Number(o.id)) ? ' ok' : '');
|
||||
const tag = data.revealed && o.is_correct ? ' ✓' : '';
|
||||
return `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">вес ${o.weight}</span>` : ''}</div>`;
|
||||
return `<div class="qz-opt${okClass}"><span class="qz-opt-text">${esc(o.text)}${tag}</span>${data.revealed && o.weight ? `<span class="qz-opt-weight">балл ${o.weight}</span>` : ''}</div>`;
|
||||
}).join('')
|
||||
: '';
|
||||
return `<section class="qz-q">
|
||||
@@ -420,6 +531,8 @@
|
||||
}
|
||||
|
||||
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(() => ({}));
|
||||
@@ -431,6 +544,8 @@
|
||||
}
|
||||
state.selection = new Map();
|
||||
state.texts = new Map();
|
||||
state.systemIds = new Map();
|
||||
state.sugTimers = new Map();
|
||||
state.result = null;
|
||||
state.attemptDetail = null;
|
||||
renderTake();
|
||||
@@ -442,6 +557,19 @@
|
||||
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;
|
||||
@@ -451,13 +579,6 @@
|
||||
return;
|
||||
}
|
||||
}
|
||||
const missing = state.questions.filter(q => {
|
||||
if (q.required === false) return false;
|
||||
return isFree(q.kind)
|
||||
? !String(state.texts.get(q.id) || '').trim()
|
||||
: !(state.selection.get(q.id) || new Set()).size;
|
||||
}).length;
|
||||
if (missing && !confirm(`Без ответа осталось вопросов: ${missing}. Отправить?`)) return;
|
||||
}
|
||||
const btn = document.querySelector('[data-act="submit"]');
|
||||
if (btn) btn.disabled = true;
|
||||
@@ -465,12 +586,13 @@
|
||||
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 }),
|
||||
body: JSON.stringify({ answers, time_up: auto === true }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось отправить ответы');
|
||||
@@ -479,6 +601,7 @@
|
||||
state.result = data.result;
|
||||
state.revealed = data.revealed;
|
||||
state.tab = 'take';
|
||||
markRetry();
|
||||
renderTab();
|
||||
await loadQuiz(true);
|
||||
showToast(data.revealed ? 'Ответы отправлены' : 'Ответы сохранены');
|
||||
@@ -489,6 +612,8 @@
|
||||
}
|
||||
|
||||
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', {
|
||||
@@ -503,6 +628,8 @@
|
||||
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);
|
||||
@@ -548,11 +675,35 @@
|
||||
document.addEventListener('input', e => {
|
||||
const el = e.target;
|
||||
if (el.dataset.qtext) {
|
||||
state.texts.set(Number(el.dataset.qtext), el.value);
|
||||
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();
|
||||
@@ -606,6 +757,8 @@
|
||||
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;
|
||||
|
||||
Reference in New Issue
Block a user