add soft delete with trash page and group photo chronology with styling
This commit is contained in:
@@ -48,12 +48,45 @@ async function getSetting(key, def) {
|
||||
return rows.length ? rows[0].value : def;
|
||||
}
|
||||
|
||||
function removeUpload(file) {
|
||||
if (!file) return;
|
||||
const fp = path.join(__dirname, file.path);
|
||||
function safeUnlink(relPath) {
|
||||
if (!relPath) return;
|
||||
const fp = path.join(__dirname, String(relPath).replace(/^\/+/, ''));
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
|
||||
function removeUpload(file) {
|
||||
safeUnlink(file && file.path);
|
||||
}
|
||||
|
||||
async function removeEntryFiles(entryId) {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT photo_path AS p FROM entries WHERE id = $1
|
||||
UNION ALL
|
||||
SELECT path AS p FROM project_files WHERE entry_id = $1`,
|
||||
[entryId]
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.p));
|
||||
}
|
||||
|
||||
async function sweepOrphanedUploads() {
|
||||
const dir = path.join(__dirname, 'uploads');
|
||||
if (!fs.existsSync(dir)) return;
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }] = await Promise.all([
|
||||
pool.query('SELECT photo_path AS p FROM entries WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM project_files'),
|
||||
pool.query('SELECT photo_path AS p FROM group_photos'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos].forEach(r => refs.add('/' + String(r.p).replace(/^\/+/, '')));
|
||||
for (const f of fs.readdirSync(dir)) {
|
||||
const fp = path.join(dir, f);
|
||||
if (!fs.statSync(fp).isFile()) continue;
|
||||
if (!refs.has('/uploads/' + f)) {
|
||||
try { fs.unlinkSync(fp); } catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Settings ---
|
||||
app.get('/api/settings', requireAdmin, async (_, res) => {
|
||||
const { rows } = await pool.query('SELECT key, value FROM settings ORDER BY key');
|
||||
@@ -188,8 +221,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
}
|
||||
for (const x of data.entries) {
|
||||
await client.query(
|
||||
'INSERT INTO entries (id, student_name, group_id, description, photo_path, created_at) VALUES ($1,$2,$3,$4,$5,$6)',
|
||||
[x.id, x.student_name, x.group_id, x.description, x.photo_path ?? null, x.created_at]
|
||||
'INSERT INTO entries (id, student_name, group_id, description, photo_path, deleted_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7)',
|
||||
[x.id, x.student_name, x.group_id, x.description, x.photo_path ?? null, x.deleted_at ?? null, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of data.project_files || []) {
|
||||
@@ -234,6 +267,7 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
}
|
||||
}
|
||||
fs.rmSync(staging, { recursive: true, force: true });
|
||||
await sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -297,6 +331,7 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
if (l.student_name) { params.push(l.student_name); conditions.push(`e.student_name = $${params.length}`); }
|
||||
if (l.date_from) { params.push(l.date_from); conditions.push(`e.created_at >= $${params.length}::date`); }
|
||||
if (l.date_to) { params.push(l.date_to); conditions.push(`e.created_at < ($${params.length}::date + interval '1 day')`); }
|
||||
conditions.push('e.deleted_at IS NULL');
|
||||
const where = conditions.length ? ' WHERE ' + conditions.join(' AND ') : '';
|
||||
const { rows: entries } = await pool.query(
|
||||
`SELECT e.*, g.name AS group_name FROM entries e
|
||||
@@ -312,6 +347,15 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
fRes.rows.forEach(f => { (files[f.entry_id] = files[f.entry_id] || []).push({ token: f.token, name: f.name }); });
|
||||
}
|
||||
entries.forEach(r => { r.files = files[r.id] || []; });
|
||||
let photos = [];
|
||||
if (l.group_id) {
|
||||
const pRes = await pool.query(
|
||||
`SELECT id, photo_path, caption, taken_at, created_at FROM group_photos
|
||||
WHERE group_id = $1 ORDER BY taken_at DESC NULLS LAST, created_at DESC LIMIT 12`,
|
||||
[l.group_id]
|
||||
);
|
||||
photos = pRes.rows.map(r => ({ id: r.id, photo_path: r.photo_path, caption: r.caption, taken_at: r.taken_at, created_at: r.created_at }));
|
||||
}
|
||||
res.json({
|
||||
name: l.name,
|
||||
group_name: l.group_name,
|
||||
@@ -321,6 +365,7 @@ app.get('/api/share/:token', async (req, res) => {
|
||||
date_to: l.date_to,
|
||||
created_at: l.created_at,
|
||||
entries,
|
||||
photos,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -330,7 +375,16 @@ app.get('/s/:token', (req, res) => {
|
||||
|
||||
// --- Groups CRUD ---
|
||||
app.get('/api/groups', async (_, res) => {
|
||||
const { rows } = await pool.query('SELECT * FROM groups ORDER BY id');
|
||||
const { rows } = await pool.query(
|
||||
`SELECT g.*, gp.photo_path AS cover_path
|
||||
FROM groups g
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT photo_path FROM group_photos
|
||||
WHERE group_id = g.id
|
||||
ORDER BY taken_at DESC NULLS LAST, created_at DESC LIMIT 1
|
||||
) gp ON true
|
||||
ORDER BY g.id`
|
||||
);
|
||||
res.json(rows);
|
||||
});
|
||||
|
||||
@@ -384,10 +438,73 @@ app.post('/api/groups', requireAdmin, async (req, res) => {
|
||||
});
|
||||
|
||||
app.delete('/api/groups/:id', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM group_photos WHERE group_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.photo_path));
|
||||
await pool.query('DELETE FROM groups WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/groups/:id/photos', requireAdmin, async (req, res) => {
|
||||
const { limit, offset } = req.query;
|
||||
const { rows: crows } = await pool.query(
|
||||
'SELECT count(*)::int AS n FROM group_photos WHERE group_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT * FROM group_photos WHERE group_id = $1
|
||||
ORDER BY taken_at DESC NULLS LAST, created_at DESC`;
|
||||
const qparams = [req.params.id];
|
||||
const lim = parseInt(limit, 10);
|
||||
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
|
||||
const off = parseInt(offset, 10);
|
||||
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
|
||||
const { rows } = await pool.query(q, qparams);
|
||||
res.json({ photos: rows, total });
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos', requireAdmin, upload.single('photo'), async (req, res) => {
|
||||
const { caption, taken_at } = req.body;
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO group_photos (group_id, photo_path, caption, taken_at)
|
||||
VALUES ($1, $2, $3, $4) RETURNING *`,
|
||||
[req.params.id, `/uploads/${req.file.filename}`, caption?.trim() || null, taken_at || null]
|
||||
);
|
||||
res.status(201).json(rows[0]);
|
||||
} catch (e) {
|
||||
safeUnlink(`uploads/${req.file.filename}`);
|
||||
throw e;
|
||||
}
|
||||
});
|
||||
|
||||
app.put('/api/groups/:id/photos/:photoId', requireAdmin, async (req, res) => {
|
||||
const { caption, taken_at } = req.body;
|
||||
const { rows } = await pool.query(
|
||||
`UPDATE group_photos SET
|
||||
caption = $1,
|
||||
taken_at = $2
|
||||
WHERE id = $3 AND group_id = $4 RETURNING *`,
|
||||
[caption?.trim() || null, taken_at || null, req.params.photoId, req.params.id]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
res.json(rows[0]);
|
||||
});
|
||||
|
||||
app.delete('/api/groups/:id/photos/:photoId', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM group_photos WHERE id = $1 AND group_id = $2',
|
||||
[req.params.photoId, req.params.id]
|
||||
);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Не найдено' });
|
||||
safeUnlink(rows[0].photo_path);
|
||||
await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
// --- Students CRUD ---
|
||||
app.get('/api/students', async (_, res) => {
|
||||
const { rows } = await pool.query(
|
||||
@@ -464,9 +581,11 @@ app.delete('/api/students/:id', requireAdmin, async (req, res) => {
|
||||
|
||||
// --- Entries ---
|
||||
app.get('/api/entries', requireAdmin, async (req, res) => {
|
||||
const { group_id, date_from, date_to, student_name, search, limit, offset } = req.query;
|
||||
const { group_id, date_from, date_to, student_name, search, limit, offset, deleted } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
if (deleted === '1') conditions.push('e.deleted_at IS NOT NULL');
|
||||
else conditions.push('e.deleted_at IS NULL');
|
||||
if (group_id) { params.push(group_id); conditions.push(`e.group_id = $${params.length}`); }
|
||||
if (date_from) { params.push(date_from); conditions.push(`e.created_at >= $${params.length}::date`); }
|
||||
if (date_to) { params.push(date_to); conditions.push(`e.created_at < ($${params.length}::date + interval '1 day')`); }
|
||||
@@ -518,6 +637,7 @@ app.get('/api/files', requireAdmin, async (req, res) => {
|
||||
const { search, student_name, group_id, date_from, date_to, limit, offset } = req.query;
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
conditions.push('e.deleted_at IS NULL');
|
||||
if (search) { params.push(`%${search}%`); conditions.push(`pf.name ILIKE $${params.length}`); }
|
||||
if (student_name) { params.push(student_name); conditions.push(`e.student_name = $${params.length}`); }
|
||||
if (group_id) { params.push(group_id); conditions.push(`e.group_id = $${params.length}`); }
|
||||
@@ -559,14 +679,16 @@ app.get('/api/files/:token', async (req, res) => {
|
||||
});
|
||||
|
||||
app.get('/api/stats', requireAdmin, async (_, res) => {
|
||||
const [entries, groups, students, today] = await Promise.all([
|
||||
pool.query('SELECT count(*)::int AS n FROM entries'),
|
||||
const [entries, trash, groups, students, today] = await Promise.all([
|
||||
pool.query('SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NULL'),
|
||||
pool.query('SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NOT NULL'),
|
||||
pool.query('SELECT count(*)::int AS n FROM groups'),
|
||||
pool.query('SELECT count(DISTINCT student_name)::int AS n FROM entries'),
|
||||
pool.query("SELECT count(*)::int AS n FROM entries WHERE created_at >= now()::date"),
|
||||
pool.query('SELECT count(DISTINCT student_name)::int AS n FROM entries WHERE deleted_at IS NULL'),
|
||||
pool.query("SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NULL AND created_at >= now()::date"),
|
||||
]);
|
||||
res.json({
|
||||
entries: entries.rows[0].n,
|
||||
trash: trash.rows[0].n,
|
||||
groups: groups.rows[0].n,
|
||||
students: students.rows[0].n,
|
||||
today: today.rows[0].n,
|
||||
@@ -647,27 +769,60 @@ app.put('/api/entries/:id', requireAdmin, async (req, res) => {
|
||||
});
|
||||
|
||||
app.delete('/api/entries/:id', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
'SELECT photo_path FROM entries WHERE id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
if (rows[0]?.photo_path) {
|
||||
const fp = path.join(__dirname, rows[0].photo_path);
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
const fRes = await pool.query(
|
||||
'SELECT path FROM project_files WHERE entry_id = $1',
|
||||
[req.params.id]
|
||||
);
|
||||
for (const r of fRes.rows) {
|
||||
const fp = path.join(__dirname, r.path);
|
||||
if (fs.existsSync(fp)) fs.unlinkSync(fp);
|
||||
}
|
||||
await pool.query('DELETE FROM project_files WHERE entry_id = $1', [req.params.id]);
|
||||
await pool.query('UPDATE entries SET deleted_at = now() WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.put('/api/entries/:id/restore', requireAdmin, async (req, res) => {
|
||||
await pool.query('UPDATE entries SET deleted_at = NULL WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.delete('/api/entries/:id/permanent', requireAdmin, async (req, res) => {
|
||||
await removeEntryFiles(req.params.id);
|
||||
await pool.query('DELETE FROM entries WHERE id = $1', [req.params.id]);
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
app.get('/api/trash', requireAdmin, async (req, res) => {
|
||||
const { limit, offset } = req.query;
|
||||
const { rows: crows } = await pool.query(
|
||||
"SELECT count(*)::int AS n FROM entries WHERE deleted_at IS NOT NULL"
|
||||
);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT e.*, g.name AS group_name FROM entries e
|
||||
JOIN groups g ON g.id = e.group_id
|
||||
WHERE e.deleted_at IS NOT NULL ORDER BY e.deleted_at DESC`;
|
||||
const qparams = [];
|
||||
const lim = parseInt(limit, 10);
|
||||
if (lim > 0) { qparams.push(lim); q += ` LIMIT $${qparams.length}`; }
|
||||
const off = parseInt(offset, 10);
|
||||
if (off > 0) { qparams.push(off); q += ` OFFSET $${qparams.length}`; }
|
||||
const { rows } = await pool.query(q, qparams);
|
||||
let files = {};
|
||||
if (rows.length) {
|
||||
const fRes = await pool.query(
|
||||
'SELECT entry_id, token, name FROM project_files WHERE entry_id = ANY($1) ORDER BY id',
|
||||
[rows.map(r => r.id)]
|
||||
);
|
||||
fRes.rows.forEach(f => { (files[f.entry_id] = files[f.entry_id] || []).push(f); });
|
||||
}
|
||||
rows.forEach(r => { r.files = files[r.id] || []; });
|
||||
res.json({ entries: rows, total });
|
||||
});
|
||||
|
||||
app.delete('/api/trash', requireAdmin, async (req, res) => {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT photo_path AS p FROM entries WHERE deleted_at IS NOT NULL
|
||||
UNION ALL
|
||||
SELECT pf.path AS p FROM project_files pf
|
||||
JOIN entries e ON e.id = pf.entry_id WHERE e.deleted_at IS NOT NULL`
|
||||
);
|
||||
rows.forEach(r => safeUnlink(r.p));
|
||||
const d = await pool.query('DELETE FROM entries WHERE deleted_at IS NOT NULL');
|
||||
res.json({ ok: true, deleted: d.rowCount });
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
const HTTPS_PORT = process.env.HTTPS_PORT || 3443;
|
||||
|
||||
@@ -689,3 +844,5 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
||||
} else {
|
||||
console.log('HTTPS: no certs found, skipping');
|
||||
}
|
||||
|
||||
sweepOrphanedUploads().catch(err => console.error('Upload sweep:', err));
|
||||
|
||||
Reference in New Issue
Block a user