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: документация по статистике и флагам обязательности/минимальной длины ответов
This commit is contained in:
+218
-36
@@ -193,6 +193,7 @@ async function ensureQuizTables(pool) {
|
||||
pass_percent INT NOT NULL DEFAULT 60,
|
||||
cover_path TEXT,
|
||||
allow_anonymous BOOLEAN NOT NULL DEFAULT false,
|
||||
stats_public BOOLEAN NOT NULL DEFAULT false,
|
||||
access_code VARCHAR(64),
|
||||
grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL,
|
||||
author_id INT REFERENCES users(id) ON DELETE SET NULL,
|
||||
@@ -212,6 +213,7 @@ async function ensureQuizTables(pool) {
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS pass_percent INT NOT NULL DEFAULT 60');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS cover_path TEXT');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS allow_anonymous BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS stats_public BOOLEAN NOT NULL DEFAULT false');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS access_code VARCHAR(64)');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS grade_scale_id INT REFERENCES quiz_grade_scales(id) ON DELETE SET NULL');
|
||||
await pool.query('ALTER TABLE quizzes ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
|
||||
@@ -457,6 +459,7 @@ function quizMeta(row) {
|
||||
pass_percent: row.pass_percent,
|
||||
cover_path: row.cover_path,
|
||||
allow_anonymous: row.allow_anonymous === true,
|
||||
stats_public: row.stats_public === true,
|
||||
requires_code: !!(row.access_code && String(row.access_code).trim()),
|
||||
grade_scale_id: row.grade_scale_id == null ? null : Number(row.grade_scale_id),
|
||||
author_id: row.author_id,
|
||||
@@ -511,15 +514,19 @@ async function listQuizzes(pool, user, params = {}) {
|
||||
[...args, user.id, limit, offset]
|
||||
);
|
||||
const totalRes = await pool.query(`SELECT count(*)::int AS c FROM quizzes q ${whereSql}`, args);
|
||||
const items = rows.map(r => ({
|
||||
...quizMeta(r),
|
||||
author_name: r.author_name,
|
||||
question_count: r.question_count,
|
||||
attempt_count: r.attempt_count,
|
||||
my_attempt_count: r.my_attempt_count,
|
||||
can_edit: canEditQuiz(r, user),
|
||||
can_take: r.is_published === true && !r.deleted_at,
|
||||
}));
|
||||
const items = rows.map(r => {
|
||||
const canEdit = canEditQuiz(r, user);
|
||||
return {
|
||||
...quizMeta(r),
|
||||
author_name: r.author_name,
|
||||
question_count: r.question_count,
|
||||
attempt_count: r.attempt_count,
|
||||
my_attempt_count: r.my_attempt_count,
|
||||
can_edit: canEdit,
|
||||
stats_available: canEdit || (r.stats_public === true && r.is_published === true && !r.deleted_at),
|
||||
can_take: r.is_published === true && !r.deleted_at,
|
||||
};
|
||||
});
|
||||
return { items, total: totalRes.rows[0].c };
|
||||
}
|
||||
|
||||
@@ -578,6 +585,7 @@ async function getQuiz(pool, id, user, opts = {}) {
|
||||
current_attempt: current.rows[0] || null,
|
||||
attempts_left: attemptsLeft,
|
||||
can_edit: editable,
|
||||
stats_available: editable || (row.stats_public === true && row.is_published === true && !row.deleted_at),
|
||||
can_take: row.is_published === true && !row.deleted_at && (row.max_attempts == null || attemptsLeft > 0),
|
||||
};
|
||||
}
|
||||
@@ -611,6 +619,7 @@ function normalizeMeta(body, current) {
|
||||
show_results: asBool(body.show_results, current.show_results !== false),
|
||||
show_answers: asBool(body.show_answers, current.show_answers !== false),
|
||||
allow_anonymous: asBool(body.allow_anonymous, current.allow_anonymous === true),
|
||||
stats_public: asBool(body.stats_public, current.stats_public === true),
|
||||
grade_scale_id: kind === 'survey'
|
||||
? null
|
||||
: (body.grade_scale_id === undefined ? (current.grade_scale_id == null ? null : Number(current.grade_scale_id)) : gradeScaleId),
|
||||
@@ -792,12 +801,12 @@ async function saveQuiz(pool, id, user, body = {}) {
|
||||
`UPDATE quizzes SET title = $2, description = $3, kind = $4, is_published = $5, shuffle_questions = $6,
|
||||
shuffle_options = $7, show_results = $8, max_attempts = $9, time_limit_min = $10,
|
||||
pass_percent = $11, cover_path = $12, allow_anonymous = $13, show_answers = $14,
|
||||
grade_scale_id = $15, access_code = $16, retry_cooldown_min = $17, updated_at = now()
|
||||
grade_scale_id = $15, access_code = $16, retry_cooldown_min = $17, stats_public = $18, updated_at = now()
|
||||
WHERE id = $1`,
|
||||
[id, meta.title, meta.description, meta.kind, meta.is_published, meta.shuffle_questions,
|
||||
meta.shuffle_options, meta.show_results, meta.max_attempts, meta.time_limit_min,
|
||||
meta.pass_percent, meta.cover_path, meta.allow_anonymous, meta.show_answers, meta.grade_scale_id,
|
||||
meta.access_code, meta.retry_cooldown_min]
|
||||
meta.access_code, meta.retry_cooldown_min, meta.stats_public]
|
||||
);
|
||||
const { rows: existingQ } = await client.query('SELECT id FROM quiz_questions WHERE quiz_id = $1', [id]);
|
||||
const existingQIds = new Set(existingQ.map(r => r.id));
|
||||
@@ -1215,6 +1224,7 @@ async function getPublicQuiz(pool, quizId) {
|
||||
delete meta.author_id;
|
||||
delete meta.deleted_at;
|
||||
delete meta.purge_at;
|
||||
delete meta.stats_public;
|
||||
return {
|
||||
quiz: {
|
||||
...meta,
|
||||
@@ -1413,54 +1423,224 @@ async function getAttempt(pool, quizId, attemptId, user) {
|
||||
};
|
||||
}
|
||||
|
||||
async function quizStats(pool, quizId, user) {
|
||||
function statsId(v) {
|
||||
const n = Number(v);
|
||||
return Number.isInteger(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
function statsDate(v) {
|
||||
const s = typeof v === 'string' ? v.trim() : '';
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
|
||||
const d = new Date(`${s}T00:00:00Z`);
|
||||
if (Number.isNaN(d.getTime()) || d.toISOString().slice(0, 10) !== s) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
function statsFilterRows(rows, filters) {
|
||||
return rows.filter(r =>
|
||||
(!filters.date_from || (r.day && r.day >= filters.date_from)) &&
|
||||
(!filters.date_to || (r.day && r.day <= filters.date_to)) &&
|
||||
(!filters.student_id || Number(r.student_id) === filters.student_id) &&
|
||||
(!filters.group_id || Number(r.group_id) === filters.group_id) &&
|
||||
(!filters.branch_id || Number(r.branch_id) === filters.branch_id) &&
|
||||
(!filters.module_id || Number(r.module_id) === filters.module_id)
|
||||
);
|
||||
}
|
||||
|
||||
function statsBucket(rows, idKey, nameKey) {
|
||||
const map = new Map();
|
||||
for (const r of rows) {
|
||||
const id = r[idKey];
|
||||
if (id == null) continue;
|
||||
const key = String(id);
|
||||
const name = r[nameKey] || '';
|
||||
let item = map.get(key);
|
||||
if (!item) {
|
||||
item = { id: Number(id), name, attempts: 0, percent_sum: 0, passed: 0 };
|
||||
map.set(key, item);
|
||||
}
|
||||
item.attempts += 1;
|
||||
item.percent_sum += Number(r.percent) || 0;
|
||||
if (r.passed === true) item.passed += 1;
|
||||
if (!item.name && name) item.name = name;
|
||||
}
|
||||
return [...map.values()]
|
||||
.map(x => ({
|
||||
id: x.id,
|
||||
name: x.name,
|
||||
attempts: x.attempts,
|
||||
avg_percent: x.attempts ? round2(x.percent_sum / x.attempts) : 0,
|
||||
passed: x.passed,
|
||||
}))
|
||||
.sort((a, b) => (a.name || '').localeCompare(b.name || '', 'ru') || a.id - b.id);
|
||||
}
|
||||
|
||||
function statsSummary(rows) {
|
||||
const attempts = rows.length;
|
||||
const users = new Set();
|
||||
let anonymous = 0;
|
||||
let percentSum = 0;
|
||||
let passed = 0;
|
||||
for (const r of rows) {
|
||||
if (r.user_id == null) anonymous += 1;
|
||||
else users.add(String(r.user_id));
|
||||
percentSum += Number(r.percent) || 0;
|
||||
if (r.passed === true) passed += 1;
|
||||
}
|
||||
const days = new Map();
|
||||
for (const r of rows) {
|
||||
if (!r.day) continue;
|
||||
let item = days.get(r.day);
|
||||
if (!item) {
|
||||
item = { date: r.day, attempts: 0, percent_sum: 0, passed: 0 };
|
||||
days.set(r.day, item);
|
||||
}
|
||||
item.attempts += 1;
|
||||
item.percent_sum += Number(r.percent) || 0;
|
||||
if (r.passed === true) item.passed += 1;
|
||||
}
|
||||
return {
|
||||
totals: {
|
||||
attempts,
|
||||
users: users.size,
|
||||
anonymous,
|
||||
avg_percent: attempts ? round2(percentSum / attempts) : 0,
|
||||
passed,
|
||||
pass_rate: attempts ? round2((passed / attempts) * 100) : 0,
|
||||
},
|
||||
dates: [...days.values()]
|
||||
.sort((a, b) => a.date.localeCompare(b.date))
|
||||
.map(x => ({
|
||||
date: x.date,
|
||||
attempts: x.attempts,
|
||||
avg_percent: round2(x.percent_sum / x.attempts),
|
||||
passed: x.passed,
|
||||
})),
|
||||
students: statsBucket(rows, 'student_id', 'student_name'),
|
||||
groups: statsBucket(rows, 'group_id', 'group_name'),
|
||||
branches: statsBucket(rows, 'branch_id', 'branch_name'),
|
||||
modules: statsBucket(rows, 'module_id', 'module_name'),
|
||||
};
|
||||
}
|
||||
|
||||
function statsOptions(rows) {
|
||||
const pick = list => list.map(x => ({ id: x.id, name: x.name }));
|
||||
return {
|
||||
students: pick(statsBucket(rows, 'student_id', 'student_name')),
|
||||
groups: pick(statsBucket(rows, 'group_id', 'group_name')),
|
||||
branches: pick(statsBucket(rows, 'branch_id', 'branch_name')),
|
||||
modules: pick(statsBucket(rows, 'module_id', 'module_name')),
|
||||
};
|
||||
}
|
||||
|
||||
async function quizStats(pool, quizId, user, params = {}) {
|
||||
const row = await findQuizRow(pool, quizId);
|
||||
if (!row) throw httpError(404, 'Тест не найден');
|
||||
if (!canEditQuiz(row, user)) throw httpError(403, 'Статистика доступна автору и администратору');
|
||||
const totals = await pool.query(
|
||||
`SELECT count(*)::int AS attempts, count(DISTINCT user_id)::int AS users,
|
||||
COALESCE(round(avg(percent), 2), 0) AS avg_percent,
|
||||
count(*) FILTER (WHERE passed)::int AS passed
|
||||
FROM quiz_attempts WHERE quiz_id = $1 AND status = 'done'`,
|
||||
[quizId]
|
||||
);
|
||||
const { questions } = await loadQuizStructure(pool, quizId);
|
||||
const answers = await pool.query(
|
||||
`SELECT aa.question_id, aa.option_ids, aa.text_answer
|
||||
FROM quiz_attempt_answers aa
|
||||
JOIN quiz_attempts a ON a.id = aa.attempt_id
|
||||
WHERE a.quiz_id = $1 AND a.status = 'done'`,
|
||||
[quizId]
|
||||
const editable = canEditQuiz(row, user);
|
||||
const statsPublic = row.stats_public === true && row.is_published === true && !row.deleted_at;
|
||||
if (!editable && !statsPublic) throw httpError(403, 'Статистика доступна автору и администратору');
|
||||
const tz = typeof params.tz === 'string' && params.tz ? params.tz : 'UTC';
|
||||
const filters = {
|
||||
date_from: statsDate(params.date_from),
|
||||
date_to: statsDate(params.date_to),
|
||||
student_id: statsId(params.student_id),
|
||||
group_id: statsId(params.group_id),
|
||||
branch_id: statsId(params.branch_id),
|
||||
module_id: statsId(params.module_id),
|
||||
};
|
||||
const { rows } = await pool.query(
|
||||
`WITH ans AS (
|
||||
SELECT aa.attempt_id,
|
||||
MAX(aa.answer_id) FILTER (WHERE qq.kind = 'student') AS student_id,
|
||||
MAX(aa.answer_id) FILTER (WHERE qq.kind = 'group') AS group_id,
|
||||
MAX(aa.answer_id) FILTER (WHERE qq.kind = 'branch') AS branch_id,
|
||||
MAX(aa.answer_id) FILTER (WHERE qq.kind = 'module') AS module_id
|
||||
FROM quiz_attempt_answers aa
|
||||
JOIN quiz_attempts a2 ON a2.id = aa.attempt_id
|
||||
JOIN quiz_questions qq ON qq.id = aa.question_id
|
||||
WHERE a2.quiz_id = $1 AND a2.status = 'done' AND aa.answer_id IS NOT NULL
|
||||
GROUP BY aa.attempt_id
|
||||
),
|
||||
base AS (
|
||||
SELECT a.id, a.user_id, a.percent, a.passed,
|
||||
to_char(a.finished_at AT TIME ZONE $2, 'YYYY-MM-DD') AS day,
|
||||
an.student_id, s.name AS student_name, s.group_id AS student_group_id,
|
||||
an.group_id AS answer_group_id, an.branch_id AS answer_branch_id, an.module_id
|
||||
FROM quiz_attempts a
|
||||
LEFT JOIN ans an ON an.attempt_id = a.id
|
||||
LEFT JOIN students s ON s.id = an.student_id
|
||||
WHERE a.quiz_id = $1 AND a.status = 'done'
|
||||
),
|
||||
resolved AS (
|
||||
SELECT b.*, COALESCE(b.answer_group_id, b.student_group_id) AS group_id
|
||||
FROM base b
|
||||
)
|
||||
SELECT r.id, r.user_id, r.percent, r.passed, r.day,
|
||||
r.student_id, COALESCE(r.student_name, '') AS student_name,
|
||||
r.group_id, COALESCE(g.name, '') AS group_name,
|
||||
COALESCE(r.answer_branch_id, g.branch_id) AS branch_id,
|
||||
COALESCE(b2.name, '') AS branch_name,
|
||||
r.module_id, COALESCE(m.name, '') AS module_name
|
||||
FROM resolved r
|
||||
LEFT JOIN groups g ON g.id = r.group_id
|
||||
LEFT JOIN branches b2 ON b2.id = COALESCE(r.answer_branch_id, g.branch_id)
|
||||
LEFT JOIN modules m ON m.id = r.module_id
|
||||
ORDER BY r.id`,
|
||||
[quizId, tz]
|
||||
);
|
||||
const filtered = statsFilterRows(rows, filters);
|
||||
const summary = statsSummary(filtered);
|
||||
const revealKeys = editable || row.show_answers !== false;
|
||||
const attemptIds = filtered.map(r => r.id);
|
||||
const structure = await loadQuizStructure(pool, quizId);
|
||||
const answers = attemptIds.length
|
||||
? await pool.query(
|
||||
`SELECT aa.question_id, aa.option_ids, aa.text_answer, aa.is_correct
|
||||
FROM quiz_attempt_answers aa
|
||||
WHERE aa.attempt_id = ANY($1::int[])`,
|
||||
[attemptIds]
|
||||
)
|
||||
: { rows: [] };
|
||||
const counts = new Map();
|
||||
const texts = new Map();
|
||||
const answered = new Map();
|
||||
const correct = new Map();
|
||||
for (const a of answers.rows) {
|
||||
if (a.question_id == null) continue;
|
||||
if (!counts.has(a.question_id)) counts.set(a.question_id, new Map());
|
||||
const m = counts.get(a.question_id);
|
||||
for (const id of a.option_ids || []) m.set(id, (m.get(id) || 0) + 1);
|
||||
answered.set(a.question_id, (answered.get(a.question_id) || 0) + 1);
|
||||
if (a.is_correct === true) correct.set(a.question_id, (correct.get(a.question_id) || 0) + 1);
|
||||
if (a.text_answer) {
|
||||
if (!texts.has(a.question_id)) texts.set(a.question_id, []);
|
||||
texts.get(a.question_id).push(a.text_answer);
|
||||
}
|
||||
}
|
||||
return {
|
||||
totals: {
|
||||
attempts: totals.rows[0].attempts,
|
||||
users: totals.rows[0].users,
|
||||
avg_percent: Number(totals.rows[0].avg_percent),
|
||||
passed: totals.rows[0].passed,
|
||||
},
|
||||
questions: questions.map(q => ({
|
||||
can_edit: editable,
|
||||
reveal_keys: revealKeys,
|
||||
filters,
|
||||
all_attempts: rows.length,
|
||||
available: statsOptions(rows),
|
||||
totals: summary.totals,
|
||||
dates: summary.dates,
|
||||
students: summary.students,
|
||||
groups: summary.groups,
|
||||
branches: summary.branches,
|
||||
modules: summary.modules,
|
||||
questions: structure.questions.map(q => ({
|
||||
id: q.id,
|
||||
kind: q.kind,
|
||||
text: q.text,
|
||||
text_match: q.text_match,
|
||||
accepted_answers: q.accepted_answers,
|
||||
accepted_answers: revealKeys ? q.accepted_answers : [],
|
||||
answered: answered.get(q.id) || 0,
|
||||
correct: revealKeys ? (correct.get(q.id) || 0) : null,
|
||||
options: q.options.map(o => ({
|
||||
id: o.id,
|
||||
text: o.text,
|
||||
is_correct: o.is_correct,
|
||||
is_correct: revealKeys ? o.is_correct : false,
|
||||
count: (counts.get(q.id) || new Map()).get(o.id) || 0,
|
||||
})),
|
||||
texts: (texts.get(q.id) || []).slice(0, 200),
|
||||
@@ -1551,6 +1731,8 @@ module.exports = {
|
||||
listAttempts,
|
||||
getAttempt,
|
||||
quizStats,
|
||||
statsSummary,
|
||||
statsFilterRows,
|
||||
purgeQuizzes,
|
||||
cleanupQuizAssets,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user