- registerStudentRoutes / registerStudentFaceRoutes / registerStudentApiRoutes забирают все роуты /api/students*, /api/export/student, эталоны и найденные лица ученика, /api/v1/students* из server.js - ensureStudentPhotosTable и createStudentProfileAccess перенесены в lib/students.js - AGENTS.md: задокументированы lib/students.js и lib/student-routes.js в File Map
1475 lines
61 KiB
JavaScript
1475 lines
61 KiB
JavaScript
const path = require('path');
|
|
const crypto = require('crypto');
|
|
const { createZipWriter, renderStudentReport } = require('../student-report');
|
|
const {
|
|
isSafeUploadPath,
|
|
sanitizeStudentProfile,
|
|
reqInt,
|
|
optInt,
|
|
reqStr,
|
|
optDate,
|
|
optUploadPath,
|
|
} = require('../backup-restore');
|
|
const {
|
|
achError,
|
|
achRecordFields,
|
|
achFieldsError,
|
|
listForStudent: achListForStudent,
|
|
createRecord: achCreateRecord,
|
|
updateRecord: achUpdateRecord,
|
|
deleteRecord: achDeleteRecord,
|
|
} = require('./achievements');
|
|
const { studentQuizResults } = require('./quizzes');
|
|
const { findBrokenFaceRefs, deleteFaceRef } = require('./photo-cleanup');
|
|
const { normalizeStudentStatus } = require('./students');
|
|
|
|
function registerStudentRoutes({
|
|
app,
|
|
pool,
|
|
upload,
|
|
apiLimiter,
|
|
requireAuth,
|
|
optionalAuth,
|
|
cacheWrap,
|
|
scopeKey,
|
|
PUBLIC_TTL_MS,
|
|
invalidateStudents,
|
|
invalidateShare,
|
|
invalidateStats,
|
|
branchScope,
|
|
branchWhere,
|
|
groupBelongsToBranches,
|
|
studentProfileAccess,
|
|
getSetting,
|
|
trashPurgeDays,
|
|
appTimezone,
|
|
appHour12,
|
|
tzDayStart,
|
|
tzDayEnd,
|
|
bindTz,
|
|
validTimezone,
|
|
DEFAULT_TIMEZONE,
|
|
convertPhoto,
|
|
removeUpload,
|
|
safeUnlink,
|
|
storage,
|
|
logAudit,
|
|
FACE_CANDIDATE_MIN,
|
|
FILE_TOO_LARGE_ERROR,
|
|
}) {
|
|
const studentPhotoUpload = upload.single('photo');
|
|
|
|
app.get('/api/students', apiLimiter, optionalAuth, async (req, res) => {
|
|
const rows = await cacheWrap('students:list:' + scopeKey(req.user), PUBLIC_TTL_MS, async () => {
|
|
const bw = req.user ? branchWhere(req.user, 'g') : { where: '', params: [] };
|
|
const { rows } = await pool.query(
|
|
`SELECT s.*, g.name AS group_name FROM students s
|
|
LEFT JOIN groups g ON g.id = s.group_id
|
|
WHERE s.deleted_at IS NULL${bw.where} ORDER BY s.name`,
|
|
bw.params
|
|
);
|
|
return rows;
|
|
});
|
|
res.json(rows);
|
|
});
|
|
|
|
app.get('/api/students/names', requireAuth, async (req, res) => {
|
|
const bw = branchWhere(req.user, 'g');
|
|
const { rows } = await pool.query(
|
|
`SELECT DISTINCT e.student_name AS name FROM entries e
|
|
JOIN groups g ON g.id = e.group_id
|
|
WHERE e.student_name IS NOT NULL AND e.student_name <> ''
|
|
AND e.deleted_at IS NULL
|
|
AND g.deleted_at IS NULL
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM students s
|
|
WHERE TRIM(s.name) = TRIM(e.student_name) AND s.deleted_at IS NOT NULL
|
|
)${bw.where}
|
|
ORDER BY name`,
|
|
bw.params
|
|
);
|
|
res.json(rows.map(r => r.name));
|
|
});
|
|
|
|
app.get('/api/students/names-with-groups', requireAuth, async (req, res) => {
|
|
const bw = branchWhere(req.user, 'g');
|
|
const params = bw.params.slice();
|
|
const q = bindTz(
|
|
`SELECT DISTINCT ON (e.student_name) e.student_name AS name, e.group_id, g.name AS group_name,
|
|
to_char(e.created_at AT TIME ZONE $TZ$, 'YYYY-MM-DD') AS last_date
|
|
FROM entries e
|
|
JOIN groups g ON g.id = e.group_id
|
|
WHERE e.student_name IS NOT NULL AND e.student_name <> '' AND e.deleted_at IS NULL${bw.where}
|
|
ORDER BY e.student_name, e.created_at DESC NULLS LAST, e.id DESC`,
|
|
params, await appTimezone()
|
|
);
|
|
const { rows } = await pool.query(q.sql, q.params);
|
|
res.json(rows);
|
|
});
|
|
|
|
app.get('/api/students/works-by-name', requireAuth, async (req, res) => {
|
|
const name = String(req.query.name || '').trim().slice(0, 150);
|
|
if (!name) return res.json({ photos: [] });
|
|
let limit = 3;
|
|
let excludeEntry = null;
|
|
try {
|
|
limit = optInt(req.query.limit, 1, 24) ?? 3;
|
|
excludeEntry = optInt(req.query.exclude_entry, 1, Infinity);
|
|
} catch {
|
|
return res.status(400).json({ error: 'Неверный limit' });
|
|
}
|
|
const bs = branchScope(req.user);
|
|
const params = [name];
|
|
let branch = '';
|
|
if (!bs.admin) {
|
|
if (!bs.ids.length) return res.json({ photos: [] });
|
|
params.push(bs.ids);
|
|
branch = ` AND g.branch_id = ANY($${params.length}::int[])`;
|
|
}
|
|
let excl = '';
|
|
if (excludeEntry) {
|
|
params.push(excludeEntry);
|
|
excl = ` AND e.id <> $${params.length}`;
|
|
}
|
|
params.push(limit);
|
|
const { rows } = await pool.query(
|
|
`SELECT path FROM (
|
|
SELECT e.photo_path AS path, e.created_at AS ca
|
|
FROM entries e JOIN groups g ON g.id = e.group_id
|
|
WHERE e.student_name = $1 AND e.deleted_at IS NULL AND e.photo_path IS NOT NULL${branch}${excl}
|
|
UNION ALL
|
|
SELECT ep.photo_path AS path, e.created_at AS ca
|
|
FROM entries e JOIN groups g ON g.id = e.group_id JOIN entry_photos ep ON ep.entry_id = e.id
|
|
WHERE e.student_name = $1 AND e.deleted_at IS NULL AND ep.photo_path IS NOT NULL${branch}${excl}
|
|
) u
|
|
GROUP BY path
|
|
ORDER BY MAX(ca) DESC NULLS LAST
|
|
LIMIT $${params.length}`,
|
|
params
|
|
);
|
|
res.json({ photos: rows.map(r => r.path) });
|
|
});
|
|
|
|
app.get('/api/students/image-files-by-name', requireAuth, async (req, res) => {
|
|
const name = String(req.query.name || '').trim().slice(0, 150);
|
|
if (!name) return res.json({ files: [] });
|
|
let limit = 3;
|
|
try {
|
|
limit = optInt(req.query.limit, 1, 24) ?? 3;
|
|
} catch {
|
|
return res.status(400).json({ error: 'Неверный limit' });
|
|
}
|
|
const bs = branchScope(req.user);
|
|
const params = [name];
|
|
let branch = '';
|
|
if (!bs.admin) {
|
|
if (!bs.ids.length) return res.json({ files: [] });
|
|
params.push(bs.ids);
|
|
branch = ` AND g.branch_id = ANY($${params.length}::int[])`;
|
|
}
|
|
params.push(limit);
|
|
const { rows } = await pool.query(
|
|
`SELECT pf.token, pf.name
|
|
FROM project_files pf
|
|
JOIN entries e ON e.id = pf.entry_id
|
|
JOIN groups g ON g.id = e.group_id
|
|
WHERE e.student_name = $1 AND e.deleted_at IS NULL AND pf.detached_at IS NULL
|
|
AND lower(pf.name) ~ '\\.(jpe?g|jfif|png|gif|webp|bmp|avif)$'${branch}
|
|
ORDER BY pf.id DESC
|
|
LIMIT $${params.length}`,
|
|
params
|
|
);
|
|
res.json({ files: rows.map(r => ({ token: r.token, name: r.name })) });
|
|
});
|
|
|
|
app.post('/api/students', requireAuth, async (req, res) => {
|
|
const { name, group_id } = req.body;
|
|
if (!name?.trim()) return res.status(400).json({ error: 'Name required' });
|
|
const gid = group_id ? Number(group_id) : null;
|
|
if (req.user.role !== 'admin' && gid && !(await groupBelongsToBranches(req.user, gid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
|
}
|
|
try {
|
|
const { rows } = await pool.query(
|
|
'INSERT INTO students (name, group_id) VALUES ($1, $2) RETURNING *',
|
|
[name.trim(), gid]
|
|
);
|
|
await logAudit(req, 'student.create', { id: rows[0].id, name: name.trim() });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.status(201).json(rows[0]);
|
|
} catch (e) {
|
|
if (e.code === '23505') {
|
|
const { rows: revived } = await pool.query(
|
|
'UPDATE students SET deleted_at = NULL, purge_at = NULL, group_id = $2, status = \'active\' WHERE name = $1 AND deleted_at IS NOT NULL RETURNING *',
|
|
[name.trim(), gid]
|
|
);
|
|
if (revived.length) {
|
|
await logAudit(req, 'student.create', { id: revived[0].id, name: name.trim(), restored: true });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
return res.status(201).json(revived[0]);
|
|
}
|
|
return res.status(409).json({ error: 'Duplicate' });
|
|
}
|
|
throw e;
|
|
}
|
|
});
|
|
|
|
app.put('/api/students/:id', requireAuth, async (req, res) => {
|
|
const { name, group_id, status } = req.body;
|
|
if (!name?.trim()) return res.status(400).json({ error: 'Name required' });
|
|
const nextStatus = normalizeStudentStatus(status);
|
|
if (nextStatus === null) return res.status(400).json({ error: 'Неверный статус ученика' });
|
|
const newGid = group_id === undefined || group_id === null || group_id === '' ? null : Number(group_id);
|
|
if (req.user.role !== 'admin') {
|
|
const { rows: cur } = await pool.query(
|
|
`SELECT s.group_id FROM students s LEFT JOIN groups g ON g.id = s.group_id WHERE s.id = $1 AND s.deleted_at IS NULL`,
|
|
[req.params.id]
|
|
);
|
|
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
|
const curGid = cur[0].group_id;
|
|
if (curGid && !(await groupBelongsToBranches(req.user, curGid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
if (newGid && !(await groupBelongsToBranches(req.user, newGid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
|
}
|
|
}
|
|
try {
|
|
const { rows } = await pool.query(
|
|
`UPDATE students SET
|
|
name = $1,
|
|
group_id = $2,
|
|
status = COALESCE($3::text, status)
|
|
WHERE id = $4 AND deleted_at IS NULL RETURNING *`,
|
|
[name.trim(), newGid, nextStatus || null, req.params.id]
|
|
);
|
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
|
await logAudit(req, 'student.update', { id: req.params.id, name: name.trim(), status: rows[0].status });
|
|
invalidateStudents();
|
|
res.json(rows[0]);
|
|
} catch (e) {
|
|
if (e.code === '23505') return res.status(409).json({ error: 'Duplicate' });
|
|
throw e;
|
|
}
|
|
});
|
|
|
|
app.post('/api/students/batch-group', requireAuth, async (req, res) => {
|
|
const { group_id, student_ids } = req.body;
|
|
if (!group_id || !Array.isArray(student_ids) || !student_ids.length) {
|
|
return res.status(400).json({ error: 'group_id and student_ids required' });
|
|
}
|
|
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, group_id))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
|
}
|
|
const ids = [...new Set(student_ids.map(Number).filter(Boolean))];
|
|
if (!ids.length) return res.status(400).json({ error: 'No valid students' });
|
|
const params = [group_id, ...ids];
|
|
const placeholders = ids.map((_, i) => `$${i + 2}`).join(',');
|
|
const { rows } = await pool.query(
|
|
`UPDATE students SET group_id = $1 WHERE id IN (${placeholders}) AND deleted_at IS NULL RETURNING id`,
|
|
params
|
|
);
|
|
await logAudit(req, 'student.batch-group', { group_id, count: rows.length });
|
|
invalidateStudents();
|
|
res.json({ ok: true, updated: rows.length });
|
|
});
|
|
|
|
app.delete('/api/students/:id', requireAuth, async (req, res) => {
|
|
if (req.user.role !== 'admin') {
|
|
const { rows: cur } = await pool.query(
|
|
'SELECT s.group_id FROM students s WHERE s.id = $1 AND s.deleted_at IS NULL', [req.params.id]
|
|
);
|
|
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
|
const gid = cur[0].group_id;
|
|
if (!(await groupBelongsToBranches(req.user, gid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
}
|
|
const result = await pool.query(
|
|
'UPDATE students SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL', [req.params.id]
|
|
);
|
|
if (result.rowCount === 0) {
|
|
return res.status(404).json({ error: 'Ученик не найден или уже в корзине' });
|
|
}
|
|
await logAudit(req, 'student.soft-delete', { id: req.params.id });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.put('/api/students/:id/restore', requireAuth, async (req, res) => {
|
|
if (req.user.role !== 'admin') {
|
|
const { rows: cur } = await pool.query(
|
|
'SELECT s.group_id FROM students s WHERE s.id = $1 AND s.deleted_at IS NOT NULL', [req.params.id]
|
|
);
|
|
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
|
const gid = cur[0].group_id;
|
|
if (!(await groupBelongsToBranches(req.user, gid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
}
|
|
const result = await pool.query(
|
|
'UPDATE students SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND deleted_at IS NOT NULL', [req.params.id]
|
|
);
|
|
if (result.rowCount === 0) {
|
|
return res.status(404).json({ error: 'Ученик не найден или не в корзине' });
|
|
}
|
|
await logAudit(req, 'student.restore', { id: req.params.id });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.delete('/api/students/:id/permanent', requireAuth, async (req, res) => {
|
|
if (req.user.role !== 'admin') {
|
|
const { rows: cur } = await pool.query(
|
|
'SELECT s.group_id FROM students s WHERE s.id = $1 AND s.deleted_at IS NOT NULL', [req.params.id]
|
|
);
|
|
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
|
const gid = cur[0].group_id;
|
|
if (!(await groupBelongsToBranches(req.user, gid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
}
|
|
const days = await trashPurgeDays();
|
|
const result = await pool.query(
|
|
`UPDATE students SET purge_at = now() + ($2 || ' days')::interval WHERE id = $1 AND deleted_at IS NOT NULL AND purge_at IS NULL`,
|
|
[req.params.id, days]
|
|
);
|
|
if (result.rowCount === 0) {
|
|
return res.status(404).json({ error: 'Ученик не найден, не в корзине или уже помечен на удаление' });
|
|
}
|
|
await logAudit(req, 'student.schedule-delete', { id: req.params.id, days });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.put('/api/students/:id/unschedule', requireAuth, async (req, res) => {
|
|
if (req.user.role !== 'admin') {
|
|
const { rows: cur } = await pool.query(
|
|
'SELECT s.group_id FROM students s WHERE s.id = $1 AND s.purge_at IS NOT NULL', [req.params.id]
|
|
);
|
|
if (!cur.length) return res.status(404).json({ error: 'Not found' });
|
|
const gid = cur[0].group_id;
|
|
if (!(await groupBelongsToBranches(req.user, gid))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
}
|
|
const result = await pool.query(
|
|
'UPDATE students SET purge_at = NULL WHERE id = $1 AND purge_at IS NOT NULL', [req.params.id]
|
|
);
|
|
if (result.rowCount === 0) {
|
|
return res.status(404).json({ error: 'Ученик не найден или не помечен на удаление' });
|
|
}
|
|
await logAudit(req, 'student.unschedule', { id: req.params.id });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.json({ ok: true });
|
|
});
|
|
|
|
app.get('/api/students/:id/profile', 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
res.json({ ...acc.student, profile: acc.student.profile || null });
|
|
});
|
|
|
|
app.put('/api/students/:id/profile', requireAuth, async (req, res) => {
|
|
let id;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
} catch {
|
|
return res.status(400).json({ error: 'Неверный id ученика' });
|
|
}
|
|
let profile;
|
|
let photoPath;
|
|
try {
|
|
profile = sanitizeStudentProfile(req.body?.profile);
|
|
photoPath = req.body?.photo_path === undefined ? undefined : optUploadPath(req.body.photo_path, 255);
|
|
} catch (e) {
|
|
return res.status(400).json({ error: 'Неверные данные профиля: ' + e.message });
|
|
}
|
|
const acc = await studentProfileAccess(req.user, id);
|
|
if (!acc.found) {
|
|
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
const sets = ['profile = $1'];
|
|
const params = [profile ? JSON.stringify(profile) : null];
|
|
if (photoPath !== undefined) {
|
|
params.push(photoPath);
|
|
sets.push(`photo_path = $${params.length}`);
|
|
}
|
|
params.push(id);
|
|
const { rows } = await pool.query(
|
|
`UPDATE students SET ${sets.join(', ')} WHERE id = $${params.length}
|
|
RETURNING id, name, group_id, photo_path, profile`,
|
|
params
|
|
);
|
|
await logAudit(req, 'student.profile.update', { id, name: acc.student.name, blocks: profile ? Object.keys(profile) : [] });
|
|
invalidateStudents();
|
|
res.json(rows[0]);
|
|
});
|
|
|
|
app.get('/api/students/:id/photos', 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
const { rows } = await pool.query(
|
|
'SELECT id, photo_path, created_at FROM student_photos WHERE student_id = $1 ORDER BY id DESC',
|
|
[id]
|
|
);
|
|
res.json({ photos: rows, photo_path: acc.student.photo_path || null });
|
|
});
|
|
|
|
app.get('/api/students/:id/overview', 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
const student = acc.student;
|
|
const name = student.name;
|
|
const LIST_LIMIT = 200;
|
|
try {
|
|
const bs = branchScope(req.user);
|
|
const eConds = ['e.student_name = $1', 'e.deleted_at IS NULL'];
|
|
const eParams = [name];
|
|
if (bs.ids) {
|
|
if (!bs.ids.length) eConds.push('1 = 0');
|
|
else { eParams.push(bs.ids); eConds.push(`g.branch_id = ANY($${eParams.length}::int[])`); }
|
|
}
|
|
const eWhere = eConds.join(' AND ');
|
|
|
|
const fConds = ['f.resident = $1', 'f.deleted_at IS NULL'];
|
|
const fParams = [name];
|
|
if (bs.ids) {
|
|
if (!bs.ids.length) fConds.push('1 = 0');
|
|
else { fParams.push(bs.ids); fConds.push(`f.branch_id = ANY($${fParams.length}::int[])`); }
|
|
}
|
|
const fWhere = fConds.join(' AND ');
|
|
|
|
const [groupRes, entriesTotalRes, entriesRes, fbTotalRes, fbRes, shortsTotalRes, shortsRes, photosRes, facesRes, achList, quizResults] = 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),
|
|
(() => {
|
|
const p = eParams.slice();
|
|
p.push(LIST_LIMIT);
|
|
return pool.query(
|
|
`SELECT e.id, e.description, e.created_at, e.ai_status, e.module_id, e.group_id, e.photo_path, e.photo_original_path,
|
|
g.name AS group_name, m.name AS module_name
|
|
FROM entries e JOIN groups g ON g.id = e.group_id
|
|
LEFT JOIN modules m ON m.id = e.module_id
|
|
WHERE ${eWhere} ORDER BY e.created_at DESC LIMIT $${p.length}`,
|
|
p
|
|
);
|
|
})(),
|
|
pool.query(`SELECT count(*)::int AS n FROM feedbacks f WHERE ${fWhere}`, fParams),
|
|
(() => {
|
|
const p = fParams.slice();
|
|
p.push(LIST_LIMIT);
|
|
return pool.query(
|
|
`SELECT f.id, f.feedback_date, f.topic, f.text, f.ai_status, f.sent_at, f.group_id, f.created_at, f.author_id,
|
|
g.name AS group_name
|
|
FROM feedbacks f LEFT JOIN groups g ON g.id = f.group_id
|
|
WHERE ${fWhere} ORDER BY f.feedback_date DESC NULLS LAST, f.id DESC LIMIT $${p.length}`,
|
|
p
|
|
);
|
|
})(),
|
|
pool.query('SELECT count(*)::int AS n FROM short_messages WHERE resident = $1 AND deleted_at IS NULL', [name]),
|
|
pool.query(
|
|
`SELECT sm.id, sm.resident, sm.lesson_date, sm.topic, sm.message, sm.used, sm.used_at, sm.created_at,
|
|
u.name AS author_name, u.username AS author_username
|
|
FROM short_messages sm LEFT JOIN users u ON u.id = sm.author_id
|
|
WHERE sm.resident = $1 AND sm.deleted_at IS NULL
|
|
ORDER BY sm.lesson_date DESC, sm.id DESC LIMIT $2`,
|
|
[name, LIST_LIMIT]
|
|
),
|
|
pool.query('SELECT id, photo_path, created_at FROM student_photos WHERE student_id = $1 ORDER BY id DESC LIMIT $2', [id, LIST_LIMIT]),
|
|
pool.query(
|
|
`SELECT
|
|
(SELECT count(*)::int FROM student_face_refs WHERE student_id = $1) AS refs,
|
|
(SELECT count(*)::int FROM photo_faces WHERE student_id = $1) AS found,
|
|
(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),
|
|
studentQuizResults(pool, id, req.user).catch(e => {
|
|
console.error('student quizzes:', e);
|
|
return { items: [], total: 0 };
|
|
}),
|
|
]);
|
|
|
|
const entryIds = entriesRes.rows.map(r => r.id);
|
|
if (entryIds.length) {
|
|
const pr = await pool.query(
|
|
'SELECT id, entry_id, photo_path, caption FROM entry_photos WHERE entry_id = ANY($1) ORDER BY sort_order, id',
|
|
[entryIds]
|
|
);
|
|
const byEntry = {};
|
|
pr.rows.forEach(p => { (byEntry[p.entry_id] = byEntry[p.entry_id] || []).push(p); });
|
|
entriesRes.rows.forEach(r => { r.photos = byEntry[r.id] || []; });
|
|
} else {
|
|
entriesRes.rows.forEach(r => { r.photos = []; });
|
|
}
|
|
|
|
const faces = facesRes.rows[0] || {};
|
|
res.json({
|
|
student: { ...student, group_name: groupRes.rows[0]?.name || null, profile: student.profile || null },
|
|
entries: { items: entriesRes.rows, total: entriesTotalRes.rows[0].n },
|
|
feedbacks: { items: fbRes.rows, total: fbTotalRes.rows[0].n },
|
|
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 },
|
|
quizzes: quizResults || { items: [], total: 0 },
|
|
});
|
|
} catch (e) {
|
|
console.error('student overview:', e);
|
|
res.status(500).json({ error: 'Internal error' });
|
|
}
|
|
});
|
|
|
|
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) {
|
|
if (err.code === 'LIMIT_FILE_SIZE') return res.status(400).json({ error: FILE_TOO_LARGE_ERROR });
|
|
if (err.message === 'Only images') return res.status(400).json({ error: 'Фото: допустимы только изображения (jpg, png, gif, webp, bmp, avif, ico, heic, heif, jfif)' });
|
|
if (err.message === 'Not allowed extension') return res.status(400).json({ error: 'Недопустимый тип файла (*.html, *.js, *.svg и т.п. запрещены)' });
|
|
return res.status(400).json({ error: 'Недопустимый файл' });
|
|
}
|
|
next();
|
|
});
|
|
}, async (req, res) => {
|
|
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
|
let id;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
} catch {
|
|
removeUpload(req.file);
|
|
return res.status(400).json({ error: 'Неверный id ученика' });
|
|
}
|
|
const acc = await studentProfileAccess(req.user, id);
|
|
if (!acc.found) {
|
|
removeUpload(req.file);
|
|
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
try {
|
|
await convertPhoto(req.file);
|
|
const photoPath = `/uploads/${req.file.filename}`;
|
|
const { rows } = await pool.query(
|
|
'INSERT INTO student_photos (student_id, photo_path) VALUES ($1, $2) RETURNING id, photo_path, created_at',
|
|
[id, photoPath]
|
|
);
|
|
if (!acc.student.photo_path) {
|
|
await pool.query('UPDATE students SET photo_path = $1 WHERE id = $2', [photoPath, id]);
|
|
}
|
|
await logAudit(req, 'student.photo.create', { id, photo_path: photoPath });
|
|
invalidateStudents();
|
|
invalidateShare();
|
|
res.status(201).json(rows[0]);
|
|
} catch (e) {
|
|
safeUnlink(`uploads/${req.file.filename}`);
|
|
console.error('POST /api/students/:id/photos:', e);
|
|
res.status(500).json({ error: e.message });
|
|
}
|
|
});
|
|
|
|
app.delete('/api/students/:id/photos/:pid', requireAuth, async (req, res) => {
|
|
let id, pid;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
pid = reqInt(req.params.pid);
|
|
} 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
const { rows } = await pool.query(
|
|
'SELECT id, photo_path FROM student_photos WHERE id = $1 AND student_id = $2',
|
|
[pid, id]
|
|
);
|
|
if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' });
|
|
const { rows: rest } = await pool.query(
|
|
'SELECT photo_path FROM student_photos WHERE student_id = $1 AND id <> $2 ORDER BY id DESC LIMIT 1',
|
|
[id, pid]
|
|
);
|
|
try {
|
|
await pool.query('DELETE FROM student_photos WHERE id = $1', [pid]);
|
|
if (acc.student.photo_path === rows[0].photo_path) {
|
|
const next = rest.length ? rest[0].photo_path : null;
|
|
await pool.query('UPDATE students SET photo_path = $1 WHERE id = $2', [next, id]);
|
|
}
|
|
safeUnlink(rows[0].photo_path);
|
|
await logAudit(req, 'student.photo.delete', { id, photo_path: rows[0].photo_path });
|
|
invalidateStudents();
|
|
invalidateShare();
|
|
res.json({ ok: true });
|
|
} catch (e) {
|
|
console.error('DELETE /api/students/:id/photos/:pid:', e);
|
|
res.status(500).json({ error: e.message });
|
|
}
|
|
});
|
|
|
|
app.put('/api/students/:id/photos/:pid/main', requireAuth, async (req, res) => {
|
|
let id, pid;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
pid = reqInt(req.params.pid);
|
|
} 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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
const { rows } = await pool.query(
|
|
'SELECT photo_path FROM student_photos WHERE id = $1 AND student_id = $2',
|
|
[pid, id]
|
|
);
|
|
if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' });
|
|
await pool.query('UPDATE students SET photo_path = $1 WHERE id = $2', [rows[0].photo_path, id]);
|
|
await logAudit(req, 'student.photo.main', { id, photo_path: rows[0].photo_path });
|
|
invalidateStudents();
|
|
invalidateShare();
|
|
res.json({ ok: true, photo_path: rows[0].photo_path });
|
|
});
|
|
|
|
function fmtLongDate(iso, tz) {
|
|
if (!iso) return '';
|
|
return new Date(iso).toLocaleDateString('ru-RU', { day: 'numeric', month: 'long', year: 'numeric', timeZone: validTimezone(tz) ? tz : DEFAULT_TIMEZONE });
|
|
}
|
|
|
|
app.get('/api/export/student', requireAuth, async (req, res) => {
|
|
let name;
|
|
try {
|
|
name = reqStr(req.query.name, 150);
|
|
} catch {
|
|
return res.status(400).json({ error: 'Укажите имя резидента' });
|
|
}
|
|
const LESSON_REPORTS_LIMIT = 60;
|
|
const opts = {
|
|
includeEntries: req.query.include_entries !== '0',
|
|
includePhotos: req.query.include_photos !== '0',
|
|
includeFiles: req.query.include_files !== '0',
|
|
includeCaptions: req.query.include_captions !== '0',
|
|
includeReports: req.query.include_reports !== '0',
|
|
showDates: req.query.show_dates !== '0',
|
|
};
|
|
if (!opts.includeEntries && !opts.includePhotos && !opts.includeFiles) {
|
|
return res.status(400).json({ error: 'Выберите, что включать в отчёт' });
|
|
}
|
|
let dateFrom = null;
|
|
let dateTo = null;
|
|
try {
|
|
if (req.query.date_from) dateFrom = optDate(req.query.date_from);
|
|
if (req.query.date_to) dateTo = optDate(req.query.date_to);
|
|
} catch {
|
|
return res.status(400).json({ error: 'Неверный период' });
|
|
}
|
|
if (dateFrom && dateTo && dateFrom > dateTo) {
|
|
return res.status(400).json({ error: 'Дата «С» позже даты «По»' });
|
|
}
|
|
const hasPeriod = !!(dateFrom || dateTo);
|
|
try {
|
|
const conds = ['e.student_name = $1', 'e.deleted_at IS NULL'];
|
|
const params = [name];
|
|
const bw = branchWhere(req.user, 'g');
|
|
if (dateFrom) {
|
|
params.push(dateFrom);
|
|
conds.push(`e.created_at >= ${tzDayStart(params.length)}`);
|
|
}
|
|
if (dateTo) {
|
|
params.push(dateTo);
|
|
conds.push(`e.created_at < ${tzDayEnd(params.length)}`);
|
|
}
|
|
if (bw.params.length) {
|
|
const start = params.length + 1;
|
|
conds.push(`g.branch_id IN (${bw.params.map((_, i) => '$' + (start + i)).join(',')})`);
|
|
params.push(...bw.params);
|
|
}
|
|
const condStr = bindTz(conds.join(' AND '), params, await appTimezone()).sql;
|
|
const whereStr = ' WHERE ' + condStr;
|
|
const [studRes, entriesRes, photosRes, mainsRes, filesRes, modulesRes, groupPhotosRes] = await Promise.all([
|
|
pool.query(
|
|
`SELECT s.id, s.name, s.created_at, s.group_id, s.photo_path, s.profile,
|
|
g.name AS group_name, b.name AS branch_name
|
|
FROM students s
|
|
LEFT JOIN groups g ON g.id = s.group_id
|
|
LEFT JOIN branches b ON b.id = g.branch_id
|
|
WHERE s.deleted_at IS NULL AND s.name = $1`,
|
|
[name]
|
|
),
|
|
pool.query(`SELECT e.id, e.description, e.created_at, e.module_id, e.ai_status, e.group_id, g.name AS group_name, m.name AS module_name
|
|
FROM entries e JOIN groups g ON g.id = e.group_id
|
|
LEFT JOIN modules m ON m.id = e.module_id${whereStr}
|
|
ORDER BY e.created_at DESC`, params),
|
|
pool.query(`SELECT ep.photo_path, ep.caption, ep.entry_id, e.description, e.created_at, g.name AS group_name
|
|
FROM entry_photos ep
|
|
JOIN entries e ON e.id = ep.entry_id
|
|
JOIN groups g ON g.id = e.group_id${whereStr}
|
|
ORDER BY e.created_at DESC, ep.sort_order ASC, ep.id ASC`, params),
|
|
pool.query(`SELECT e.photo_path, e.description, e.created_at, e.id AS entry_id, g.name AS group_name
|
|
FROM entries e JOIN groups g ON g.id = e.group_id
|
|
WHERE e.photo_path IS NOT NULL AND ${condStr}
|
|
ORDER BY e.created_at DESC`, params),
|
|
pool.query(`SELECT pf.path, pf.name, pf.entry_id, e.created_at, e.description, g.name AS group_name, m.name AS module_name
|
|
FROM project_files pf
|
|
JOIN entries e ON e.id = pf.entry_id
|
|
JOIN groups g ON g.id = e.group_id
|
|
LEFT JOIN modules m ON m.id = e.module_id
|
|
WHERE ${condStr} AND pf.detached_at IS NULL
|
|
ORDER BY e.created_at DESC, pf.id DESC`, params),
|
|
pool.query(`SELECT m.id, m.name, m.lessons_count,
|
|
count(e.id)::int AS entries_count,
|
|
min(e.created_at) AS first_at, max(e.created_at) AS last_at
|
|
FROM entries e
|
|
JOIN groups g ON g.id = e.group_id
|
|
JOIN modules m ON m.id = e.module_id
|
|
WHERE ${condStr}
|
|
GROUP BY m.id ORDER BY min(e.created_at)`, params),
|
|
pool.query(`SELECT gp.photo_path, gp.caption, gp.taken_at, gp.created_at, g.name AS group_name
|
|
FROM group_photos gp
|
|
JOIN groups g ON g.id = gp.group_id
|
|
WHERE gp.group_id = (SELECT group_id FROM students WHERE name = $1 AND deleted_at IS NULL)
|
|
ORDER BY gp.sort_order ASC, gp.created_at DESC`, [name]),
|
|
]);
|
|
const entryRows = entriesRes.rows;
|
|
if (!entryRows.length && !photosRes.rows.length && !filesRes.rows.length) {
|
|
return res.status(404).json({ error: hasPeriod ? 'Нет данных за выбранный период' : 'У резидента нет данных для отчёта' });
|
|
}
|
|
const student = studRes.rows[0] || { name };
|
|
const studentPhotosRes = student.id
|
|
? await pool.query('SELECT photo_path, created_at FROM student_photos WHERE student_id = $1 ORDER BY id DESC', [student.id])
|
|
: { rows: [] };
|
|
const lessonReportsRes = opts.includeReports
|
|
? await (async () => {
|
|
const groupIds = [...new Set([student.group_id, ...entryRows.map(e => e.group_id)].filter(id => Number.isInteger(id)))];
|
|
if (!groupIds.length) return { rows: [], truncated: false };
|
|
const conds = ['lr.group_id = ANY($1::int[])'];
|
|
const rp = [groupIds];
|
|
if (dateFrom) {
|
|
rp.push(dateFrom);
|
|
conds.push(`lr.lesson_date >= $${rp.length}`);
|
|
}
|
|
if (dateTo) {
|
|
rp.push(dateTo);
|
|
conds.push(`lr.lesson_date <= $${rp.length}`);
|
|
}
|
|
if (bw.params.length) {
|
|
const start = rp.length + 1;
|
|
conds.push(`g.branch_id IN (${bw.params.map((_, i) => '$' + (start + i)).join(',')})`);
|
|
rp.push(...bw.params);
|
|
}
|
|
const { rows } = await pool.query(
|
|
`SELECT lr.id, lr.group_id, lr.lesson_date, lr.lesson_time, lr.topic, lr.text, g.name AS group_name
|
|
FROM lesson_reports lr
|
|
JOIN groups g ON g.id = lr.group_id
|
|
WHERE ${conds.join(' AND ')}
|
|
ORDER BY lr.lesson_date DESC, lr.lesson_time DESC NULLS LAST
|
|
LIMIT $${rp.length + 1}`, [...rp, LESSON_REPORTS_LIMIT + 1]);
|
|
return { rows, truncated: rows.length > LESSON_REPORTS_LIMIT };
|
|
})()
|
|
: { rows: [], truncated: false };
|
|
const zip = createZipWriter();
|
|
if (opts.includePhotos) zip.addDir('photos');
|
|
if (opts.includeFiles) zip.addDir('files');
|
|
|
|
let logoFile = null;
|
|
const logoSetting = await getSetting('system_logo', '');
|
|
if (isSafeUploadPath(logoSetting)) {
|
|
const logoKey = logoSetting.slice('/uploads/'.length);
|
|
const logoData = await storage.getBuffer(logoKey);
|
|
if (logoData) {
|
|
const logoExt = (path.extname(logoKey) || '.png').toLowerCase();
|
|
logoFile = 'logo' + (/^\.[a-z0-9]{1,5}$/.test(logoExt) ? logoExt : '.png');
|
|
zip.addFile(logoFile, logoData, new Date());
|
|
}
|
|
}
|
|
|
|
const seenPhotos = new Set();
|
|
const photosBuilt = [];
|
|
async function addPhoto(p) {
|
|
if (!isSafeUploadPath(p.photo_path)) return;
|
|
const stored = p.photo_path.slice('/uploads/'.length);
|
|
if (seenPhotos.has(stored)) return;
|
|
seenPhotos.add(stored);
|
|
const data = await storage.getBuffer(stored);
|
|
if (!data) return;
|
|
const ts = p.created_at ? new Date(p.created_at) : new Date();
|
|
zip.addFile('photos/' + stored, data, ts);
|
|
photosBuilt.push({
|
|
stored,
|
|
caption: p.caption || null,
|
|
createdAt: p.created_at || null,
|
|
desc: p.description || null,
|
|
entryId: p.entry_id || null,
|
|
groupName: p.group_name || null,
|
|
});
|
|
}
|
|
let avatarStored = null;
|
|
if (opts.includePhotos) {
|
|
const profilePhoto = (student.profile && student.profile.photo_path) || student.photo_path;
|
|
if (profilePhoto && isSafeUploadPath(profilePhoto)) {
|
|
const stored = profilePhoto.slice('/uploads/'.length);
|
|
if (await storage.exists(stored)) avatarStored = stored;
|
|
}
|
|
for (const p of photosRes.rows) await addPhoto(p);
|
|
for (const m of mainsRes.rows) await addPhoto(m);
|
|
photosBuilt.sort((a, b) => new Date(b.createdAt || Date.now()) - new Date(a.createdAt || Date.now()));
|
|
}
|
|
|
|
const studentPhotosBuilt = [];
|
|
if (opts.includePhotos) {
|
|
const mainPath = (student.profile && student.profile.photo_path) || student.photo_path || null;
|
|
for (const sp of studentPhotosRes.rows) {
|
|
if (!isSafeUploadPath(sp.photo_path)) continue;
|
|
const stored = sp.photo_path.slice('/uploads/'.length);
|
|
if (studentPhotosBuilt.some(p => p.stored === stored)) continue;
|
|
if (!seenPhotos.has(stored)) {
|
|
const data = await storage.getBuffer(stored);
|
|
if (!data) continue;
|
|
zip.addFile('photos/' + stored, data, sp.created_at ? new Date(sp.created_at) : new Date());
|
|
seenPhotos.add(stored);
|
|
}
|
|
studentPhotosBuilt.push({
|
|
stored,
|
|
createdAt: sp.created_at || null,
|
|
main: sp.photo_path === mainPath,
|
|
});
|
|
}
|
|
if (avatarStored && !studentPhotosBuilt.some(p => p.stored === avatarStored)) {
|
|
if (!seenPhotos.has(avatarStored)) {
|
|
const data = await storage.getBuffer(avatarStored);
|
|
if (data) {
|
|
zip.addFile('photos/' + avatarStored, data, student.created_at ? new Date(student.created_at) : new Date());
|
|
seenPhotos.add(avatarStored);
|
|
}
|
|
}
|
|
studentPhotosBuilt.unshift({ stored: avatarStored, createdAt: student.created_at || null, main: true });
|
|
}
|
|
const mi = studentPhotosBuilt.findIndex(p => p.main);
|
|
if (mi > 0) studentPhotosBuilt.unshift(studentPhotosBuilt.splice(mi, 1)[0]);
|
|
}
|
|
|
|
const groupPhotosBuilt = [];
|
|
if (opts.includePhotos) {
|
|
for (const gp of groupPhotosRes.rows) {
|
|
if (!isSafeUploadPath(gp.photo_path)) continue;
|
|
const stored = gp.photo_path.slice('/uploads/'.length);
|
|
if (seenPhotos.has(stored)) continue;
|
|
const data = await storage.getBuffer(stored);
|
|
if (!data) continue;
|
|
const ts = gp.taken_at || gp.created_at || new Date();
|
|
zip.addFile('photos/' + stored, data, new Date(ts));
|
|
seenPhotos.add(stored);
|
|
groupPhotosBuilt.push({
|
|
stored,
|
|
caption: gp.caption || null,
|
|
takenAt: gp.taken_at || null,
|
|
createdAt: gp.created_at || null,
|
|
groupName: gp.group_name || null,
|
|
});
|
|
}
|
|
}
|
|
|
|
const seenFiles = new Map();
|
|
const filesBuilt = [];
|
|
if (opts.includeFiles) {
|
|
for (const f of filesRes.rows) {
|
|
if (!isSafeUploadPath(f.path)) continue;
|
|
const stored = f.path.slice('/uploads/'.length);
|
|
const data = await storage.getBuffer(stored);
|
|
if (!data) continue;
|
|
let base = String(f.name || 'file').replace(/[\\/:*?"<>|]/g, '_').replace(/^[.\s]+/, '').slice(0, 120) || 'file';
|
|
const ext = path.extname(base);
|
|
const stem = ext ? base.slice(0, -ext.length) : base;
|
|
let saved = base;
|
|
let n = 1;
|
|
while (seenFiles.has(saved)) {
|
|
n++;
|
|
saved = `${stem}(${n})${ext}`;
|
|
}
|
|
seenFiles.set(saved, true);
|
|
zip.addFile('files/' + saved, data, new Date(f.created_at));
|
|
filesBuilt.push({
|
|
saved,
|
|
original: f.name,
|
|
ext: ext ? ext.slice(1).toUpperCase() : '',
|
|
size: data.length,
|
|
createdAt: f.created_at,
|
|
entryId: f.entry_id,
|
|
desc: f.description || null,
|
|
moduleName: f.module_name || null,
|
|
groupName: f.group_name || null,
|
|
});
|
|
}
|
|
}
|
|
|
|
let period = null;
|
|
if (hasPeriod) {
|
|
const exportTz = await appTimezone();
|
|
period = `Период: ${dateFrom ? fmtLongDate(dateFrom + 'T00:00:00', exportTz) : 'начало'} — ${dateTo ? fmtLongDate(dateTo + 'T00:00:00', exportTz) : 'сегодня'}`;
|
|
}
|
|
|
|
const reportData = {
|
|
name,
|
|
student: {
|
|
id: student.id || null,
|
|
name: student.name || name,
|
|
created_at: student.created_at || null,
|
|
group_name: student.group_name || null,
|
|
branch_name: student.branch_name || null,
|
|
},
|
|
profile: student.profile || null,
|
|
entries: entryRows,
|
|
modules: modulesRes.rows,
|
|
photos: photosBuilt,
|
|
groupPhotos: groupPhotosBuilt,
|
|
studentPhotos: studentPhotosBuilt,
|
|
files: filesBuilt,
|
|
lessonReports: opts.includeReports ? lessonReportsRes.rows.slice(0, LESSON_REPORTS_LIMIT) : [],
|
|
lessonReportsTruncated: opts.includeReports && lessonReportsRes.truncated,
|
|
hour12: await appHour12(),
|
|
generatedAt: new Date(),
|
|
period,
|
|
logo: logoFile,
|
|
};
|
|
const html = renderStudentReport(reportData, opts);
|
|
zip.addFile('index.html', Buffer.from(html, 'utf8'));
|
|
const meta = {
|
|
exported_at: new Date().toISOString(),
|
|
student: reportData.student,
|
|
profile: student.profile || null,
|
|
period: period || null,
|
|
totals: { entries: entryRows.length, modules: modulesRes.rows.length, photos: photosBuilt.length, files: filesBuilt.length, groupPhotos: groupPhotosBuilt.length, studentPhotos: studentPhotosBuilt.length, lessonReports: reportData.lessonReports.length },
|
|
options: opts,
|
|
entries: entryRows.map(e => ({ id: e.id, group: e.group_name, module: e.module_name || null, created_at: e.created_at, ai_status: e.ai_status, description: e.description })),
|
|
photos: photosBuilt.map(p => ({ file: 'photos/' + p.stored, caption: p.caption, created_at: p.createdAt, entry_id: p.entryId })),
|
|
student_photos: studentPhotosBuilt.map(p => ({ file: 'photos/' + p.stored, main: !!p.main, created_at: p.createdAt })),
|
|
files: filesBuilt.map(f => ({ file: 'files/' + f.saved, name: f.original, size: f.size, created_at: f.createdAt, entry_id: f.entryId })),
|
|
lesson_reports: reportData.lessonReports.map(r => ({ id: r.id, group_id: r.group_id, group_name: r.group_name, lesson_date: r.lesson_date, lesson_time: r.lesson_time, topic: r.topic || null, text: r.text })),
|
|
};
|
|
zip.addFile('data.json', Buffer.from(JSON.stringify(meta, null, 2), 'utf8'));
|
|
|
|
const buf = zip.toBuffer();
|
|
await logAudit(req, 'export.student', {
|
|
student: name,
|
|
entries: entryRows.length,
|
|
photos: photosBuilt.length,
|
|
files: filesBuilt.length,
|
|
lesson_reports: reportData.lessonReports.length,
|
|
opts,
|
|
date_from: dateFrom,
|
|
date_to: dateTo,
|
|
});
|
|
const safeName = name.replace(/[^a-zA-Z0-9._-]+/g, '_').slice(0, 80) || 'student';
|
|
const zipDate = new Date().toISOString().slice(0, 10);
|
|
const zipFname = `student_${safeName}_${zipDate}.zip`;
|
|
res.setHeader('Content-Type', 'application/zip');
|
|
res.setHeader('Content-Disposition', `attachment; filename="${zipFname}"; filename*=UTF-8''${encodeURIComponent(`student_${name}_${zipDate}.zip`)}`);
|
|
res.send(buf);
|
|
} catch (err) {
|
|
console.error('export student:', err);
|
|
res.status(500).json({ error: err.message });
|
|
}
|
|
});
|
|
}
|
|
|
|
function registerStudentFaceRoutes({
|
|
app,
|
|
pool,
|
|
upload,
|
|
requireAuth,
|
|
requireAdmin,
|
|
storage,
|
|
convertPhoto,
|
|
removeUpload,
|
|
safeUnlink,
|
|
logAudit,
|
|
studentProfileAccess,
|
|
faceIdConfigured,
|
|
faceIdDetect,
|
|
rematchFacesBackground,
|
|
apiBranchClause,
|
|
safeId,
|
|
FACE_CANDIDATE_MIN,
|
|
}) {
|
|
const studentPhotoUpload = upload.single('photo');
|
|
|
|
app.post('/api/students/:id/face-refs', requireAuth, (req, res, next) => {
|
|
studentPhotoUpload(req, res, (err) => {
|
|
if (err) return res.status(400).json({ error: 'Недопустимый файл' });
|
|
next();
|
|
});
|
|
}, async (req, res) => {
|
|
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
|
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
|
let id;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
} catch {
|
|
removeUpload(req.file);
|
|
return res.status(400).json({ error: 'Неверный id ученика' });
|
|
}
|
|
const acc = await studentProfileAccess(req.user, id);
|
|
if (!acc.found) {
|
|
removeUpload(req.file);
|
|
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
}
|
|
try {
|
|
await convertPhoto(req.file);
|
|
const detected = await faceIdDetect(req.file.filename, null);
|
|
if (!detected) {
|
|
removeUpload(req.file);
|
|
return res.status(503).json({ error: 'Face-ID сервис недоступен' });
|
|
}
|
|
const faces = detected.faces;
|
|
if (!faces.length) {
|
|
removeUpload(req.file);
|
|
return res.status(400).json({ error: 'Лицо не найдено на фото. Загрузите фото анфас' });
|
|
}
|
|
const best = faces.reduce((a, b) => ((b.det_score || 0) > (a.det_score || 0) ? b : a));
|
|
const photoPath = `/uploads/${req.file.filename}`;
|
|
const { rows } = await pool.query(
|
|
`INSERT INTO student_face_refs (student_id, photo_path, embedding, det_score) VALUES ($1, $2, $3, $4) RETURNING id, student_id, photo_path, det_score, created_at`,
|
|
[id, photoPath, JSON.stringify(best.embedding), Number(best.det_score) || 0]
|
|
);
|
|
await logAudit(req, 'student.face_ref.create', { student_id: id, ref_id: rows[0].id });
|
|
res.status(201).json(rows[0]);
|
|
rematchFacesBackground();
|
|
} catch (e) {
|
|
safeUnlink(`uploads/${req.file.filename}`);
|
|
console.error('POST /api/students/:id/face-refs:', e);
|
|
res.status(500).json({ error: e.message });
|
|
}
|
|
});
|
|
|
|
app.post('/api/students/:id/face-refs/from-profile', requireAuth, async (req, res) => {
|
|
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
|
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 ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
|
const srcKeys = [];
|
|
const seenKeys = new Set();
|
|
const addKey = (p) => {
|
|
if (typeof p !== 'string' || !p.startsWith('/uploads/')) return;
|
|
const key = storage.keyFromPath(p);
|
|
if (key && !seenKeys.has(key)) {
|
|
seenKeys.add(key);
|
|
srcKeys.push(key);
|
|
}
|
|
};
|
|
addKey(acc.student.photo_path);
|
|
const { rows: photoRows } = await pool.query('SELECT photo_path FROM student_photos WHERE student_id = $1 ORDER BY id DESC', [id]);
|
|
for (const r of photoRows) addKey(r.photo_path);
|
|
if (!srcKeys.length) return res.status(400).json({ error: 'У ученика нет фото профиля' });
|
|
const created = [];
|
|
let skipped = 0;
|
|
try {
|
|
for (const srcKey of srcKeys) {
|
|
const copyName = `${crypto.randomBytes(12).toString('hex')}${path.extname(srcKey) || '.jpg'}`;
|
|
if (!(await storage.copyObject(srcKey, copyName))) {
|
|
skipped++;
|
|
continue;
|
|
}
|
|
const detected = await faceIdDetect(copyName, null);
|
|
if (!detected) {
|
|
safeUnlink(`uploads/${copyName}`);
|
|
return res.status(503).json({ error: 'Face-ID сервис недоступен' });
|
|
}
|
|
const faces = detected.faces;
|
|
if (!faces.length) {
|
|
safeUnlink(`uploads/${copyName}`);
|
|
skipped++;
|
|
continue;
|
|
}
|
|
const best = faces.reduce((a, b) => ((b.det_score || 0) > (a.det_score || 0) ? b : a));
|
|
const { rows } = await pool.query(
|
|
`INSERT INTO student_face_refs (student_id, photo_path, embedding, det_score) VALUES ($1, $2, $3, $4) RETURNING id, student_id, photo_path, det_score, created_at`,
|
|
[id, `/uploads/${copyName}`, JSON.stringify(best.embedding), Number(best.det_score) || 0]
|
|
);
|
|
await logAudit(req, 'student.face_ref.create', { student_id: id, ref_id: rows[0].id, source: 'profile' });
|
|
created.push(rows[0]);
|
|
}
|
|
} catch (e) {
|
|
console.error('POST /api/students/:id/face-refs/from-profile:', e);
|
|
return res.status(500).json({ error: e.message });
|
|
}
|
|
if (!created.length) return res.status(400).json({ error: 'Лицо не найдено ни на одном фото профиля. Загрузите фото анфас' });
|
|
res.status(201).json({ refs: created, added: created.length, skipped });
|
|
rematchFacesBackground();
|
|
});
|
|
|
|
app.get('/api/students/:id/face-refs', 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: 'Ученик не найден' });
|
|
const { rows } = await pool.query(
|
|
'SELECT id, student_id, photo_path, det_score, created_at FROM student_face_refs WHERE student_id = $1 ORDER BY id',
|
|
[id]
|
|
);
|
|
res.json({ refs: rows });
|
|
});
|
|
|
|
app.delete('/api/students/:id/face-refs/:refId', requireAuth, async (req, res) => {
|
|
let id, refId;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
refId = reqInt(req.params.refId);
|
|
} 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: 'Ученик не найден' });
|
|
const { rows } = await pool.query('SELECT photo_path FROM student_face_refs WHERE id = $1 AND student_id = $2', [refId, id]);
|
|
if (!rows.length) return res.status(404).json({ error: 'Референс не найден' });
|
|
await pool.query('DELETE FROM student_face_refs WHERE id = $1 AND student_id = $2', [refId, id]);
|
|
safeUnlink(rows[0].photo_path.replace(/^\/?uploads\//, 'uploads/'));
|
|
await logAudit(req, 'student.face_ref.delete', { student_id: id, ref_id: refId });
|
|
res.json({ ok: true });
|
|
rematchFacesBackground();
|
|
});
|
|
|
|
app.get('/api/students/:id/face-photos', 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: 'Ученик не найден' });
|
|
const params = [];
|
|
const gscope = apiBranchClause(req.user, 'g.branch_id', params);
|
|
params.push(id);
|
|
const { rows } = await pool.query(
|
|
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
|
|
gp.group_id, e.id AS entry_ref, g.name AS group_name,
|
|
COALESCE(gp.created_at, ep.created_at) AS created_at, pf.confidence,
|
|
COALESCE(gp.photo_original_path, CASE WHEN e.photo_path = pf.photo_path THEN e.photo_original_path END) AS photo_original_path
|
|
FROM photo_faces pf
|
|
LEFT JOIN group_photos gp ON gp.id = pf.source_id AND pf.source_type = 'group'
|
|
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.source_type = 'entry'
|
|
LEFT JOIN entries e ON e.id = ep.entry_id
|
|
LEFT JOIN groups g ON g.id = COALESCE(gp.group_id, e.group_id)
|
|
WHERE pf.student_id = $${params.length}${gscope}
|
|
ORDER BY pf.source_type, pf.source_id, COALESCE(gp.created_at, ep.created_at) DESC`,
|
|
params
|
|
);
|
|
const sparams = [];
|
|
const sscope = apiBranchClause(req.user, 'g.branch_id', sparams);
|
|
sparams.push(id);
|
|
const { rows: srows } = await pool.query(
|
|
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.id AS face_id, pf.source_type, pf.source_id, pf.photo_path,
|
|
gp.group_id, e.id AS entry_ref, g.name AS group_name,
|
|
COALESCE(gp.created_at, ep.created_at) AS created_at, pf.best_score,
|
|
COALESCE(gp.photo_original_path, CASE WHEN e.photo_path = pf.photo_path THEN e.photo_original_path END) AS photo_original_path
|
|
FROM photo_faces pf
|
|
LEFT JOIN group_photos gp ON gp.id = pf.source_id AND pf.source_type = 'group'
|
|
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.source_type = 'entry'
|
|
LEFT JOIN entries e ON e.id = ep.entry_id
|
|
LEFT JOIN groups g ON g.id = COALESCE(gp.group_id, e.group_id)
|
|
WHERE pf.student_id IS NULL AND pf.best_student_id = $${sparams.length}
|
|
AND pf.best_score >= $${sparams.length + 1}${sscope}
|
|
ORDER BY pf.source_type, pf.source_id, pf.best_score DESC`,
|
|
sparams.concat([FACE_CANDIDATE_MIN])
|
|
);
|
|
res.json({
|
|
photos: rows.map(r => ({
|
|
source_type: r.source_type,
|
|
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
|
|
photo_id: r.source_id,
|
|
path: r.photo_path,
|
|
group_name: r.group_name,
|
|
created_at: r.created_at,
|
|
confidence: r.confidence,
|
|
manual: Number(r.confidence) >= 1,
|
|
photo_original_path: r.photo_original_path || null,
|
|
})),
|
|
similar: srows.map(r => ({
|
|
face_id: r.face_id,
|
|
source_type: r.source_type,
|
|
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
|
|
photo_id: r.source_id,
|
|
path: r.photo_path,
|
|
group_name: r.group_name,
|
|
created_at: r.created_at,
|
|
score: Number(r.best_score) || 0,
|
|
photo_original_path: r.photo_original_path || null,
|
|
})),
|
|
total: rows.length,
|
|
similar_total: srows.length,
|
|
});
|
|
});
|
|
|
|
app.get('/api/students/:id/faces/broken', 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: 'Ученик не найден' });
|
|
}
|
|
const limit = Math.min(1000, Math.max(1, safeId(req.query.limit) || 200));
|
|
const broken = await findBrokenFaceRefs(pool, storage, { studentId: id, limit });
|
|
res.json({ broken, total: broken.length });
|
|
});
|
|
|
|
app.delete('/api/students/:id/face-refs/:refId/broken', requireAuth, requireAdmin, async (req, res) => {
|
|
let id, refId;
|
|
try {
|
|
id = reqInt(req.params.id);
|
|
refId = reqInt(req.params.refId);
|
|
} 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: 'Ученик не найден' });
|
|
}
|
|
const deleted = await deleteFaceRef(pool, storage, { table: 'student_face_refs', id: refId });
|
|
if (!deleted) {
|
|
return res.status(404).json({ error: 'Эталон лица не найден' });
|
|
}
|
|
await logAudit(req, 'face_ref.delete_broken', { student_id: id, ref_id: refId, photo_path: deleted.photo_path });
|
|
res.json({ ok: true, deleted: { id: deleted.id, photo_path: deleted.photo_path } });
|
|
});
|
|
}
|
|
|
|
function registerStudentApiRoutes({
|
|
apiV1,
|
|
pool,
|
|
apiPage,
|
|
apiList,
|
|
apiWrite,
|
|
apiAudit,
|
|
branchWhere,
|
|
groupBelongsToBranches,
|
|
invalidateStudents,
|
|
invalidateStats,
|
|
lessonReportGroup,
|
|
}) {
|
|
|
|
apiV1.get('/students', async (req, res) => {
|
|
const { limit, offset } = apiPage(req);
|
|
const bw = branchWhere(req.user, 'g');
|
|
const params = bw.params.slice();
|
|
const search = String(req.query.search || '').trim();
|
|
if (search) params.push(`%${search}%`);
|
|
const extra = search ? ` AND s.name ILIKE $${params.length}` : '';
|
|
const { rows: crows } = await pool.query(
|
|
`SELECT count(*)::int AS n FROM students s
|
|
LEFT JOIN groups g ON g.id = s.group_id
|
|
WHERE s.deleted_at IS NULL${extra}${bw.where}`,
|
|
params
|
|
);
|
|
const total = crows[0].n;
|
|
const q = `SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.status, s.created_at
|
|
FROM students s
|
|
LEFT JOIN groups g ON g.id = s.group_id
|
|
WHERE s.deleted_at IS NULL${extra}${bw.where}
|
|
ORDER BY s.name
|
|
LIMIT $${params.push(limit)} OFFSET $${params.push(offset)}`;
|
|
const { rows } = await pool.query(q, params);
|
|
res.json(apiList(rows, total, limit, offset));
|
|
});
|
|
|
|
apiV1.get('/students/:id', async (req, res) => {
|
|
const { rows } = await pool.query(
|
|
`SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.profile, s.status, s.created_at
|
|
FROM students s
|
|
LEFT JOIN groups g ON g.id = s.group_id
|
|
WHERE s.deleted_at IS NULL AND s.id = $1`,
|
|
[req.params.id]
|
|
);
|
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
|
if (req.user.role !== 'admin' && rows[0].group_id) {
|
|
if (!(await groupBelongsToBranches(req.user, rows[0].group_id))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
}
|
|
res.json(rows[0]);
|
|
});
|
|
|
|
apiV1.post('/students', apiWrite('write'), async (req, res) => {
|
|
const name = reqStr(req.body?.name, 150);
|
|
let gid = null;
|
|
if (req.body?.group_id !== undefined && req.body?.group_id !== null && req.body?.group_id !== '') {
|
|
const grp = await lessonReportGroup(req.user, req.body.group_id);
|
|
if (grp.error) return res.status(grp.code || 400).json({ error: grp.error });
|
|
gid = grp.group.id;
|
|
}
|
|
const { rows } = await pool.query('INSERT INTO students (name, group_id) VALUES ($1, $2) RETURNING *', [name, gid]);
|
|
await apiAudit(req, 'api.student.create', { id: rows[0].id, name });
|
|
invalidateStudents();
|
|
invalidateStats();
|
|
res.status(201).json(rows[0]);
|
|
});
|
|
|
|
apiV1.put('/students/:id', apiWrite('write'), async (req, res) => {
|
|
const name = reqStr(req.body?.name, 150);
|
|
const nextStatus = normalizeStudentStatus(req.body?.status);
|
|
if (nextStatus === null) return res.status(400).json({ error: 'Неверный статус ученика' });
|
|
const cur = await pool.query('SELECT id, group_id FROM students WHERE id = $1 AND deleted_at IS NULL', [req.params.id]);
|
|
if (!cur.rows.length) return res.status(404).json({ error: 'Not found' });
|
|
if (req.user.role !== 'admin' && cur.rows[0].group_id && !(await groupBelongsToBranches(req.user, cur.rows[0].group_id))) {
|
|
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
|
}
|
|
let gid = null;
|
|
if (req.body?.group_id !== undefined && req.body?.group_id !== null && req.body?.group_id !== '') {
|
|
const grp = await lessonReportGroup(req.user, req.body.group_id);
|
|
if (grp.error) return res.status(grp.code || 400).json({ error: grp.error });
|
|
gid = grp.group.id;
|
|
}
|
|
const { rows } = await pool.query('UPDATE students SET name = $1, group_id = $2, status = COALESCE($3::text, status) WHERE id = $4 AND deleted_at IS NULL RETURNING *', [name, gid, nextStatus || null, req.params.id]);
|
|
if (!rows.length) return res.status(404).json({ error: 'Not found' });
|
|
await apiAudit(req, 'api.student.update', { id: rows[0].id, name, status: rows[0].status });
|
|
invalidateStudents();
|
|
res.json(rows[0]);
|
|
});
|
|
}
|
|
|
|
module.exports = { registerStudentRoutes, registerStudentFaceRoutes, registerStudentApiRoutes };
|