feat(modules): флаг «Вложения» у модуля и подсказка ученику на главной

- переключатель «Вложения» слева от «Количество занятий» в модалке модуля,
  бейдж «Вложения» в списке модулей
- колонка modules.has_attachments: db/init.sql, db/migration.sql,
  ensureModulesTable(), POST/PUT/GET /api/modules, GET /api/v1/modules, backup
- на главной странице у выбранного модуля с вложениями показывается
  подсказка «К этой теме нужно приложить файлы»

Также вошла ранее незакоммиченная работа:
- битые изображения: скан и карантин, раздел «Битые изображения» в корзине
  (таблица broken_images, /api/broken-images/*, trash.html + trash.js)
- отзывы: фото ученика и цветовая полоса оценки работ в модалке
  (#fbResidentPhoto, #fbMarkStripe, GET /api/feedbacks/work-marks)
- фото и галереи: photo_key/photo_id в /api/photos и inline-карантин битых фото
- поля пароля на journal.html и links.html обёрнуты в no-op form
This commit is contained in:
dev
2026-10-14 00:01:27 +03:00
parent 055084b9c5
commit 39ae3fdd30
20 changed files with 853 additions and 44 deletions
+351 -22
View File
@@ -1467,6 +1467,8 @@ async function purgeScheduledDeletions() {
const scount = sres.rowCount;
const fbres = await pool.query('DELETE FROM feedbacks WHERE purge_at IS NOT NULL AND purge_at <= now()');
const fbcount = fbres.rowCount;
const bires = await pool.query('DELETE FROM broken_images WHERE purge_at IS NOT NULL AND purge_at <= now()');
const bicount = bires.rowCount;
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) {
@@ -1478,7 +1480,7 @@ async function purgeScheduledDeletions() {
await pool.query('DELETE FROM students WHERE id = $1', [s.id]);
stcount++;
}
if (erefs.rowCount || gcount || ccount || scount || fbcount || stcount) {
if (erefs.rowCount || gcount || ccount || scount || fbcount || stcount || bicount) {
invalidateEntries();
invalidateGroups();
invalidateStats();
@@ -1486,7 +1488,8 @@ async function purgeScheduledDeletions() {
if (scount) invalidateShorts();
if (fbcount) invalidateFeedbacks();
if (stcount) invalidateStudents();
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, students: stcount };
if (bicount) invalidateAll();
return { entries: erefs.rowCount, groups: gcount, chat_threads: ccount, short_messages: scount, feedbacks: fbcount, students: stcount, broken_images: bicount };
}
function safeUnlink(relPath) {
@@ -1600,6 +1603,182 @@ async function sweepOrphanedUploads() {
storage.pruneCache();
}
const BROKEN_IMAGE_SOURCES = [
{ key: 'entries.photo_path', table: 'entries', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Главное фото записи' },
{ key: 'entries.photo_original_path', table: 'entries', column: 'photo_original_path', idColumn: 'id', kind: 'column', label: 'Оригинал фото записи' },
{ key: 'entry_photos.photo_path', table: 'entry_photos', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Фото записи' },
{ key: 'group_photos.photo_path', table: 'group_photos', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Фотохроника группы' },
{ key: 'group_photos.photo_original_path', table: 'group_photos', column: 'photo_original_path', idColumn: 'id', kind: 'column', label: 'Оригинал фото группы' },
{ key: 'student_photos.photo_path', table: 'student_photos', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Фото ученика' },
{ key: 'students.photo_path', table: 'students', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Аватар ученика' },
{ key: 'groups.cover_path', table: 'groups', column: 'cover_path', idColumn: 'id', kind: 'column', label: 'Обложка группы' },
{ key: 'modules.photo_path', table: 'modules', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Фото темы' },
{ key: 'bookmarks.photo_path', table: 'bookmarks', column: 'photo_path', idColumn: 'id', kind: 'column', label: 'Картинка закладки' },
{ key: 'student_face_refs.photo_path', table: 'student_face_refs', column: 'photo_path', idColumn: 'id', kind: 'row', label: 'Эталон лица' },
{ key: 'project_files.path', table: 'project_files', column: 'path', idColumn: 'id', kind: 'row', label: 'Файл проекта' },
{ key: 'chat_attachments.path', table: 'chat_attachments', column: 'path', idColumn: 'id', kind: 'row', label: 'Вложение чата' },
{ key: 'photo_jobs.before_path', table: 'photo_jobs', column: 'before_path', idColumn: 'id', kind: 'column', label: 'Фото до обработки' },
{ key: 'photo_jobs.after_path', table: 'photo_jobs', column: 'after_path', idColumn: 'id', kind: 'column', label: 'Фото после обработки' },
{ key: 'settings.system_logo', table: 'settings', column: 'value', idColumn: null, kind: 'setting', label: 'Логотип системы', where: `key = 'system_logo'` },
];
function brokenImageSource(key) {
return BROKEN_IMAGE_SOURCES.find(s => s.key === key) || null;
}
function brokenSourceRowsSql(src) {
const where = src.kind === 'setting'
? `${src.where} AND ${src.column} IS NOT NULL AND ${src.column} <> ''`
: `${src.column} IS NOT NULL`;
const idExpr = src.kind === 'setting' ? 'NULL::int' : src.idColumn;
return `SELECT ${idExpr} AS id, ${src.column} AS path FROM ${src.table} WHERE ${where}`;
}
async function scanBrokenImages() {
const have = new Set();
try {
const objects = await storage.listAll('');
for (const o of objects) have.add(o.key);
} catch (err) {
console.error('Broken images list failed:', err.message);
}
const candidates = [];
let checked = 0;
for (const src of BROKEN_IMAGE_SOURCES) {
let rows;
try {
({ rows } = await pool.query(brokenSourceRowsSql(src)));
} catch (err) {
console.error('Broken images scan failed:', src.key, err.message);
continue;
}
for (const r of rows) {
if (!r.path) continue;
const key = storage.keyFromPath(r.path);
if (!key) continue;
checked++;
if (have.has(key)) continue;
candidates.push({ source_key: src.key, label: src.label, source_table: src.table, source_column: src.column, source_id: r.id == null ? null : Number(r.id), path: r.path, key });
}
}
const items = [];
const CONC = 8;
for (let i = 0; i < candidates.length; i += CONC) {
const batch = candidates.slice(i, i + CONC);
const res = await Promise.all(batch.map(async c => {
try { return (await storage.exists(c.key)) ? null : c; } catch { return c; }
}));
for (const r of res) {
if (!r) continue;
delete r.key;
items.push(r);
}
}
return { items, checked };
}
async function quarantineBrokenReference(src, id, req) {
let path = null;
if (src.kind === 'setting') {
const { rows } = await pool.query(`SELECT ${src.column} AS path FROM ${src.table} WHERE ${src.where}`);
if (!rows.length) return { error: 'not_found' };
path = rows[0].path;
} else {
const { rows } = await pool.query(`SELECT ${src.column} AS path FROM ${src.table} WHERE ${src.idColumn} = $1`, [id]);
if (!rows.length) return { error: 'not_found' };
path = rows[0].path;
}
if (!path) return { error: 'empty' };
const key = storage.keyFromPath(path);
if (!key) return { error: 'bad_path' };
if (await storage.exists(key)) return { error: 'exists' };
if (src.kind === 'row') {
const { rows } = await pool.query(`SELECT * FROM ${src.table} WHERE ${src.idColumn} = $1`, [id]);
if (!rows.length) return { error: 'not_found' };
const snapshot = rows[0];
await pool.query(
`INSERT INTO broken_images (source_key, source_table, source_column, source_id, photo_path, label, row_snapshot, reason, deleted_by)
VALUES ($1,$2,$3,$4,$5,$6,$7::jsonb,$8,$9)`,
[src.key, src.table, src.column, id, path, src.label, JSON.stringify(snapshot), 'missing', req.user.id]
);
await pool.query(`DELETE FROM ${src.table} WHERE ${src.idColumn} = $1`, [id]);
if (src.table === 'group_photos') {
await pool.query('UPDATE groups SET cover_path = NULL WHERE cover_path = $1', [path]);
await pool.query(`DELETE FROM photo_faces WHERE source_type = 'group' AND source_id = $1`, [id]);
} else if (src.table === 'entry_photos') {
await pool.query(`DELETE FROM photo_faces WHERE source_type = 'entry' AND source_id = $1`, [id]);
}
return { ok: true, path };
}
if (src.kind === 'setting') {
await pool.query(
`INSERT INTO broken_images (source_key, source_table, source_column, source_id, photo_path, label, column_value, reason, deleted_by)
VALUES ($1,$2,$3,NULL,$4,$5,$6,$7,$8)`,
[src.key, src.table, src.column, path, src.label, path, 'missing', req.user.id]
);
await pool.query(`UPDATE ${src.table} SET ${src.column} = NULL WHERE ${src.where}`);
return { ok: true, path };
}
await pool.query(
`INSERT INTO broken_images (source_key, source_table, source_column, source_id, photo_path, label, column_value, reason, deleted_by)
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
[src.key, src.table, src.column, id, path, src.label, path, 'missing', req.user.id]
);
await pool.query(`UPDATE ${src.table} SET ${src.column} = NULL WHERE ${src.idColumn} = $1`, [id]);
return { ok: true, path };
}
async function restoreBrokenImage(id) {
const { rows } = await pool.query('SELECT * FROM broken_images WHERE id = $1', [id]);
if (!rows.length) return { error: 'not_found' };
const row = rows[0];
const src = brokenImageSource(row.source_key);
if (!src) return { error: 'bad_source' };
if (row.row_snapshot) {
const snap = row.row_snapshot;
const { rows: cols } = await pool.query(
`SELECT column_name, data_type FROM information_schema.columns
WHERE table_schema = 'public' AND table_name = $1 ORDER BY ordinal_position`,
[src.table]
);
const names = [];
const types = [];
for (const c of cols) {
if (!Object.prototype.hasOwnProperty.call(snap, c.column_name)) continue;
names.push(c.column_name);
types.push(c.data_type);
}
if (!names.length) return { error: 'bad_snapshot' };
const vals = names.map((name, i) => {
const v = snap[name];
if (v == null) return null;
if (types[i] === 'json' || types[i] === 'jsonb') return JSON.stringify(v);
return v;
});
const ph = names.map((_, i) => `$${i + 1}`);
await pool.query(
`INSERT INTO ${src.table} (${names.map(n => `"${n}"`).join(', ')}) VALUES (${ph.join(', ')}) ON CONFLICT (id) DO NOTHING`,
vals
);
} else if (src.kind === 'setting') {
await pool.query(
`UPDATE ${src.table} SET ${src.column} = $1 WHERE ${src.where} AND (${src.column} IS NULL OR ${src.column} = '')`,
[row.column_value]
);
} else {
await pool.query(
`UPDATE ${src.table} SET ${src.column} = $1 WHERE ${src.idColumn} = $2 AND (${src.column} IS NULL OR ${src.column} = '')`,
[row.column_value, row.source_id]
);
}
await pool.query('DELETE FROM broken_images WHERE id = $1', [id]);
return { ok: true };
}
async function ensureAuditTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS audit_log (
id SERIAL PRIMARY KEY,
@@ -1634,15 +1813,36 @@ async function ensureBannedIpsTable() {
)`);
}
async function ensureBrokenImagesTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS broken_images (
id SERIAL PRIMARY KEY,
source_key VARCHAR(80) NOT NULL,
source_table VARCHAR(64) NOT NULL,
source_column VARCHAR(64) NOT NULL,
source_id INT,
photo_path VARCHAR(255) NOT NULL,
label VARCHAR(200),
row_snapshot JSONB,
column_value VARCHAR(255),
reason VARCHAR(200),
deleted_by INT REFERENCES users(id) ON DELETE SET NULL,
deleted_at TIMESTAMPTZ DEFAULT now(),
purge_at TIMESTAMPTZ
)`);
await pool.query('CREATE INDEX IF NOT EXISTS idx_broken_images_purge ON broken_images(purge_at)');
}
async function ensureModulesTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS modules (
id SERIAL PRIMARY KEY,
name VARCHAR(200) NOT NULL UNIQUE,
lessons_count INT NOT NULL DEFAULT 0,
is_active BOOLEAN NOT NULL DEFAULT true,
has_attachments BOOLEAN NOT NULL DEFAULT false,
created_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS is_active BOOLEAN NOT NULL DEFAULT true');
await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS has_attachments BOOLEAN NOT NULL DEFAULT false');
await pool.query('ALTER TABLE modules ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255)');
await pool.query('ALTER TABLE entries ADD COLUMN IF NOT EXISTS module_id INT REFERENCES modules(id) ON DELETE SET NULL');
await pool.query('CREATE INDEX IF NOT EXISTS idx_entries_module_id ON entries(module_id)');
@@ -3562,6 +3762,7 @@ app.post('/api/shorts', requireAuth, async (req, res) => {
await client.query('COMMIT');
await logAudit(req, 'shorts.create', { count: created.length, lesson_date: lessonDate, topic });
invalidateShorts();
invalidateStats();
res.status(201).json({ items: created });
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
@@ -3613,6 +3814,7 @@ app.put('/api/shorts/:id', requireAuth, async (req, res) => {
if (delta !== undefined) await syncShortMessageMark(id, resident, delta, req.user.id);
await logAudit(req, 'shorts.update', { id, resident, lesson_date: lessonDate, topic, used, used_at: usedAt, ...(delta !== undefined ? { delta } : {}) });
invalidateShorts();
if (delta !== undefined) invalidateStats();
res.json({ ...rows[0], delta: delta !== undefined ? delta : await shortMessageDelta(id) });
} catch (e) {
res.status(500).json({ error: e.message });
@@ -3804,6 +4006,32 @@ app.get('/api/feedbacks', requireAuth, async (req, res) => {
}
});
app.get('/api/feedbacks/work-marks', requireAuth, async (req, res) => {
try {
const payload = await cacheWrap('stats:feedback-work-marks:' + scopeKey(req.user), STATS_TTL_MS, async () => {
const bs = branchScope(req.user);
const params = [];
let scope = ' AND 1 = 0';
if (bs.admin) scope = '';
else if (bs.ids.length) { params.push(bs.ids); scope = ' AND (s.group_id IS NULL OR g.branch_id = ANY($1::int[]))'; }
const { rows } = await pool.query(
`SELECT s.name, COALESCE(SUM(swm.delta), 0)::int AS total, count(*)::int AS marks
FROM student_work_marks swm
JOIN students s ON s.id = swm.student_id
LEFT JOIN groups g ON g.id = s.group_id
WHERE s.deleted_at IS NULL${scope}
GROUP BY s.id, s.name
ORDER BY s.id`,
params
);
return { items: rows };
});
res.json(payload);
} catch (e) {
res.status(500).json({ error: e.message });
}
});
app.get('/api/feedbacks/:id', requireAuth, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
@@ -5535,6 +5763,7 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
await client.query('DELETE FROM user_branches');
await client.query('DELETE FROM sessions');
await client.query('DELETE FROM api_keys');
await client.query('DELETE FROM broken_images');
await client.query('DELETE FROM audit_log');
await client.query('DELETE FROM user_settings');
await client.query('DELETE FROM user_notes');
@@ -5611,8 +5840,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
}
for (const x of ndata.modules) {
await client.query(
'INSERT INTO modules (id, name, lessons_count, is_active, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6)',
[x.id, x.name, x.lessons_count, x.is_active, x.photo_path, x.created_at]
'INSERT INTO modules (id, name, lessons_count, is_active, has_attachments, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
[x.id, x.name, x.lessons_count, x.is_active, x.has_attachments, x.photo_path, x.created_at]
);
}
for (const x of ndata.entries) {
@@ -7003,17 +7232,18 @@ function parseLessonsCount(v) {
}
app.post('/api/modules', requireAdmin, async (req, res) => {
const { name, lessons_count } = req.body;
const { name, lessons_count, has_attachments } = req.body;
if (!name?.trim()) return res.status(400).json({ error: 'Название обязательно' });
let lessons;
try { lessons = parseLessonsCount(lessons_count); }
catch (e) { return res.status(400).json({ error: e.message }); }
const attach = has_attachments === true;
try {
const { rows } = await pool.query(
'INSERT INTO modules (name, lessons_count) VALUES ($1, $2) RETURNING *',
[name.trim(), lessons]
'INSERT INTO modules (name, lessons_count, has_attachments) VALUES ($1, $2, $3) RETURNING *',
[name.trim(), lessons, attach]
);
await logAudit(req, 'module.create', { id: rows[0].id, name: name.trim(), lessons_count: lessons });
await logAudit(req, 'module.create', { id: rows[0].id, name: name.trim(), lessons_count: lessons, has_attachments: attach });
res.status(201).json(rows[0]);
} catch (e) {
if (e.code === '23505') return res.status(409).json({ error: 'Модуль с таким названием уже существует' });
@@ -7022,18 +7252,19 @@ app.post('/api/modules', requireAdmin, async (req, res) => {
});
app.put('/api/modules/:id', requireAdmin, async (req, res) => {
const { name, lessons_count } = req.body;
const { name, lessons_count, has_attachments } = req.body;
if (!name?.trim()) return res.status(400).json({ error: 'Название обязательно' });
let lessons;
try { lessons = parseLessonsCount(lessons_count); }
catch (e) { return res.status(400).json({ error: e.message }); }
const attach = has_attachments === true;
try {
const { rows } = await pool.query(
'UPDATE modules SET name = $1, lessons_count = $2 WHERE id = $3 RETURNING *',
[name.trim(), lessons, req.params.id]
'UPDATE modules SET name = $1, lessons_count = $2, has_attachments = $3 WHERE id = $4 RETURNING *',
[name.trim(), lessons, attach, req.params.id]
);
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
await logAudit(req, 'module.update', { id: req.params.id, name: name.trim(), lessons_count: lessons });
await logAudit(req, 'module.update', { id: req.params.id, name: name.trim(), lessons_count: lessons, has_attachments: attach });
res.json(rows[0]);
} catch (e) {
if (e.code === '23505') return res.status(409).json({ error: 'Модуль с таким названием уже существует' });
@@ -9570,14 +9801,16 @@ app.get('/api/photos', requireAuth, async (req, res) => {
const where = conditions.length ? ' WHERE ' + bindTz(conditions.join(' AND '), params, await appTimezone()).sql : '';
const from = `FROM (
SELECT 'entry'::text AS source_type, 'Главное фото записи'::text AS source_label,
e.photo_path AS path, e.id AS source_id, e.student_name, e.group_id,
e.photo_path AS path, e.id AS source_id, 'entries.photo_path'::text AS photo_key, e.id AS photo_id,
e.student_name, e.group_id,
g.branch_id, g.name AS group_name, e.created_at,
e.description AS title
FROM entries e
JOIN groups g ON g.id = e.group_id
WHERE e.deleted_at IS NULL AND e.photo_path IS NOT NULL
UNION ALL
SELECT 'entry_photo', 'Фото записи', ep.photo_path, ep.entry_id, e.student_name, e.group_id,
SELECT 'entry_photo', 'Фото записи', ep.photo_path, ep.entry_id, 'entry_photos.photo_path', ep.id,
e.student_name, e.group_id,
g.branch_id, g.name, ep.created_at,
COALESCE(NULLIF(ep.caption, ''), e.description)
FROM entry_photos ep
@@ -9585,20 +9818,23 @@ app.get('/api/photos', requireAuth, async (req, res) => {
JOIN groups g ON g.id = e.group_id
WHERE e.deleted_at IS NULL AND ep.photo_path IS DISTINCT FROM e.photo_path
UNION ALL
SELECT 'group_photo', 'Фотохроника группы', gp.photo_path, gp.group_id, NULL::varchar, gp.group_id,
SELECT 'group_photo', 'Фотохроника группы', gp.photo_path, gp.group_id, 'group_photos.photo_path', gp.id,
NULL::varchar, gp.group_id,
g.branch_id, g.name, gp.created_at,
COALESCE(NULLIF(gp.caption, ''), g.name)
FROM group_photos gp
JOIN groups g ON g.id = gp.group_id
UNION ALL
SELECT 'student_photo', 'Фото ученика', sp.photo_path, sp.student_id, s.name, s.group_id,
SELECT 'student_photo', 'Фото ученика', sp.photo_path, sp.student_id, 'student_photos.photo_path', sp.id,
s.name, s.group_id,
g.branch_id, g.name, sp.created_at,
s.name
FROM student_photos sp
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
UNION ALL
SELECT 'module_photo', 'Тема модуля', m.photo_path, m.id, NULL::varchar, NULL::int,
SELECT 'module_photo', 'Тема модуля', m.photo_path, m.id, 'modules.photo_path', m.id,
NULL::varchar, NULL::int,
NULL::int, NULL::varchar, m.created_at,
m.name
FROM modules m
@@ -9606,7 +9842,7 @@ app.get('/api/photos', requireAuth, async (req, res) => {
) t`;
const { rows: crows } = await pool.query(`SELECT count(*)::int AS n ${from}${where}`, params);
const total = crows[0].n;
let q = `SELECT t.source_type, t.source_label, t.path, t.source_id, t.student_name,
let q = `SELECT t.source_type, t.source_label, t.path, t.source_id, t.photo_key, t.photo_id, t.student_name,
t.group_id, t.group_name, t.created_at, t.title ${from}${where}
ORDER BY t.created_at DESC`;
const qparams = params.slice();
@@ -9619,6 +9855,8 @@ app.get('/api/photos', requireAuth, async (req, res) => {
source_type: r.source_type,
source_label: r.source_label,
source_id: r.source_id,
photo_key: r.photo_key || null,
photo_id: r.photo_id == null ? null : r.photo_id,
path: r.path,
title: r.title || '',
student_name: r.student_name || null,
@@ -11285,7 +11523,21 @@ async function trashData(req, mode, limit, offset) {
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 } };
let images = [];
if (req.user.role === 'admin') {
const iWhere = isPending ? ' WHERE purge_at IS NOT NULL' : ' WHERE purge_at IS NULL';
const { rows: irows } = await pool.query(
`SELECT id, source_key, source_table, source_column, source_id, photo_path, label, deleted_at, purge_at
FROM broken_images${iWhere} ORDER BY deleted_at DESC`
);
images = irows;
}
return {
entries: rows, total: crows.rows[0].n,
groups: ggroups, total_groups: gcount[0].n,
students: { rows: strows, total: stcount[0].n },
images, total_images: images.length,
};
}
app.get('/api/trash', requireAuth, async (req, res) => {
@@ -11325,12 +11577,88 @@ app.delete('/api/trash', requireAuth, requireAdmin, async (req, res) => {
`UPDATE students SET purge_at = now() + ($1 || ' days')::interval WHERE deleted_at IS NOT NULL AND purge_at IS NULL`,
[days]
);
const bi = await pool.query(
`UPDATE broken_images SET purge_at = now() + ($1 || ' days')::interval WHERE purge_at IS NULL`,
[days]
);
invalidateEntries();
invalidateGroups();
invalidateStudents();
invalidateStats();
await logAudit(req, 'trash.clear', { entries: e.rowCount, groups: g.rowCount, students: s.rowCount });
res.json({ ok: true, entries: e.rowCount, groups: g.rowCount, students: s.rowCount, days });
await logAudit(req, 'trash.clear', { entries: e.rowCount, groups: g.rowCount, students: s.rowCount, images: bi.rowCount });
res.json({ ok: true, entries: e.rowCount, groups: g.rowCount, students: s.rowCount, images: bi.rowCount, days });
});
app.get('/api/broken-images/scan', requireAuth, requireAdmin, async (req, res) => {
try {
const result = await scanBrokenImages();
res.json(result);
} catch (err) {
console.error('GET /api/broken-images/scan:', err);
res.status(500).json({ error: 'Ошибка проверки изображений' });
}
});
app.post('/api/broken-images', requireAuth, requireAdmin, async (req, res) => {
try {
const raw = Array.isArray(req.body && req.body.items) ? req.body.items : [];
if (!raw.length) return res.status(400).json({ error: 'Нет элементов' });
if (raw.length > 500) return res.status(400).json({ error: 'Слишком много элементов за раз' });
let quarantined = 0;
let skipped = 0;
const errors = [];
for (const it of raw) {
const src = brokenImageSource(String(it && it.source_key || ''));
if (!src) { skipped++; continue; }
const id = it.source_id == null ? null : parseInt(it.source_id, 10);
if (src.kind !== 'setting' && !Number.isFinite(id)) { skipped++; continue; }
const r = await quarantineBrokenReference(src, id, req);
if (r.ok) quarantined++;
else {
skipped++;
if (r.error !== 'exists' && r.error !== 'empty') errors.push(`${src.key}#${id}: ${r.error}`);
}
}
invalidateAll();
await logAudit(req, 'broken_image.quarantine', { quarantined, skipped, errors: errors.slice(0, 20) });
res.json({ ok: true, quarantined, skipped, errors });
} catch (err) {
console.error('POST /api/broken-images:', err);
res.status(500).json({ error: 'Ошибка удаления изображений' });
}
});
app.put('/api/broken-images/:id/restore', requireAuth, requireAdmin, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Неверный id' });
const r = await restoreBrokenImage(id);
if (r.error === 'not_found') return res.status(404).json({ error: 'Не найдено' });
if (r.error) return res.status(400).json({ error: 'Не удалось восстановить' });
invalidateAll();
await logAudit(req, 'broken_image.restore', { id });
res.json({ ok: true });
});
app.put('/api/broken-images/:id/unschedule', requireAuth, requireAdmin, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Неверный id' });
const r = await pool.query('UPDATE broken_images SET purge_at = NULL WHERE id = $1', [id]);
if (!r.rowCount) return res.status(404).json({ error: 'Не найдено' });
await logAudit(req, 'broken_image.unschedule', { id });
res.json({ ok: true });
});
app.delete('/api/broken-images/:id/permanent', requireAuth, requireAdmin, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isFinite(id)) return res.status(400).json({ error: 'Неверный id' });
const days = await trashPurgeDays();
const r = await pool.query(
`UPDATE broken_images SET purge_at = now() + ($1 || ' days')::interval WHERE id = $2`,
[days, id]
);
if (!r.rowCount) return res.status(404).json({ error: 'Не найдено' });
await logAudit(req, 'broken_image.permanent', { id });
res.json({ ok: true, days });
});
// --- External API v1 ---
@@ -11465,7 +11793,7 @@ apiV1.get('/modules', async (req, res) => {
const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : '';
const { rows: crows } = await pool.query(`SELECT count(*)::int AS n FROM modules m${where}`, params);
const total = crows[0].n;
const q = `SELECT m.id, m.name, m.lessons_count, m.is_active, m.created_at, count(e.id)::int AS entries_count
const q = `SELECT m.id, m.name, m.lessons_count, m.is_active, m.has_attachments, m.created_at, count(e.id)::int AS entries_count
FROM modules m
LEFT JOIN entries e ON e.module_id = m.id${where}
GROUP BY m.id
@@ -11996,6 +12324,7 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
try { await ensureShortMessagesTable(); } catch (err) { console.error('Short messages table:', err); }
try { await ensureStudentWorkMarksTable(); } catch (err) { console.error('Student work marks table:', err); }
try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks table:', err); }
try { await ensureBrokenImagesTable(); } catch (err) { console.error('Broken images table:', err); }
try { await purgeOldNotifications(); } catch (err) { console.error('Notifications purge:', err); }
setInterval(() => { purgeOldNotifications().catch(err => console.error('Notifications purge:', err)); }, 60 * 60 * 1000).unref();
try { await purgeOldChat(); } catch (err) { console.error('Chat purge:', err); }