feat: student achievements (admin-managed types + per-student records, UI & backup)

This commit is contained in:
dev
2026-10-27 13:02:56 +03:00
parent 2bc96aaecc
commit 12034812ec
12 changed files with 1067 additions and 6 deletions
+236 -2
View File
@@ -67,6 +67,24 @@ const {
publicArticle: publicDocArticle,
docsError,
} = require('./lib/docs');
const {
achError,
normAchDate,
achRecordFields,
achFieldsError,
ACH_TYPE_NAME_MAX,
ACH_VALUE_MAX,
ACH_NOTE_MAX,
listTypes: achListTypes,
createType: achCreateType,
updateType: achUpdateType,
deleteType: achDeleteType,
reorderTypes: achReorderTypes,
listForStudent: achListForStudent,
createRecord: achCreateRecord,
updateRecord: achUpdateRecord,
deleteRecord: achDeleteRecord,
} = require('./lib/achievements');
const https = require('https');
const path = require('path');
@@ -2743,6 +2761,31 @@ async function ensureBookmarksTable() {
await pool.query('CREATE INDEX IF NOT EXISTS idx_bookmarks_sort ON bookmarks(sort_order, id)');
}
async function ensureAchievementsTables() {
await pool.query(`CREATE TABLE IF NOT EXISTS achievement_types (
id SERIAL PRIMARY KEY,
name VARCHAR(150) NOT NULL,
sort_order INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT true,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_achievement_types_name ON achievement_types(lower(name))');
await pool.query('CREATE INDEX IF NOT EXISTS idx_achievement_types_order ON achievement_types(sort_order, id)');
await pool.query(`CREATE TABLE IF NOT EXISTS student_achievements (
id SERIAL PRIMARY KEY,
student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE,
type_name VARCHAR(150) NOT NULL,
value VARCHAR(200) NOT NULL DEFAULT '',
achieved_at DATE,
note TEXT NOT NULL DEFAULT '',
author_id INT REFERENCES users(id) ON DELETE SET NULL,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_student_achievements_student ON student_achievements(student_id)');
}
async function ensureApiKeysTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS api_keys (
id SERIAL PRIMARY KEY,
@@ -2783,6 +2826,7 @@ async function ensureUsersAndFirstAdmin() {
await ensureApiKeysTable();
await ensureUserNotesTable();
await ensureBookmarksTable();
await ensureAchievementsTables();
await ensureDocsTables(pool);
await ensureFirstAdmin();
}
@@ -4995,6 +5039,68 @@ app.delete('/api/bookmarks/:id/photo', requireAdmin, async (req, res) => {
res.json({ ok: true });
});
app.get('/api/achievement-types', requireAuth, async (req, res) => {
try {
res.json({ items: await achListTypes(pool) });
} catch (e) {
achError(res, e, 'Не удалось получить типы достижений', 'achievement types list');
}
});
app.post('/api/achievement-types', requireAdmin, async (req, res) => {
try {
const name = reqStr(req.body?.name, ACH_TYPE_NAME_MAX);
const item = await achCreateType(pool, name);
await logAudit(req, 'achievement.type.create', { id: item.id, name: item.name });
res.json({ item });
} catch (e) {
achError(res, e, 'Не удалось создать тип достижения', 'achievement type create');
}
});
app.put('/api/achievement-types/reorder', requireAdmin, async (req, res) => {
try {
const raw = Array.isArray(req.body?.ids) ? req.body.ids : null;
if (!raw || raw.some(id => !Number.isInteger(Number(id)))) {
return res.status(400).json({ error: 'Некорректный порядок типов' });
}
const ids = raw.map(id => Number(id));
if (ids.some(id => id < 1)) return res.status(400).json({ error: 'Некорректный порядок типов' });
if (new Set(ids).size !== ids.length) {
return res.status(400).json({ error: 'Порядок содержит дубликаты' });
}
await achReorderTypes(pool, ids);
await logAudit(req, 'achievement.type.reorder', { order: ids });
res.json({ ok: true });
} catch (e) {
achError(res, e, 'Не удалось сохранить порядок типов', 'achievement type reorder');
}
});
app.put('/api/achievement-types/:id', requireAdmin, async (req, res) => {
try {
const id = reqInt(req.params.id);
const name = reqStr(req.body?.name, ACH_TYPE_NAME_MAX);
const isActive = typeof req.body?.is_active === 'boolean' ? req.body.is_active : undefined;
const { item, renamed } = await achUpdateType(pool, id, name, isActive);
await logAudit(req, 'achievement.type.update', { id, name: item.name, is_active: item.is_active, renamed });
res.json({ item });
} catch (e) {
achError(res, e, 'Не удалось обновить тип достижения', 'achievement type update');
}
});
app.delete('/api/achievement-types/:id', requireAdmin, async (req, res) => {
try {
const id = reqInt(req.params.id);
const gone = await achDeleteType(pool, id);
await logAudit(req, 'achievement.type.delete', { id, name: gone.name });
res.json({ ok: true });
} catch (e) {
achError(res, e, 'Не удалось удалить тип достижения', 'achievement type delete');
}
});
app.get('/api/docs/tree', requireAuth, async (req, res) => {
try {
res.json(await docsTree(pool, req.user));
@@ -6295,7 +6401,7 @@ function sweepBackupStorage() {
async function buildBackupArchive() {
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
try {
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di] = await Promise.all([
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs, swm, ds, da, di, atr, sar] = await Promise.all([
pool.query('SELECT * FROM groups ORDER BY id'),
pool.query('SELECT * FROM students ORDER BY id'),
pool.query('SELECT * FROM entries ORDER BY id'),
@@ -6330,6 +6436,8 @@ async function buildBackupArchive() {
pool.query('SELECT * FROM doc_sections ORDER BY id'),
pool.query('SELECT * FROM doc_articles ORDER BY id'),
pool.query('SELECT * FROM doc_images ORDER BY id'),
pool.query('SELECT * FROM achievement_types ORDER BY id'),
pool.query('SELECT * FROM student_achievements ORDER BY id'),
]);
const settings = {};
st.rows.forEach(r => { settings[r.key] = r.value; });
@@ -6348,9 +6456,11 @@ async function buildBackupArchive() {
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount,
bookmarks: bm.rowCount,
student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount, student_work_marks: swm.rowCount,
achievement_types: atr.rowCount, student_achievements: sar.rowCount,
doc_sections: ds.rowCount, doc_articles: da.rowCount, doc_images: di.rowCount,
},
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows, student_work_marks: swm.rows,
achievement_types: atr.rows, student_achievements: sar.rows,
doc_sections: ds.rows, doc_articles: da.rows, doc_images: di.rows,
};
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
@@ -6559,6 +6669,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
await client.query('DELETE FROM feedbacks');
await client.query('DELETE FROM entries');
await client.query('DELETE FROM modules');
await client.query('DELETE FROM student_achievements');
await client.query('DELETE FROM students');
await client.query('DELETE FROM share_links');
await client.query('DELETE FROM groups');
@@ -6570,6 +6681,7 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
await client.query('DELETE FROM user_settings');
await client.query('DELETE FROM user_notes');
await client.query('DELETE FROM bookmarks');
await client.query('DELETE FROM achievement_types');
await client.query('DELETE FROM photo_faces');
await client.query('DELETE FROM student_face_refs');
await client.query('DELETE FROM doc_images');
@@ -6611,6 +6723,12 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
[x.id, x.title, x.url, x.description, x.photo_path || null, x.image_mode === 'cover' ? 'cover' : 'logo', x.open_new_tab !== false, x.is_active !== false, x.sort_order, x.created_at || null, x.updated_at || null]
);
}
for (const x of (ndata.achievement_types || [])) {
await client.query(
'INSERT INTO achievement_types (id, name, sort_order, is_active, created_at, updated_at) VALUES ($1,$2,$3,$4,$5,$6)',
[x.id, x.name, x.sort_order, x.is_active !== false, x.created_at || null, x.updated_at || null]
);
}
for (const x of (ndata.doc_sections || [])) {
await client.query(
'INSERT INTO doc_sections (id, parent_id, title, sort_order, tutor_edit, is_public, created_at, updated_at) VALUES ($1, NULL, $2, $3, $4, $5, $6, $7)',
@@ -6666,6 +6784,15 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
[x.id, x.student_id, x.photo_path, JSON.stringify(x.embedding || []), x.det_score || 0, x.created_at || null]
);
}
for (const x of (ndata.student_achievements || [])) {
const ex = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
if (!ex.rowCount) continue;
await client.query(
`INSERT INTO student_achievements (id, student_id, type_name, value, achieved_at, note, author_id, created_at, updated_at)
VALUES ($1,$2,$3,$4,$5,$6,(SELECT id FROM users WHERE id = $7),$8,$9)`,
[x.id, x.student_id, x.type_name, x.value, x.achieved_at || null, x.note, x.author_id, x.created_at || null, x.updated_at || null]
);
}
for (const x of ndata.modules) {
await client.query(
'INSERT INTO modules (id, name, lessons_count, is_active, has_attachments, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
@@ -9093,7 +9220,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
}
const fWhere = fConds.join(' AND ');
const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes] = await Promise.all([
const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes, achList] = await Promise.all([
student.group_id ? pool.query('SELECT id, name FROM groups WHERE id = $1', [student.group_id]) : Promise.resolve({ rows: [] }),
pool.query(`SELECT count(*)::int AS n FROM entries e JOIN groups g ON g.id = e.group_id WHERE ${eWhere}`, eParams),
(() => {
@@ -9137,6 +9264,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
(SELECT count(*)::int FROM photo_faces WHERE student_id IS NULL AND best_student_id = $1 AND best_score >= $2) AS similar`,
[id, FACE_CANDIDATE_MIN]
),
achListForStudent(pool, id),
]);
const entryIds = entriesRes.rows.map(r => r.id);
@@ -9160,6 +9288,7 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
shorts: { items: shortsRes.rows, total: shortsTotalRes.rows[0].n },
photos: { items: photosRes.rows, photo_path: student.photo_path || null },
faces: { refs: faces.refs || 0, found: faces.found || 0, similar: faces.similar || 0 },
achievements: achList || { items: [], total: 0 },
});
} catch (e) {
console.error('student overview:', e);
@@ -9167,6 +9296,111 @@ app.get('/api/students/:id/overview', requireAuth, async (req, res) => {
}
});
app.get('/api/students/:id/achievements', requireAuth, async (req, res) => {
let id;
try {
id = reqInt(req.params.id);
} catch {
return res.status(400).json({ error: 'Неверный id ученика' });
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) {
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
}
try {
res.json(await achListForStudent(pool, id));
} catch (e) {
achError(res, e, 'Не удалось получить достижения', 'student achievements list');
}
});
app.post('/api/students/:id/achievements', requireAuth, async (req, res) => {
let id;
try {
id = reqInt(req.params.id);
} catch {
return res.status(400).json({ error: 'Неверный id ученика' });
}
let fields;
try {
fields = achRecordFields(req.body);
} catch (e) {
return res.status(400).json({ error: achFieldsError(e) });
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) {
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
}
try {
const item = await achCreateRecord(pool, { ...fields, studentId: id, authorId: req.user.id });
await logAudit(req, 'achievement.create', { id: item.id, student_id: id, type_name: item.type_name });
invalidateStudents();
res.json({ item });
} catch (e) {
achError(res, e, 'Не удалось добавить достижение', 'student achievement create');
}
});
app.put('/api/students/:id/achievements/:aid', requireAuth, async (req, res) => {
let id;
try {
id = reqInt(req.params.id);
} catch {
return res.status(400).json({ error: 'Неверный id ученика' });
}
let aid;
try {
aid = reqInt(req.params.aid);
} catch {
return res.status(400).json({ error: 'Неверный id достижения' });
}
let fields;
try {
fields = achRecordFields(req.body);
} catch (e) {
return res.status(400).json({ error: achFieldsError(e) });
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) {
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
}
try {
const item = await achUpdateRecord(pool, id, aid, fields);
await logAudit(req, 'achievement.update', { id: aid, student_id: id, type_name: item.type_name });
invalidateStudents();
res.json({ item });
} catch (e) {
achError(res, e, 'Не удалось обновить достижение', 'student achievement update');
}
});
app.delete('/api/students/:id/achievements/:aid', requireAuth, async (req, res) => {
let id;
try {
id = reqInt(req.params.id);
} catch {
return res.status(400).json({ error: 'Неверный id ученика' });
}
let aid;
try {
aid = reqInt(req.params.aid);
} catch {
return res.status(400).json({ error: 'Неверный id достижения' });
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) {
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
}
try {
const item = await achDeleteRecord(pool, id, aid);
await logAudit(req, 'achievement.delete', { id: aid, student_id: id, type_name: item.type_name });
invalidateStudents();
res.json({ ok: true });
} catch (e) {
achError(res, e, 'Не удалось удалить достижение', 'student achievement delete');
}
});
app.post('/api/students/:id/photos', requireAuth, (req, res, next) => {
studentPhotoUpload(req, res, (err) => {
if (err) {