Add soft-delete for students: deleted_at/purge_at columns, trash page, API filters and audit logs

This commit is contained in:
dev
2026-10-08 18:21:46 +03:00
parent 2b60a69bd4
commit f07f15cdb0
7 changed files with 254 additions and 33 deletions
+2
View File
@@ -301,6 +301,8 @@ function normalizeRestoreData(data) {
group_id: optInt(x.group_id, 0, 2147483647), group_id: optInt(x.group_id, 0, 2147483647),
photo_path: optUploadPath(x.photo_path, 255), photo_path: optUploadPath(x.photo_path, 255),
profile: sanitizeStudentProfile(x.profile), profile: sanitizeStudentProfile(x.profile),
deleted_at: optTs(x.deleted_at),
purge_at: optTs(x.purge_at),
})); }));
const entries = (data.entries || []).map(x => ({ const entries = (data.entries || []).map(x => ({
id: reqInt(x.id), id: reqInt(x.id),
+2
View File
@@ -46,6 +46,8 @@ CREATE TABLE IF NOT EXISTS students (
name VARCHAR(150) NOT NULL UNIQUE, name VARCHAR(150) NOT NULL UNIQUE,
group_id INT REFERENCES groups(id), group_id INT REFERENCES groups(id),
created_at TIMESTAMPTZ DEFAULT now(), created_at TIMESTAMPTZ DEFAULT now(),
deleted_at TIMESTAMPTZ,
purge_at TIMESTAMPTZ,
photo_path VARCHAR(255), photo_path VARCHAR(255),
profile JSONB profile JSONB
); );
+2
View File
@@ -12,6 +12,8 @@ CREATE TABLE IF NOT EXISTS banned_ips (
); );
ALTER TABLE students ADD COLUMN IF NOT EXISTS group_id INT REFERENCES groups(id); ALTER TABLE students ADD COLUMN IF NOT EXISTS group_id INT REFERENCES groups(id);
ALTER TABLE students ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ;
ALTER TABLE students ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ;
ALTER TABLE students ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255); ALTER TABLE students ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255);
ALTER TABLE students ADD COLUMN IF NOT EXISTS profile JSONB; ALTER TABLE students ADD COLUMN IF NOT EXISTS profile JSONB;
+100 -6
View File
@@ -1,13 +1,17 @@
const PAGE_SIZE = 20; const PAGE_SIZE = 20;
let currentEntries = []; let currentEntries = [];
let currentGroups = []; let currentGroups = [];
let currentStudents = [];
let pendingEntries = []; let pendingEntries = [];
let pendingGroups = []; let pendingGroups = [];
let pendingStudents = [];
let page = 1; let page = 1;
let totalEntries = 0; let totalEntries = 0;
let totalGroups = 0; let totalGroups = 0;
let totalStudents = 0;
let pendingTotalEntries = 0; let pendingTotalEntries = 0;
let pendingTotalGroups = 0; let pendingTotalGroups = 0;
let pendingTotalStudents = 0;
let purgeDays = 30; let purgeDays = 30;
function isImageFile(name) { function isImageFile(name) {
@@ -85,6 +89,35 @@ function pendingGroupHTML(g) {
`; `;
} }
function studentHTML(s) {
return `\
<div class="card">
${s.photo_path ? `<img src="${thumbSrc(s.photo_path)}" data-img="${API}${s.photo_path}" loading="lazy" decoding="async" alt="">` : ''}
<div class="info">
<div class="name">${esc(s.name)}</div>
${s.group_name ? `<div class="group">${esc(s.group_name)}</div>` : ''}
<div class="trash-time">Удалена: ${fmtFull(s.deleted_at)}</div>
</div>
<button class="restore-btn" data-restore="${s.id}" title="Восстановить">Восстановить</button>
<button class="del-btn" data-hard="${s.id}" title="Пометить на удаление (через ${purgeDays} дней будет удалена безвозвратно)">&times;</button>
</div>
`;
}
function pendingStudentHTML(s) {
return `\
<div class="card pending">
${s.photo_path ? `<img src="${thumbSrc(s.photo_path)}" data-img="${API}${s.photo_path}" loading="lazy" decoding="async" alt="">` : ''}
<div class="info">
<div class="name">${esc(s.name)}</div>
${s.group_name ? `<div class="group">${esc(s.group_name)}</div>` : ''}
<div class="trash-time warn">Удаление через ${purgeDays} дн.: ${fmtFull(s.purge_at)}</div>
</div>
<button class="restore-btn" data-unschedule="${s.id}" title="Вернуть в корзину">В корзину</button>
</div>
`;
}
function renderGroups() { function renderGroups() {
const grid = document.getElementById('groupsGrid'); const grid = document.getElementById('groupsGrid');
grid.className = 'grid'; grid.className = 'grid';
@@ -94,6 +127,16 @@ function renderGroups() {
document.getElementById('groupsInfo').textContent = document.getElementById('groupsInfo').textContent =
totalGroups > 0 ? `— групп в корзине: ${totalGroups}` : ''; totalGroups > 0 ? `— групп в корзине: ${totalGroups}` : '';
} }
function renderStudents() {
const grid = document.getElementById('studentsGrid');
grid.className = 'grid';
grid.innerHTML = currentStudents.length
? currentStudents.map(studentHTML).join('')
: '<div class="empty">Учеников в корзине нет</div>';
document.getElementById('studentsInfo').textContent =
totalStudents > 0 ? `— учеников в корзине: ${totalStudents}` : '';
}
function renderGrid() { function renderGrid() {
const grid = document.getElementById('grid'); const grid = document.getElementById('grid');
@@ -104,10 +147,10 @@ function renderGrid() {
document.getElementById('entriesInfo').textContent = document.getElementById('entriesInfo').textContent =
totalEntries > 0 ? `— записей в корзине: ${totalEntries}` : ''; totalEntries > 0 ? `— записей в корзине: ${totalEntries}` : '';
document.getElementById('trashInfo').textContent = document.getElementById('trashInfo').textContent =
totalEntries + totalGroups > 0 totalEntries + totalGroups + totalStudents > 0
? `В корзине: записей ${totalEntries}, групп ${totalGroups}` ? `В корзине: записей ${totalEntries}, групп ${totalGroups}, учеников ${totalStudents}`
: 'Корзина пуста'; : 'Корзина пуста';
document.getElementById('emptyBtn').disabled = totalEntries + totalGroups === 0; document.getElementById('emptyBtn').disabled = totalEntries + totalGroups + totalStudents === 0;
renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalEntries / PAGE_SIZE)), goPage); renderPager(document.getElementById('pager'), page, Math.max(1, Math.ceil(totalEntries / PAGE_SIZE)), goPage);
} }
@@ -122,15 +165,21 @@ function renderPending() {
: '<div class="empty">Нет записей, помеченных на удаление</div>'; : '<div class="empty">Нет записей, помеченных на удаление</div>';
document.getElementById('pendingGroupsInfo').textContent = document.getElementById('pendingGroupsInfo').textContent =
pendingTotalGroups > 0 ? `— ${pendingTotalGroups}` : ''; pendingTotalGroups > 0 ? `— ${pendingTotalGroups}` : '';
document.getElementById('pendingStudentsGrid').className = 'grid';
document.getElementById('pendingStudentsGrid').innerHTML = pendingStudents.length
? pendingStudents.map(pendingStudentHTML).join('')
: '<div class="empty">Нет учеников, помеченных на удаление</div>';
document.getElementById('pendingStudentsInfo').textContent =
pendingTotalStudents > 0 ? `— ${pendingTotalStudents}` : '';
document.getElementById('pendingEntriesInfo').textContent = document.getElementById('pendingEntriesInfo').textContent =
pendingTotalEntries > 0 ? `— ${pendingTotalEntries}` : ''; pendingTotalEntries > 0 ? `— ${pendingTotalEntries}` : '';
const n = pendingTotalEntries + pendingTotalGroups; const n = pendingTotalEntries + pendingTotalGroups + pendingTotalStudents;
document.getElementById('pendingInfo').textContent = document.getElementById('pendingInfo').textContent =
n > 0 ? `— будет удалено: ${n}` : ''; n > 0 ? `— будет удалено: ${n}` : '';
const hint = document.getElementById('pendingToggleHint'); const hint = document.getElementById('pendingToggleHint');
if (hint) { if (hint) {
hint.textContent = n > 0 hint.textContent = n > 0
? `Помечено: записей ${pendingTotalEntries}, групп ${pendingTotalGroups} — безвозвратно удалятся через ${purgeDays} дней` ? `Помечено: записей ${pendingTotalEntries}, групп ${pendingTotalGroups}, учеников ${pendingTotalStudents} — безвозвратно удалятся через ${purgeDays} дней`
: 'Данных, помеченных на удаление, нет'; : 'Данных, помеченных на удаление, нет';
} }
document.getElementById('pendingSection').hidden = !document.getElementById('pendingToggle').checked; document.getElementById('pendingSection').hidden = !document.getElementById('pendingToggle').checked;
@@ -150,12 +199,17 @@ async function loadTrash() {
totalEntries = data.total; totalEntries = data.total;
currentGroups = data.groups; currentGroups = data.groups;
totalGroups = data.total_groups; totalGroups = data.total_groups;
currentStudents = data.students ? data.students.rows : [];
totalStudents = data.students ? data.students.total : 0;
pendingEntries = pend.entries; pendingEntries = pend.entries;
pendingTotalEntries = pend.total; pendingTotalEntries = pend.total;
pendingGroups = pend.groups; pendingGroups = pend.groups;
pendingTotalGroups = pend.total_groups; pendingTotalGroups = pend.total_groups;
pendingStudents = pend.students ? pend.students.rows : [];
pendingTotalStudents = pend.students ? pend.students.total : 0;
if (pend.purge_days > 0) purgeDays = pend.purge_days; if (pend.purge_days > 0) purgeDays = pend.purge_days;
renderGroups(); renderGroups();
renderStudents();
renderGrid(); renderGrid();
renderPending(); renderPending();
} }
@@ -200,10 +254,30 @@ async function unscheduleGroup(id) {
else { const err = await res.json(); showToast(err.error || 'Ошибка'); } else { const err = await res.json(); showToast(err.error || 'Ошибка'); }
} }
async function restoreStudent(id) {
const res = await fetch(`${API}/api/students/${id}/restore`, { method: 'PUT', headers: hdr() });
if (res.ok) { showToast('Ученик восстановлен'); loadTrash(); }
else { const err = await res.json(); showToast(err.error || 'Ошибка восстановления'); }
}
async function hardDeleteStudent(id, name) {
if (!confirm(`Пометить ученика "${name}" на удаление? Он будет безвозвратно удалён через ${purgeDays} дней вместе с фото.`)) return;
const res = await fetch(`${API}/api/students/${id}/permanent`, { method: 'DELETE', headers: hdr() });
if (res.ok) { showToast(`Ученик помечен на удаление через ${purgeDays} дн.`); loadTrash(); }
else { const err = await res.json(); showToast(err.error || 'Ошибка'); }
}
async function unscheduleStudent(id) {
const res = await fetch(`${API}/api/students/${id}/unschedule`, { method: 'PUT', headers: hdr() });
if (res.ok) { showToast('Ученик возвращён в корзину'); loadTrash(); }
else { const err = await res.json(); showToast(err.error || 'Ошибка'); }
}
async function emptyTrash() { async function emptyTrash() {
const parts = []; const parts = [];
if (totalEntries) parts.push(`записей: ${totalEntries}`); if (totalEntries) parts.push(`записей: ${totalEntries}`);
if (totalGroups) parts.push(`групп: ${totalGroups}`); if (totalGroups) parts.push(`групп: ${totalGroups}`);
if (totalStudents) parts.push(`студентов: ${totalStudents}`);
if (!parts.length) return; if (!parts.length) return;
if (!confirm(`Пометить всё из корзины (${parts.join(', ')}) на удаление? Данные будут безвозвратно удалены через ${purgeDays} дней.`)) return; if (!confirm(`Пометить всё из корзины (${parts.join(', ')}) на удаление? Данные будут безвозвратно удалены через ${purgeDays} дней.`)) return;
const res = await fetch(`${API}/api/trash`, { method: 'DELETE', headers: hdr() }); const res = await fetch(`${API}/api/trash`, { method: 'DELETE', headers: hdr() });
@@ -241,6 +315,19 @@ document.getElementById('groupsGrid').addEventListener('click', e => {
} }
}); });
document.getElementById('studentsGrid').addEventListener('click', e => {
const card = e.target.closest('.card');
if (!card) return;
const rs = card.querySelector('[data-restore]');
if (rs && (e.target === rs || rs.contains(e.target))) { restoreStudent(parseInt(rs.dataset.restore, 10)); return; }
const hd = card.querySelector('[data-hard]');
if (hd && (e.target === hd || hd.contains(e.target))) {
const id = parseInt(hd.dataset.hard, 10);
const s = currentStudents.find(x => String(x.id) === String(id));
hardDeleteStudent(id, s ? s.name : id);
}
});
document.getElementById('pendingGrid').addEventListener('click', e => { document.getElementById('pendingGrid').addEventListener('click', e => {
const card = e.target.closest('.card'); const card = e.target.closest('.card');
if (!card) return; if (!card) return;
@@ -255,8 +342,15 @@ document.getElementById('pendingGroupsGrid').addEventListener('click', e => {
if (us && (e.target === us || us.contains(e.target))) { unscheduleGroup(parseInt(us.dataset.unscheduleGroup, 10)); } if (us && (e.target === us || us.contains(e.target))) { unscheduleGroup(parseInt(us.dataset.unscheduleGroup, 10)); }
}); });
document.getElementById('pendingStudentsGrid').addEventListener('click', e => {
const card = e.target.closest('.card');
if (!card) return;
const us = card.querySelector('[data-unschedule]');
if (us && (e.target === us || us.contains(e.target))) { unscheduleStudent(parseInt(us.dataset.unschedule, 10)); }
});
(async () => { (async () => {
if (await checkAuth()) { if (await requireAdminPage()) {
buildSidebar(document.body.dataset.page); buildSidebar(document.body.dataset.page);
loadTrash(); loadTrash();
} }
+6
View File
@@ -25,6 +25,8 @@
<p class="trash-muted">Эти данные будут удалены автоматически и безвозвратно вместе с файлами. Чтобы отменить удаление, нажмите «В корзину» — данные вернутся в корзину, откуда их можно восстановить.</p> <p class="trash-muted">Эти данные будут удалены автоматически и безвозвратно вместе с файлами. Чтобы отменить удаление, нажмите «В корзину» — данные вернутся в корзину, откуда их можно восстановить.</p>
<h4>Группы <span class="trash-muted" id="pendingGroupsInfo"></span></h4> <h4>Группы <span class="trash-muted" id="pendingGroupsInfo"></span></h4>
<div class="grid" id="pendingGroupsGrid"><div class="empty">Загрузка...</div></div> <div class="grid" id="pendingGroupsGrid"><div class="empty">Загрузка...</div></div>
<h4>Ученики <span class="trash-muted" id="pendingStudentsInfo"></span></h4>
<div class="grid" id="pendingStudentsGrid"><div class="empty">Загрузка...</div></div>
<h4>Записи журнала <span class="trash-muted" id="pendingEntriesInfo"></span></h4> <h4>Записи журнала <span class="trash-muted" id="pendingEntriesInfo"></span></h4>
<div class="grid" id="pendingGrid"><div class="empty">Загрузка...</div></div> <div class="grid" id="pendingGrid"><div class="empty">Загрузка...</div></div>
</div> </div>
@@ -32,6 +34,10 @@
<h3>Группы <span class="trash-muted" id="groupsInfo"></span></h3> <h3>Группы <span class="trash-muted" id="groupsInfo"></span></h3>
<div class="grid" id="groupsGrid"><div class="empty">Загрузка...</div></div> <div class="grid" id="groupsGrid"><div class="empty">Загрузка...</div></div>
</div> </div>
<div class="trash-section" id="studentsSection">
<h3>Ученики <span class="trash-muted" id="studentsInfo"></span></h3>
<div class="grid" id="studentsGrid"><div class="empty">Загрузка...</div></div>
</div>
<div class="trash-section"> <div class="trash-section">
<h3>Записи журнала <span class="trash-muted" id="entriesInfo"></span></h3> <h3>Записи журнала <span class="trash-muted" id="entriesInfo"></span></h3>
<div class="grid" id="grid"><div class="empty">Загрузка...</div></div> <div class="grid" id="grid"><div class="empty">Загрузка...</div></div>
+142 -27
View File
@@ -1398,14 +1398,26 @@ async function purgeScheduledDeletions() {
const scount = sres.rowCount; const scount = sres.rowCount;
const fbres = await pool.query('DELETE FROM feedbacks WHERE purge_at IS NOT NULL AND purge_at <= now()'); const fbres = await pool.query('DELETE FROM feedbacks WHERE purge_at IS NOT NULL AND purge_at <= now()');
const fbcount = fbres.rowCount; const fbcount = fbres.rowCount;
if (erefs.rowCount || gcount || ccount || scount || fbcount) { const strefs = await pool.query('SELECT id FROM students WHERE purge_at IS NOT NULL AND purge_at <= now()');
let stcount = 0;
for (const s of strefs.rows) {
const { rows: spRows } = await pool.query('SELECT photo_path AS p FROM student_photos WHERE student_id = $1', [s.id]);
spRows.forEach(r => safeUnlink(r.p));
await pool.query('DELETE FROM student_photos WHERE student_id = $1', [s.id]);
const { rows: sRows } = await pool.query('SELECT photo_path AS p FROM students WHERE id = $1 AND photo_path IS NOT NULL', [s.id]);
sRows.forEach(r => safeUnlink(r.p));
await pool.query('DELETE FROM students WHERE id = $1', [s.id]);
stcount++;
}
if (erefs.rowCount || gcount || ccount || scount || fbcount || stcount) {
invalidateEntries(); invalidateEntries();
invalidateGroups(); invalidateGroups();
invalidateStats(); invalidateStats();
} }
if (scount) invalidateShorts(); if (scount) invalidateShorts();
if (fbcount) invalidateFeedbacks(); if (fbcount) invalidateFeedbacks();
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount }; if (stcount) invalidateStudents();
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, students: stcount };
} }
function safeUnlink(relPath) { function safeUnlink(relPath) {
@@ -4615,8 +4627,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
} }
for (const x of ndata.students) { for (const x of ndata.students) {
await client.query( await client.query(
'INSERT INTO students (id, name, created_at, group_id, photo_path, profile) VALUES ($1,$2,$3,$4,$5,$6)', 'INSERT INTO students (id, name, created_at, group_id, photo_path, profile, deleted_at, purge_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
[x.id, x.name, x.created_at, x.group_id, x.photo_path, x.profile ? JSON.stringify(x.profile) : null] [x.id, x.name, x.created_at, x.group_id, x.photo_path, x.profile ? JSON.stringify(x.profile) : null, x.deleted_at, x.purge_at]
); );
} }
for (const x of ndata.modules) { for (const x of ndata.modules) {
@@ -6132,7 +6144,7 @@ app.get('/api/students', apiLimiter, optionalAuth, async (req, res) => {
const { rows } = await pool.query( const { rows } = await pool.query(
`SELECT s.*, g.name AS group_name FROM students s `SELECT s.*, g.name AS group_name FROM students s
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
WHERE 1=1${bw.where} ORDER BY s.name`, WHERE s.deleted_at IS NULL${bw.where} ORDER BY s.name`,
bw.params bw.params
); );
return rows; return rows;
@@ -6182,7 +6194,19 @@ app.post('/api/students', requireAuth, async (req, res) => {
invalidateStats(); invalidateStats();
res.status(201).json(rows[0]); res.status(201).json(rows[0]);
} catch (e) { } catch (e) {
if (e.code === '23505') return res.status(409).json({ error: 'Duplicate' }); if (e.code === '23505') {
const { rows: revived } = await pool.query(
'UPDATE students SET deleted_at = NULL, purge_at = NULL, group_id = $2 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; throw e;
} }
}); });
@@ -6193,7 +6217,7 @@ app.put('/api/students/:id', requireAuth, async (req, res) => {
const newGid = group_id === undefined || group_id === null || group_id === '' ? null : Number(group_id); const newGid = group_id === undefined || group_id === null || group_id === '' ? null : Number(group_id);
if (req.user.role !== 'admin') { if (req.user.role !== 'admin') {
const { rows: cur } = await pool.query( 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`, `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] [req.params.id]
); );
if (!cur.length) return res.status(404).json({ error: 'Not found' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
@@ -6210,7 +6234,7 @@ app.put('/api/students/:id', requireAuth, async (req, res) => {
`UPDATE students SET `UPDATE students SET
name = $1, name = $1,
group_id = $2 group_id = $2
WHERE id = $3 RETURNING *`, WHERE id = $3 AND deleted_at IS NULL RETURNING *`,
[name.trim(), newGid, req.params.id] [name.trim(), newGid, req.params.id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
@@ -6236,7 +6260,7 @@ app.post('/api/students/batch-group', requireAuth, async (req, res) => {
const params = [group_id, ...ids]; const params = [group_id, ...ids];
const placeholders = ids.map((_, i) => `$${i + 2}`).join(','); const placeholders = ids.map((_, i) => `$${i + 2}`).join(',');
const { rows } = await pool.query( const { rows } = await pool.query(
`UPDATE students SET group_id = $1 WHERE id IN (${placeholders}) RETURNING id`, `UPDATE students SET group_id = $1 WHERE id IN (${placeholders}) AND deleted_at IS NULL RETURNING id`,
params params
); );
await logAudit(req, 'student.batch-group', { group_id, count: rows.length }); await logAudit(req, 'student.batch-group', { group_id, count: rows.length });
@@ -6247,7 +6271,7 @@ app.post('/api/students/batch-group', requireAuth, async (req, res) => {
app.delete('/api/students/:id', requireAuth, async (req, res) => { app.delete('/api/students/:id', requireAuth, async (req, res) => {
if (req.user.role !== 'admin') { if (req.user.role !== 'admin') {
const { rows: cur } = await pool.query( const { rows: cur } = await pool.query(
'SELECT s.group_id FROM students s WHERE s.id = $1', [req.params.id] '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' }); if (!cur.length) return res.status(404).json({ error: 'Not found' });
const gid = cur[0].group_id; const gid = cur[0].group_id;
@@ -6255,10 +6279,84 @@ app.delete('/api/students/:id', requireAuth, async (req, res) => {
return res.status(403).json({ error: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
} }
} }
await pool.query('DELETE FROM students WHERE id = $1', [req.params.id]); const result = await pool.query(
const { rows: spRows } = await pool.query('SELECT photo_path AS p FROM student_photos WHERE student_id = $1', [req.params.id]); 'UPDATE students SET deleted_at = now() WHERE id = $1 AND deleted_at IS NULL', [req.params.id]
spRows.forEach(r => safeUnlink(r.p)); );
await logAudit(req, 'student.delete', { id: 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 (gid && !(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 (gid && !(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 (gid && !(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(); invalidateStudents();
invalidateStats(); invalidateStats();
res.json({ ok: true }); res.json({ ok: true });
@@ -6266,7 +6364,7 @@ app.delete('/api/students/:id', requireAuth, async (req, res) => {
async function studentProfileAccess(user, id) { async function studentProfileAccess(user, id) {
const { rows } = await pool.query( const { rows } = await pool.query(
'SELECT id, name, group_id, photo_path, profile FROM students WHERE id = $1', 'SELECT id, name, group_id, photo_path, profile FROM students WHERE id = $1 AND deleted_at IS NULL',
[id] [id]
); );
if (!rows.length) return { found: false }; if (!rows.length) return { found: false };
@@ -6516,7 +6614,7 @@ app.get('/api/export/student', requireAuth, async (req, res) => {
FROM students s FROM students s
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
LEFT JOIN branches b ON b.id = g.branch_id LEFT JOIN branches b ON b.id = g.branch_id
WHERE s.name = $1`, WHERE s.deleted_at IS NULL AND s.name = $1`,
[name] [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 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
@@ -6550,7 +6648,7 @@ app.get('/api/export/student', requireAuth, async (req, res) => {
pool.query(`SELECT gp.photo_path, gp.caption, gp.taken_at, gp.created_at, g.name AS group_name pool.query(`SELECT gp.photo_path, gp.caption, gp.taken_at, gp.created_at, g.name AS group_name
FROM group_photos gp FROM group_photos gp
JOIN groups g ON g.id = gp.group_id JOIN groups g ON g.id = gp.group_id
WHERE gp.group_id = (SELECT group_id FROM students WHERE name = $1) 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]), ORDER BY gp.sort_order ASC, gp.created_at DESC`, [name]),
]); ]);
const entryRows = entriesRes.rows; const entryRows = entriesRes.rows;
@@ -6836,7 +6934,7 @@ app.get('/api/groups/:id/export/files', requireAuth, async (req, res) => {
} }
const condStr = bindTz(conds.join(' AND '), params, await appTimezone()).sql; const condStr = bindTz(conds.join(' AND '), params, await appTimezone()).sql;
const [studentsRes, filesRes, photosRes, entryPhotosRes, originalsRes] = await Promise.all([ const [studentsRes, filesRes, photosRes, entryPhotosRes, originalsRes] = await Promise.all([
pool.query('SELECT id, name FROM students WHERE group_id = $1 ORDER BY name', [gid]), pool.query('SELECT id, name FROM students WHERE group_id = $1 AND deleted_at IS NULL ORDER BY name', [gid]),
includeFiles includeFiles
? pool.query( ? pool.query(
`SELECT pf.name, pf.path, e.student_name, e.created_at `SELECT pf.name, pf.path, e.student_name, e.created_at
@@ -7407,7 +7505,7 @@ app.get('/api/photos', requireAuth, async (req, res) => {
g.branch_id, g.name, sp.created_at, g.branch_id, g.name, sp.created_at,
s.name s.name
FROM student_photos sp FROM student_photos sp
JOIN students s ON s.id = sp.student_id JOIN students s ON s.id = sp.student_id AND s.deleted_at IS NULL
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
UNION ALL UNION ALL
SELECT 'module_photo', 'Тема модуля', m.photo_path, m.id, NULL::varchar, NULL::int, SELECT 'module_photo', 'Тема модуля', m.photo_path, m.id, NULL::varchar, NULL::int,
@@ -8984,7 +9082,19 @@ async function trashData(req, mode, limit, offset) {
${gWhere}${gsco} ORDER BY ${gOrder} DESC`, ${gWhere}${gsco} ORDER BY ${gOrder} DESC`,
gparams gparams
); );
return { entries: rows, total: crows.rows[0].n, groups: ggroups, total_groups: gcount[0].n };
const stWhere = isPending
? ' WHERE s.purge_at IS NOT NULL'
: ' WHERE s.deleted_at IS NOT NULL AND s.purge_at IS NULL';
const stparams = [];
const stscoped = req.user.role !== 'admin';
const gsco2 = stscoped
? (bw.ids.length ? ` AND s.group_id IN (${bw.ids.map(id => `$${stparams.push(id)})`).join(',')}` : ' AND 1 = 0')
: '';
const stOrder = isPending ? 's.purge_at' : 's.deleted_at';
const { rows: stcount } = await pool.query(`SELECT count(*)::int AS n FROM students s${stWhere}${gsco2}`, stparams);
const { rows: strows } = await pool.query(`SELECT s.*, g.name AS group_name FROM students s LEFT JOIN groups g ON g.id = s.group_id${stWhere}${gsco2} ORDER BY ${stOrder} DESC`, stparams.slice());
return { entries: rows, total: crows.rows[0].n, groups: ggroups, total_groups: gcount[0].n, students: { rows: strows, total: stcount[0].n } };
} }
app.get('/api/trash', requireAuth, async (req, res) => { app.get('/api/trash', requireAuth, async (req, res) => {
@@ -9009,11 +9119,16 @@ app.delete('/api/trash', requireAuth, requireAdmin, async (req, res) => {
`UPDATE groups SET purge_at = now() + ($1 || ' days')::interval WHERE deleted_at IS NOT NULL AND purge_at IS NULL`, `UPDATE groups SET purge_at = now() + ($1 || ' days')::interval WHERE deleted_at IS NOT NULL AND purge_at IS NULL`,
[days] [days]
); );
const s = await pool.query(
`UPDATE students SET purge_at = now() + ($1 || ' days')::interval WHERE deleted_at IS NOT NULL AND purge_at IS NULL`,
[days]
);
invalidateEntries(); invalidateEntries();
invalidateGroups(); invalidateGroups();
invalidateStudents();
invalidateStats(); invalidateStats();
await logAudit(req, 'trash.clear', { entries: e.rowCount, groups: g.rowCount, days }); await logAudit(req, 'trash.clear', { entries: e.rowCount, groups: g.rowCount, students: s.rowCount });
res.json({ ok: true, entries: e.rowCount, groups: g.rowCount, days }); res.json({ ok: true, entries: e.rowCount, groups: g.rowCount, students: s.rowCount, days });
}); });
// --- External API v1 --- // --- External API v1 ---
@@ -9108,14 +9223,14 @@ apiV1.get('/students', async (req, res) => {
const { rows: crows } = await pool.query( const { rows: crows } = await pool.query(
`SELECT count(*)::int AS n FROM students s `SELECT count(*)::int AS n FROM students s
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
WHERE 1=1${extra}${bw.where}`, WHERE s.deleted_at IS NULL${extra}${bw.where}`,
params params
); );
const total = crows[0].n; const total = crows[0].n;
const q = `SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.created_at const q = `SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.created_at
FROM students s FROM students s
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
WHERE 1=1${extra}${bw.where} WHERE s.deleted_at IS NULL${extra}${bw.where}
ORDER BY s.name ORDER BY s.name
LIMIT $${params.push(limit)} OFFSET $${params.push(offset)}`; LIMIT $${params.push(limit)} OFFSET $${params.push(offset)}`;
const { rows } = await pool.query(q, params); const { rows } = await pool.query(q, params);
@@ -9127,7 +9242,7 @@ apiV1.get('/students/:id', async (req, res) => {
`SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.profile, s.created_at `SELECT s.id, s.name, s.group_id, g.name AS group_name, s.photo_path, s.profile, s.created_at
FROM students s FROM students s
LEFT JOIN groups g ON g.id = s.group_id LEFT JOIN groups g ON g.id = s.group_id
WHERE s.id = $1`, WHERE s.deleted_at IS NULL AND s.id = $1`,
[req.params.id] [req.params.id]
); );
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
@@ -9499,7 +9614,7 @@ apiV1.post('/students', apiWrite('write'), async (req, res) => {
apiV1.put('/students/:id', apiWrite('write'), async (req, res) => { apiV1.put('/students/:id', apiWrite('write'), async (req, res) => {
const name = reqStr(req.body?.name, 150); const name = reqStr(req.body?.name, 150);
const cur = await pool.query('SELECT id, group_id FROM students WHERE id = $1', [req.params.id]); 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 (!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))) { 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: 'Нет доступа к этому ученику' }); return res.status(403).json({ error: 'Нет доступа к этому ученику' });
@@ -9510,7 +9625,7 @@ apiV1.put('/students/:id', apiWrite('write'), async (req, res) => {
if (grp.error) return res.status(grp.code || 400).json({ error: grp.error }); if (grp.error) return res.status(grp.code || 400).json({ error: grp.error });
gid = grp.group.id; gid = grp.group.id;
} }
const { rows } = await pool.query('UPDATE students SET name = $1, group_id = $2 WHERE id = $3 RETURNING *', [name, gid, req.params.id]); const { rows } = await pool.query('UPDATE students SET name = $1, group_id = $2 WHERE id = $3 AND deleted_at IS NULL RETURNING *', [name, gid, req.params.id]);
if (!rows.length) return res.status(404).json({ error: 'Not found' }); if (!rows.length) return res.status(404).json({ error: 'Not found' });
await apiAudit(req, 'api.student.update', { id: rows[0].id, name }); await apiAudit(req, 'api.student.update', { id: rows[0].id, name });
invalidateStudents(); invalidateStudents();
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 118 KiB