Тесты и опросы: критерии оценки, 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:
dev
2026-12-02 18:19:18 +03:00
parent cb2621d848
commit 646d352a9e
20 changed files with 822 additions and 151 deletions
+71 -14
View File
@@ -5,13 +5,18 @@
let saving = false;
let dragState = null;
const FREE_KINDS = ['line', 'text', 'number', 'date'];
const SYSTEM_KINDS = ['student', 'group', 'branch', 'module'];
const FREE_KINDS = ['line', 'text', 'number', 'date', ...SYSTEM_KINDS];
const OPTION_KINDS = ['single', 'multiple', 'select'];
function isFree(kind) {
return FREE_KINDS.includes(kind);
}
function isSystemKind(kind) {
return SYSTEM_KINDS.includes(kind);
}
function isOptionKind(kind) {
return OPTION_KINDS.includes(kind);
}
@@ -24,6 +29,35 @@
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
}
function round2(n) {
return Math.round((Number(n) || 0) * 100) / 100;
}
function isPlainFree(kind) {
return kind === 'line' || kind === 'text' || kind === 'number' || kind === 'date';
}
function questionPoints(q) {
if (!state.quiz || state.quiz.kind !== 'test') return 0;
if (isSystemKind(q.kind)) return 0;
if (isFree(q.kind)) return round2(Math.max(0, Number(q.weight) || 0));
return round2((q.options || []).reduce((sum, o) => sum + (o.is_correct ? Math.max(0, Number(o.weight) || 0) : 0), 0));
}
function updatePoints() {
const isTest = !!(state.quiz && state.quiz.kind === 'test');
const totalEl = document.getElementById('qeTotalPoints');
if (totalEl) {
totalEl.hidden = !isTest;
if (isTest) totalEl.textContent = 'Всего баллов: ' + round2(state.questions.reduce((sum, q) => sum + questionPoints(q), 0));
}
document.querySelectorAll('[data-qpoints]').forEach(node => {
const q = state.questions[Number(node.dataset.qpoints)];
if (!q) return;
node.textContent = 'Макс. баллов: ' + round2(questionPoints(q));
});
}
function assetName(a) {
return String(a.path || '').split('/').pop();
}
@@ -71,8 +105,10 @@
show_answers: quiz.show_answers !== false,
grade_scale_id: quiz.grade_scale_id == null ? '' : quiz.grade_scale_id,
allow_anonymous: quiz.allow_anonymous === true,
access_code: quiz.access_code || '',
max_attempts: quiz.max_attempts == null ? '' : quiz.max_attempts,
time_limit_min: quiz.time_limit_min || 0,
retry_cooldown_min: Number(quiz.retry_cooldown_min) || 0,
pass_percent: quiz.pass_percent == null ? 60 : quiz.pass_percent,
cover_path: quiz.cover_path || null,
};
@@ -82,7 +118,7 @@
kind: normalizeKind(q.kind),
text: q.text || '',
description: q.description || '',
weight: q.weight == null ? 1 : Number(q.weight),
weight: q.weight == null ? 0 : Number(q.weight),
partial_credit: q.partial_credit === true,
required: q.required !== false,
min_length: Number(q.min_length) || 0,
@@ -95,7 +131,7 @@
text: o.text || '',
description: o.description || '',
is_correct: o.is_correct === true,
weight: o.weight == null ? 1 : Number(o.weight),
weight: o.weight == null ? 0 : Number(o.weight),
assets: Array.isArray(o.assets) ? o.assets.slice() : [],
})),
}));
@@ -114,8 +150,10 @@
show_answers: q.show_answers,
grade_scale_id: q.grade_scale_id === '' ? null : q.grade_scale_id,
allow_anonymous: q.allow_anonymous,
access_code: q.access_code || '',
max_attempts: q.max_attempts === '' ? null : q.max_attempts,
time_limit_min: q.time_limit_min === '' ? 0 : q.time_limit_min,
retry_cooldown_min: q.retry_cooldown_min === '' ? 0 : q.retry_cooldown_min,
pass_percent: q.pass_percent === '' ? 60 : q.pass_percent,
cover_path: q.cover_path,
asset_ids: state.assets.map(a => a.id),
@@ -175,7 +213,7 @@
<span class="toggle-track"><span class="toggle-thumb"></span></span>
<span class="toggle-text"><small>Верный</small></span>
</label>
<label class="qe-weight" title="Вес ответа"><span>вес</span>
<label class="qe-weight" title="Баллы за вариант"><span>балл</span>
<input type="number" class="settings-input qe-opt-weight" data-oi="${oi}" data-field="weight" min="0" max="100" step="0.5" value="${at(o.weight)}">
</label>` : ''}
<button type="button" class="icon-btn" data-act="del-option" data-oi="${oi}" title="Удалить вариант"><i data-lucide="trash-2"></i></button>
@@ -189,7 +227,7 @@
}
function acceptedHtml(q, qi, isTest) {
if (!isFree(q.kind) || !isTest) return '';
if (!isFree(q.kind) || !isTest || isSystemKind(q.kind)) return '';
const hints = {
line: 'Ответ вводится одной строкой. Регистр, «ё» и лишние пробелы не важны.',
text: 'Ответ вводится многострочным текстом. Регистр, «ё» и лишние пробелы не важны.',
@@ -212,7 +250,7 @@
<span></span>
<textarea id="qeAccepted${qi}" class="settings-input" rows="2" data-qi="${qi}" data-field="accepted_raw" placeholder="${placeholder}" maxlength="4000">${esc((q.accepted_answers || []).join('\n'))}</textarea>
${matchSelect}
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос: вес вопроса.</span>
<span class="qe-hint">${hints[q.kind] || ''} Балл за вопрос задаётся полем «балл» у вопроса.</span>
</div>`;
}
@@ -227,6 +265,10 @@
['text', 'Многострочный текст'],
['number', 'Число'],
['date', 'Дата'],
['student', 'Ученик — поиск по имени'],
['group', 'Группа — поиск по названию'],
['branch', 'Филиал — поиск по названию'],
['module', 'Тема модуля — поиск по названию'],
].map(([value, label]) => `<option value="${value}"${q.kind === value ? ' selected' : ''}>${label}</option>`).join('');
const options = isOptionKind(q.kind) ? `
<div data-options="${qi}">${q.options.map((o, oi) => optionHtml(o, qi, oi, isTest)).join('')}</div>
@@ -236,7 +278,8 @@
<span class="qe-drag" draggable="true" title="Перетащить вопрос">⠿</span>
<span class="qe-q-num">${qi + 1}</span>
<select class="settings-input" data-role="qkind" data-qi="${qi}">${kindOptions}</select>
${isTest ? `<label class="qe-weight" title="Вес вопроса"><span>вес</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
${isTest && isPlainFree(q.kind) ? `<label class="qe-weight" title="Баллы за вопрос"><span>балл</span><input type="number" class="settings-input qe-q-weight" style="max-width:90px" data-qi="${qi}" data-field="weight" min="0" max="100" step="0.5" value="${at(q.weight)}"></label>` : ''}
${isTest && !isSystemKind(q.kind) ? `<span class="qe-points" data-qpoints="${qi}">Макс. баллов: ${round2(questionPoints(q))}</span>` : ''}
<span class="spacer"></span>
<button type="button" class="icon-btn" data-act="up" data-qi="${qi}" title="Выше"><i data-lucide="arrow-up"></i></button>
<button type="button" class="icon-btn" data-act="down" data-qi="${qi}" title="Ниже"><i data-lucide="arrow-down"></i></button>
@@ -275,10 +318,12 @@
const wrap = document.getElementById('qeQuestions');
if (!state.questions.length) {
wrap.innerHTML = '<div class="qe-panel"><p class="qe-hint" style="margin:0">Вопросов пока нет. Добавьте первый вопрос.</p></div>';
updatePoints();
return;
}
wrap.innerHTML = state.questions.map(questionHtml).join('');
renderIcons();
updatePoints();
}
function renderQuizAssets() {
@@ -365,11 +410,13 @@
document.getElementById('qePass').value = q.pass_percent;
document.getElementById('qeAttempts').value = q.max_attempts;
document.getElementById('qeTime').value = q.time_limit_min;
document.getElementById('qeRetry').value = q.retry_cooldown_min;
document.getElementById('qePublished').checked = q.is_published;
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('qeAccessCode').value = q.access_code || '';
document.getElementById('qeShowAnswersWrap').hidden = q.kind !== 'test';
document.getElementById('qeGradeWrap').hidden = q.kind !== 'test';
renderGradeSelect();
@@ -574,8 +621,8 @@
q.options = [];
} else if (q.options.length < 2) {
q.options = [
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 1, assets: [] },
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
{ id: null, text: '', description: '', is_correct: q.kind !== 'multiple', weight: 0, assets: [] },
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
];
}
markDirty();
@@ -602,6 +649,7 @@
opt[field] = el.value;
}
markDirty();
updatePoints();
return;
}
if (el.dataset.qi !== undefined) {
@@ -622,6 +670,7 @@
q.text_match = el.value === 'contains' ? 'contains' : 'exact';
} else q[field] = el.value;
markDirty();
updatePoints();
}
}
@@ -703,7 +752,7 @@
const act = btn.dataset.act;
if (act === 'add-option') {
const qi = Number(btn.dataset.qi);
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] });
state.questions[qi].options.push({ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] });
markDirty();
renderAll();
return;
@@ -787,6 +836,14 @@
state.quiz.time_limit_min = e.target.value === '' ? 0 : Number(e.target.value);
markDirty();
});
document.getElementById('qeRetry').addEventListener('input', e => {
state.quiz.retry_cooldown_min = e.target.value === '' ? 0 : Number(e.target.value);
markDirty();
});
document.getElementById('qeAccessCode').addEventListener('input', e => {
state.quiz.access_code = e.target.value;
markDirty();
});
['qePublished', 'qeShuffleQ', 'qeShuffleO', 'qeShowResults', 'qeShowAnswers', 'qeAnonymous'].forEach(id => {
document.getElementById(id).addEventListener('change', e => {
const map = {
@@ -821,8 +878,8 @@
kind: 'single',
text: '',
description: '',
weight: 1,
partial_credit: false,
weight: 0,
partial_credit: true,
required: true,
min_length: 0,
options_inline: false,
@@ -830,8 +887,8 @@
accepted_answers: [],
assets: [],
options: [
{ id: null, text: '', description: '', is_correct: true, weight: 1, assets: [] },
{ id: null, text: '', description: '', is_correct: false, weight: 1, assets: [] },
{ id: null, text: '', description: '', is_correct: true, weight: 0, assets: [] },
{ id: null, text: '', description: '', is_correct: false, weight: 0, assets: [] },
],
});
markDirty();