feat(groups): быстрые фильтры и права тьюторов, права на отчёты о занятии

- фильтры групп по филиалу, тьютору и дню, сохранение в localStorage и сброс
- тьютор может редактировать только свои группы; филиал и тьютора меняет админ
- редактирование отчётов о занятии доступно только автору или админу
This commit is contained in:
dev
2026-10-23 10:12:44 +03:00
parent d0a17c5f62
commit 621067a880
8 changed files with 269 additions and 64 deletions
+98 -40
View File
@@ -45,6 +45,8 @@ const {
sweepRestoreTempDirs,
} = require('./lib/restore');
const { normalizeStudentStatus, ensureStudentsTable } = require('./lib/students');
const { lessonReportWriteBlocked } = require('./lib/lesson-reports');
const { groupOwnedBy } = require('./lib/groups');
const https = require('https');
const path = require('path');
@@ -6976,35 +6978,47 @@ app.put('/api/groups/:id', requireAuth, async (req, res) => {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
const isAdmin = req.user.role === 'admin';
if (!isAdmin && branch_id !== undefined) {
return res.status(403).json({ error: 'Назначение филиала — только для администратора' });
}
const tutorProvided = tutor_id !== undefined;
const tutorProvided = isAdmin && tutor_id !== undefined;
let effectiveTutor = null;
if (tutor_id !== undefined && tutor_id !== null && tutor_id !== '') {
if (tutorProvided && tutor_id !== null && tutor_id !== '') {
const t = await pool.query(`SELECT id FROM users WHERE id = $1 AND role = 'tutor'`, [tutor_id]);
if (!t.rows.length) return res.status(400).json({ error: 'Пользователь не найден или не является тутором' });
effectiveTutor = t.rows[0].id;
}
try {
const { rows } = await pool.query(
`UPDATE groups SET
name = COALESCE($1, name),
day_of_week = $2,
time_start = $3,
time_end = $4,
branch_id = $5,
tutor_id = CASE WHEN $6::boolean THEN $7::int ELSE tutor_id END
WHERE id = $8 RETURNING *`,
[name,
day_of_week === undefined || day_of_week === null || day_of_week === '' ? null : day_of_week,
time_start || null, time_end || null,
branch_id === undefined || branch_id === null || branch_id === '' ? null : branch_id,
tutorProvided,
tutorProvided ? effectiveTutor : null,
req.params.id]
);
await logAudit(req, 'group.update', { id: req.params.id, ...req.body });
const { rows } = isAdmin
? await pool.query(
`UPDATE groups SET
name = COALESCE($1, name),
day_of_week = $2,
time_start = $3,
time_end = $4,
branch_id = $5,
tutor_id = CASE WHEN $6::boolean THEN $7::int ELSE tutor_id END
WHERE id = $8 RETURNING *`,
[name,
day_of_week === undefined || day_of_week === null || day_of_week === '' ? null : day_of_week,
time_start || null, time_end || null,
branch_id === undefined || branch_id === null || branch_id === '' ? null : branch_id,
tutorProvided,
tutorProvided ? effectiveTutor : null,
req.params.id]
)
: await pool.query(
`UPDATE groups SET
name = COALESCE($1, name),
day_of_week = $2,
time_start = $3,
time_end = $4
WHERE id = $5 RETURNING *`,
[name,
day_of_week === undefined || day_of_week === null || day_of_week === '' ? null : day_of_week,
time_start || null, time_end || null,
req.params.id]
);
await logAudit(req, 'group.update', isAdmin
? { id: req.params.id, ...req.body }
: { id: req.params.id, name, day_of_week, time_start, time_end });
invalidateGroups();
invalidateStats();
res.json(rows[0]);
@@ -7018,12 +7032,28 @@ app.post('/api/groups', requireAuth, async (req, res) => {
const { name, branch_id, tutor_id } = req.body;
if (!name?.trim()) return res.status(400).json({ error: 'Name required' });
const isAdmin = req.user.role === 'admin';
const effectiveBranch = branch_id === undefined || branch_id === null || branch_id === '' ? null : Number(branch_id);
if (!isAdmin && branch_id !== undefined && branch_id !== null && branch_id !== '') {
return res.status(403).json({ error: 'Назначение филиала — только для администратора' });
const branchProvided = branch_id !== undefined && branch_id !== null && branch_id !== '';
const requestedBranch = branchProvided ? Number(branch_id) : null;
if (branchProvided && (!Number.isInteger(requestedBranch) || requestedBranch <= 0)) {
return res.status(400).json({ error: 'Некорректный филиал' });
}
const ownBranches = (req.user.branch_ids || []).map(Number);
let effectiveBranch = null;
let effectiveTutor = null;
if (tutor_id !== undefined && tutor_id !== null && tutor_id !== '') {
if (isAdmin) {
effectiveBranch = requestedBranch;
} else {
effectiveTutor = req.user.id;
if (requestedBranch !== null) {
if (!ownBranches.includes(requestedBranch)) {
return res.status(403).json({ error: 'Можно выбрать только свой филиал' });
}
effectiveBranch = requestedBranch;
} else {
effectiveBranch = ownBranches.length ? ownBranches[0] : null;
}
}
if (isAdmin && tutor_id !== undefined && tutor_id !== null && tutor_id !== '') {
const t = await pool.query(`SELECT id FROM users WHERE id = $1 AND role = 'tutor'`, [tutor_id]);
if (!t.rows.length) return res.status(400).json({ error: 'Пользователь не найден или не является тутором' });
effectiveTutor = t.rows[0].id;
@@ -7031,9 +7061,9 @@ app.post('/api/groups', requireAuth, async (req, res) => {
try {
const { rows } = await pool.query(
'INSERT INTO groups (name, branch_id, tutor_id) VALUES ($1, $2, $3) RETURNING *',
[name.trim(), isAdmin ? effectiveBranch : null, effectiveTutor]
[name.trim(), effectiveBranch, effectiveTutor]
);
await logAudit(req, 'group.create', { id: rows[0].id, name: name.trim(), branch_id });
await logAudit(req, 'group.create', { id: rows[0].id, name: name.trim(), branch_id: effectiveBranch, tutor_id: effectiveTutor });
invalidateGroups();
invalidateStats();
res.status(201).json(rows[0]);
@@ -7088,8 +7118,13 @@ async function hardDeleteGroup(groupId) {
}
app.delete('/api/groups/:id', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
if (req.user.role !== 'admin') {
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
if (!(await groupOwnedBy(pool, req.user.id, req.params.id))) {
return res.status(403).json({ error: 'Удалять можно только свои группы' });
}
}
const result = await pool.query(
'UPDATE groups SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL',
@@ -7105,8 +7140,13 @@ app.delete('/api/groups/:id', requireAuth, async (req, res) => {
});
app.put('/api/groups/:id/restore', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
if (req.user.role !== 'admin') {
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
if (!(await groupOwnedBy(pool, req.user.id, req.params.id))) {
return res.status(403).json({ error: 'Восстанавливать можно только свои группы' });
}
}
const result = await pool.query(
'UPDATE groups SET deleted_at = NULL, purge_at = NULL WHERE id = $1 AND deleted_at IS NOT NULL',
@@ -7122,8 +7162,13 @@ app.put('/api/groups/:id/restore', requireAuth, async (req, res) => {
});
app.delete('/api/groups/:id/permanent', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
if (req.user.role !== 'admin') {
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
if (!(await groupOwnedBy(pool, req.user.id, req.params.id))) {
return res.status(403).json({ error: 'Удалять навсегда можно только свои группы' });
}
}
const days = await trashPurgeDays();
const result = await pool.query(
@@ -7140,8 +7185,13 @@ app.delete('/api/groups/:id/permanent', requireAuth, async (req, res) => {
});
app.put('/api/groups/:id/unschedule', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
if (req.user.role !== 'admin') {
if (!(await groupBelongsToBranches(req.user, req.params.id))) {
return res.status(403).json({ error: 'Нет доступа к этой группе' });
}
if (!(await groupOwnedBy(pool, req.user.id, req.params.id))) {
return res.status(403).json({ error: 'Управлять корзиной можно только для своих групп' });
}
}
const result = await pool.query(
'UPDATE groups SET purge_at = NULL WHERE id = $1 AND purge_at IS NOT NULL',
@@ -8151,6 +8201,7 @@ app.post('/api/lesson-reports', requireAuth, async (req, res) => {
app.put('/api/lesson-reports/:id', requireAuth, async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
const { group_id, lesson_date, lesson_time, topic, text, ai_check } = req.body || {};
let nextGroup = report.group_id;
let nextBranch = report.branch_id;
@@ -8224,12 +8275,13 @@ app.get('/api/lesson-reports/:id/versions', requireAuth, async (req, res) => {
ORDER BY v.id DESC LIMIT $2`,
[report.id, LESSON_AI_VERSION_LIMIT]
);
res.json({ items: rows, current: report.text });
res.json({ items: rows, current: report.text, author_id: report.author_id });
});
app.post('/api/lesson-reports/:id/versions/:versionId/restore', requireAuth, async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
const vid = Number(req.params.versionId);
if (!Number.isInteger(vid) || vid < 1) return res.status(400).json({ error: 'Некорректный идентификатор версии' });
const { rows: vrows } = await pool.query(
@@ -8262,6 +8314,7 @@ app.post('/api/lesson-reports/:id/versions/:versionId/restore', requireAuth, asy
app.post('/api/lesson-reports/:id/ai/revert', requireAuth, async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
if (!report.text_original) return res.status(400).json({ error: 'Оригинал текста недоступен' });
const { rows } = await pool.query(
`UPDATE lesson_reports SET text = text_original, text_ai = NULL, ai_status = 'reverted',
@@ -8284,9 +8337,10 @@ app.post('/api/lesson-reports/:id/ai/revert', requireAuth, async (req, res) => {
res.json(rows[0]);
});
app.delete('/api/lesson-reports/:id', requireAdmin, async (req, res) => {
app.delete('/api/lesson-reports/:id', requireAuth, async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
await pool.query('DELETE FROM lesson_reports WHERE id = $1', [report.id]);
await logAudit(req, 'lesson_report.delete', { id: report.id, group_id: report.group_id, lesson_date: report.lesson_date });
invalidateLessonReports();
@@ -12480,7 +12534,9 @@ async function trashData(req, mode, limit, offset) {
? (bw.ids.length ? ` AND g.branch_id IN (${bw.ids.map(id => `$${eparams.push(id)}`).join(',')})` : ' AND 1 = 0')
: '';
const gsco = scoped
? (bw.ids.length ? ` AND g.branch_id IN (${bw.ids.map(id => `$${gparams.push(id)}`).join(',')})` : ' AND 1 = 0')
? (bw.ids.length
? ` AND g.branch_id IN (${bw.ids.map(id => `$${gparams.push(id)}`).join(',')}) AND g.tutor_id = $${gparams.push(req.user.id)}`
: ' AND 1 = 0')
: '';
const eOrder = isPending ? 'e.purge_at' : 'e.deleted_at';
const gOrder = isPending ? 'g.purge_at' : 'g.deleted_at';
@@ -13066,6 +13122,7 @@ apiV1.post('/lesson-reports', apiWrite('write'), async (req, res) => {
apiV1.put('/lesson-reports/:id', apiWrite('write'), async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
const curDate = String(report.lesson_date).slice(0, 10);
let date = curDate;
if (req.body?.lesson_date !== undefined && req.body?.lesson_date !== null && req.body?.lesson_date !== '') {
@@ -13116,6 +13173,7 @@ apiV1.put('/lesson-reports/:id', apiWrite('write'), async (req, res) => {
apiV1.delete('/lesson-reports/:id', apiWrite('write'), async (req, res) => {
const { report, error, code } = await lessonReportById(req.user, req.params.id);
if (!report) return res.status(code || 404).json({ error });
if (lessonReportWriteBlocked(res, report, req.user)) return;
await pool.query('DELETE FROM lesson_reports WHERE id = $1', [report.id]);
await apiAudit(req, 'api.lesson_report.delete', { id: report.id });
invalidateLessonReports();