Files
WhatIDo/quiz.selftest.js
dev 08fc6f9356 feat(quizzes): расширенная статистика тестов и флаг stats_public
- GET /api/quizzes/:id/stats принимает фильтры date_from/date_to,
  student_id, group_id, branch_id, module_id с tz из настроек приложения
- stats_available: статистику видит автор/админ, а при stats_public=true
  — любой авторизованный у опубликованного не удалённого теста
- stats_public сохраняется при создании/редактировании и в бэкап/рестор
- splitanswers/is_correct и прочая разметка правильных ответов отдаётся
  только автору/админу либо при show_answers !== false
- Разрезы статистики по学生/группе/филиалу/модулю через answer_id
  системных полей; ответ totals (attempts, users, anonymous, avg_percent,
  passed, pass_rate) + all_attempts + разрезы + даты
- AGENTS.md: документация по статистике и флагам обязательности/минимальной
  длины ответов
2026-12-02 18:51:41 +03:00

173 lines
9.5 KiB
JavaScript

'use strict';
const {
scoreQuestion,
normalizeAnswerText,
normalizeNumberValue,
normalizeDateValue,
QUESTION_KINDS,
QUIZ_MEDIA_EXT,
statsSummary,
statsFilterRows,
} = require('./lib/quizzes');
let failed = 0;
function ok(label, cond, extra) {
console.log(`${cond ? 'PASS' : 'FAIL'} ${label}${extra !== undefined && !cond ? ' -> ' + JSON.stringify(extra) : ''}`);
if (!cond) failed++;
}
const opts = [
{ id: 1, text: 'A', is_correct: true, weight: 1 },
{ id: 2, text: 'B', is_correct: true, weight: 2 },
{ id: 3, text: 'C', is_correct: false, weight: 1 },
];
const single = {
kind: 'single',
weight: 1.5,
options: [
{ id: 1, text: 'A', is_correct: true, weight: 2 },
{ id: 3, text: 'C', is_correct: false, weight: 1 },
],
};
ok('single: верный ответ даёт баллы варианта (без множителя веса вопроса)',
scoreQuestion(single, [1]).score === 2 && scoreQuestion(single, [1]).max_score === 2,
scoreQuestion(single, [1]));
ok('single: неверный ответ — 0',
scoreQuestion(single, [3]).score === 0 && scoreQuestion(single, [3]).is_correct === false);
ok('single: два выбранных — неверно',
scoreQuestion(single, [1, 3]).score === 0);
const multiple = { kind: 'multiple', weight: 2, partial_credit: false, options: opts };
ok('multiple: точное совпадение даёт максимум',
scoreQuestion(multiple, [1, 2]).score === 3 && scoreQuestion(multiple, [1, 2]).max_score === 3);
ok('multiple: неполный набор — 0',
scoreQuestion(multiple, [1]).score === 0);
ok('multiple: лишний вариант — 0',
scoreQuestion(multiple, [1, 2, 3]).score === 0);
const partial = { kind: 'multiple', weight: 1, partial_credit: true, options: opts };
ok('partial: верный + неверный взаимно гасятся',
scoreQuestion(partial, [1, 3]).score === 0);
ok('partial: только верные — сумма весов',
scoreQuestion(partial, [1, 2]).score === 3);
ok('partial: не уходит ниже нуля',
scoreQuestion(partial, [3]).score === 0);
const fiveCorrect = {
kind: 'multiple',
weight: 0,
partial_credit: true,
options: [1, 2, 3, 4, 5].map(id => ({ id, text: String(id), is_correct: true, weight: 2 })),
};
ok('partial: 5 вариантов по 2 балла, выбраны 3 верных — 6 из 10',
scoreQuestion(fiveCorrect, [1, 2, 3]).score === 6 &&
scoreQuestion(fiveCorrect, [1, 2, 3]).max_score === 10,
scoreQuestion(fiveCorrect, [1, 2, 3]));
const textExact = { kind: 'text', weight: 2, text_match: 'exact', accepted_answers: ['Четыре', '4'] };
ok('text exact: регистр, «ё» и пробелы не важны',
scoreQuestion(textExact, [], ' ЧЕТЫРЕ ').score === 2 &&
scoreQuestion(textExact, [], 'четыре.').score === 2);
ok('text exact: другой ответ — 0',
scoreQuestion(textExact, [], 'пять').score === 0 &&
scoreQuestion(textExact, [], 'пять').is_correct === false);
const textContains = { kind: 'text', weight: 3, text_match: 'contains', accepted_answers: ['потому что'] };
ok('text contains: ответ содержит принимаемый',
scoreQuestion(textContains, [], 'Это так, потому что 2+2=4').score === 3);
ok('text contains: нет вхождения — 0',
scoreQuestion(textContains, [], 'не знаю').score === 0);
const textManual = { kind: 'text', weight: 2, text_match: 'exact', accepted_answers: [] };
ok('text без принимаемых ответов не оценивается',
scoreQuestion(textManual, [], 'что угодно').score === 0 &&
scoreQuestion(textManual, [], 'что угодно').max_score === 0 &&
scoreQuestion(textManual, [], 'что угодно').is_correct === null);
ok('normalizeAnswerText приводит к нижнему регистру и убирает хвостовую пунктуацию',
normalizeAnswerText(' Ёлка, ПАЛКА! ') === 'елка, палка',
normalizeAnswerText(' Ёлка, ПАЛКА! '));
ok('QUIZ_MEDIA_EXT содержит картинки, аудио и видео',
QUIZ_MEDIA_EXT.includes('jpg') && QUIZ_MEDIA_EXT.includes('mp3') && QUIZ_MEDIA_EXT.includes('mp4') && QUIZ_MEDIA_EXT.includes('pdf'));
ok('QUESTION_KINDS содержит строку, список, число и дату',
['single', 'multiple', 'select', 'line', 'text', 'number', 'date'].every(k => QUESTION_KINDS.has(k)),
[...QUESTION_KINDS]);
ok('QUESTION_KINDS содержит системные поля',
['student', 'group', 'branch', 'module'].every(k => QUESTION_KINDS.has(k)),
[...QUESTION_KINDS]);
const systemScore = scoreQuestion({ kind: 'student', weight: 2, options: [] }, [], 'Иван Иванов');
ok('системное поле не оценивается автоматически (0/0, ручная проверка)',
systemScore.score === 0 && systemScore.max_score === 0 && systemScore.is_correct === null,
systemScore);
const selectQ = {
kind: 'select',
weight: 1,
options: [
{ id: 1, text: 'A', is_correct: false, weight: 1 },
{ id: 2, text: 'B', is_correct: true, weight: 1 },
],
};
ok('select оценивается как один ответ', scoreQuestion(selectQ, [2]).score === 1 && scoreQuestion(selectQ, [1]).score === 0,
{ right: scoreQuestion(selectQ, [2]), wrong: scoreQuestion(selectQ, [1]) });
const lineQ = { kind: 'line', weight: 1.5, text_match: 'exact', accepted_answers: ['Москва'] };
ok('line оценивается по принимаемым ответам', scoreQuestion(lineQ, [], ' москва ').score === 1.5 && scoreQuestion(lineQ, [], 'Казань').score === 0);
const numberQ = { kind: 'number', weight: 2, accepted_answers: ['4', '4.0'] };
ok('number сравнивает числа, а не строки',
scoreQuestion(numberQ, [], '4').score === 2 &&
scoreQuestion(numberQ, [], '4,0').score === 2 &&
scoreQuestion(numberQ, [], ' 4.00 ').score === 2 &&
scoreQuestion(numberQ, [], '5').score === 0,
{ four: scoreQuestion(numberQ, [], '4,0'), five: scoreQuestion(numberQ, [], '5') });
ok('number без принимаемых ответов не оценивается', scoreQuestion({ ...numberQ, accepted_answers: [] }, [], '4').max_score === 0);
const dateQ = { kind: 'date', weight: 1, accepted_answers: ['2026-12-31', '31.12.2026'] };
ok('date сравнивает дату в разных форматах',
scoreQuestion(dateQ, [], '2026-12-31').score === 1 &&
scoreQuestion(dateQ, [], '31.12.2026').score === 1 &&
scoreQuestion(dateQ, [], '01.01.2027').score === 0,
{ iso: scoreQuestion(dateQ, [], '2026-12-31'), dotted: scoreQuestion(dateQ, [], '31.12.2026') });
ok('normalizeNumberValue понимает запятую и пробелы',
normalizeNumberValue(' 4,50 ') === 4.5 && normalizeNumberValue('abc') === null);
ok('normalizeDateValue понимает ISO и ДД.ММ.ГГГГ',
normalizeDateValue('2026-12-31') === '2026-12-31' && normalizeDateValue('1.2.2026') === '2026-02-01' && normalizeDateValue('nope') === null);
const statsRows = [
{ id: 1, user_id: 1, percent: 80, passed: true, day: '2026-12-01', student_id: 10, student_name: 'Аня', group_id: 5, group_name: 'Группа A', branch_id: 2, branch_name: 'Филиал 2', module_id: null, module_name: '' },
{ id: 2, user_id: 2, percent: 40, passed: false, day: '2026-12-01', student_id: 11, student_name: 'Борис', group_id: 5, group_name: 'Группа A', branch_id: 2, branch_name: 'Филиал 2', module_id: null, module_name: '' },
{ id: 3, user_id: null, percent: 0, passed: null, day: '2026-12-02', student_id: 10, student_name: 'Аня', group_id: 6, group_name: 'Группа B', branch_id: 3, branch_name: 'Филиал 3', module_id: 7, module_name: 'Фотошоп' },
];
const statsAll = statsSummary(statsRows);
ok('статистика: итоги считают участников, анонимов и сдавших',
statsAll.totals.attempts === 3 && statsAll.totals.users === 2 && statsAll.totals.anonymous === 1 &&
statsAll.totals.passed === 1 && statsAll.totals.avg_percent === 40 && statsAll.totals.pass_rate === 33.33,
statsAll.totals);
ok('статистика: разрез по ученикам суммирует попытки',
statsAll.students.length === 2 && statsAll.students[0].name === 'Аня' &&
statsAll.students[0].attempts === 2 && statsAll.students[0].avg_percent === 40,
statsAll.students);
ok('статистика: разрез по группам, филиалам, модулям и дням',
statsAll.groups.length === 2 && statsAll.groups[0].name === 'Группа A' && statsAll.groups[0].attempts === 2 &&
statsAll.branches.length === 2 && statsAll.modules.length === 1 && statsAll.modules[0].name === 'Фотошоп' &&
statsAll.dates.length === 2 && statsAll.dates[0].date === '2026-12-01' && statsAll.dates[0].attempts === 2,
{ groups: statsAll.groups, branches: statsAll.branches, modules: statsAll.modules, dates: statsAll.dates });
ok('статистика: фильтры по дате/ученику/группе/филиалу/модулю',
statsFilterRows(statsRows, { date_from: '2026-12-02' }).length === 1 &&
statsFilterRows(statsRows, { student_id: 11 }).length === 1 &&
statsFilterRows(statsRows, { group_id: 5 }).length === 2 &&
statsFilterRows(statsRows, { branch_id: 3 }).length === 1 &&
statsFilterRows(statsRows, { module_id: 7 }).length === 1,
statsFilterRows(statsRows, { group_id: 5 }));
console.log(failed ? `\n${failed} проверок провалено` : '\nQUIZ SELFTEST OK');
process.exit(failed ? 1 : 0);