diff --git a/lib/photo-cleanup.js b/lib/photo-cleanup.js new file mode 100644 index 0000000..891ab04 --- /dev/null +++ b/lib/photo-cleanup.js @@ -0,0 +1,60 @@ +'use strict'; + +const FACE_REF_TABLES = ['student_face_refs', 'photo_faces']; + +function isFaceTable(table) { + return FACE_REF_TABLES.includes(table); +} + +async function findBrokenFaceRefs(pool, storage, { studentId, limit } = {}) { + const results = []; + for (const table of FACE_REF_TABLES) { + let sql; + const params = []; + if (table === 'student_face_refs') { + sql = `SELECT id, photo_path, student_id FROM student_face_refs WHERE photo_path IS NOT NULL AND photo_path <> ''`; + if (studentId) { + sql += ` AND student_id = $${params.length + 1}`; + params.push(studentId); + } + } else { + sql = `SELECT id, photo_path, student_id FROM photo_faces WHERE photo_path IS NOT NULL AND photo_path <> ''`; + if (studentId) { + sql += ` AND student_id = $${params.length + 1}`; + params.push(studentId); + } + } + sql += ` ORDER BY id`; + if (limit) { + sql += ` LIMIT $${params.length + 1}`; + params.push(limit); + } + const { rows } = await pool.query(sql, params); + for (const row of rows) { + const key = storage.keyFromPath(row.photo_path); + if (!key) continue; + const exists = await storage.exists(key); + if (!exists) { + results.push({ table, id: row.id, photo_path: row.photo_path, student_id: row.student_id }); + } + } + } + return results; +} + +async function deleteFaceRef(pool, storage, { table, id }) { + if (!isFaceTable(table)) { + throw new Error('Недопустимая таблица'); + } + const { rows } = await pool.query( + `DELETE FROM ${table} WHERE id = $1 RETURNING id, photo_path`, + [id] + ); + return rows[0] || null; +} + +module.exports = { + findBrokenFaceRefs, + deleteFaceRef, + FACE_REF_TABLES, +}; diff --git a/public/js/student.js b/public/js/student.js index d4d7256..9ec1e6b 100644 --- a/public/js/student.js +++ b/public/js/student.js @@ -6,6 +6,8 @@ let activeTab = 'entries'; let facesLoaded = false; let facesData = null; + let brokenFaces = null; + let brokenFacesLoaded = false; let achTypes = []; let achTypesLoaded = false; let achEditId = null; @@ -229,6 +231,16 @@ return `
${photoTile(f.path, 'sp-photo', f.photo_original_path)}
${esc(f.group_name || '')}${cap ? ` · ${esc(cap)}` : ''}
`; }).join('')}`; } + const broken = (brokenFaces && brokenFaces.broken) || []; + if (broken.length) { + const admin = typeof isAdmin === 'function' && isAdmin(); + html += `
Битые ссылки на фото (${broken.length}) — файл не найден
${broken.map(f => { + return `
${esc(f.photo_path)}
${esc(f.group_name || '')} · ${f.table === 'student_face_refs' ? 'эталон лица' : 'найденное лицо'}${admin ? ` ` : ''}
`; + }).join('')}
`; + if (admin) { + html += `
`; + } + } if (!html) html = emptyHtml('Фото с распознанным лицом не найдены'); return html; } @@ -243,6 +255,9 @@ loadFaces(); return; } + if (!brokenFacesLoaded) { + loadBrokenFaces(); + } pane.innerHTML = facesHtml(); } else if (activeTab === 'entries') { pane.innerHTML = entriesHtml(); @@ -271,6 +286,17 @@ if (activeTab === 'faces') renderPane(); } + async function loadBrokenFaces() { + try { + const res = await fetch(`${API}/api/students/${studentId}/faces/broken`, { headers: hdr() }); + brokenFaces = res.ok ? await res.json() : { broken: [], total: 0 }; + } catch { + brokenFaces = { broken: [], total: 0 }; + } + brokenFacesLoaded = true; + if (activeTab === 'faces') renderPane(); + } + function achItemHtml(a) { return `
@@ -494,7 +520,7 @@
`; - page.addEventListener('click', e => { + page.addEventListener('click', async e => { const g = e.target.closest('[data-tab],[data-goto]'); if (!g) return; const tab = g.dataset.tab || g.dataset.goto; @@ -504,6 +530,46 @@ renderPane(); } }); + page.addEventListener('click', async e => { + const del = e.target.closest('[data-broken-del]'); + if (del) { + const parts = del.dataset.brokenDel.split(':'); + const table = parts[0]; + const id = parseInt(parts[1], 10); + if (!confirm(`Удалить битую ссылку на фото «${table}:${id}»?`)) return; + try { + const url = table === 'student_face_refs' + ? `${API}/api/students/${studentId}/face-refs/${id}/broken` + : `${API}/api/photo-faces/${id}/broken`; + const res = await fetch(url, { method: 'DELETE', headers: hdr() }); + if (!res.ok) throw new Error('delete failed'); + showToast('Битую ссылку удалено'); + brokenFacesLoaded = false; + if (activeTab === 'faces') renderPane(); + } catch { + showToast('Не удалось удалить битую ссылку', true); + } + return; + } + const clear = e.target.closest('#spBrokenClearBtn'); + if (clear) { + if (!confirm(`Удалить все битые ссылки на фото этого ученика (${brokenFaces.total})?`)) return; + try { + const res = await fetch(`${API}/api/faces/cleanup`, { + method: 'POST', + headers: { ...hdr(), 'Content-Type': 'application/json' }, + body: JSON.stringify({ student_id: studentId, limit: 5000 }), + }); + const d = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(d.error || 'cleanup failed'); + showToast(`Удалено битых ссылок: ${d.deleted || 0}`); + brokenFacesLoaded = false; + if (activeTab === 'faces') renderPane(); + } catch { + showToast('Не удалось выполнить пакетную очистку', true); + } + } + }); document.getElementById('spDownloadBtn').addEventListener('click', downloadProfile); renderTabs(); renderPane(); diff --git a/public/student.html b/public/student.html index d4a6beb..fdc5fed 100644 --- a/public/student.html +++ b/public/student.html @@ -90,6 +90,10 @@ .sp-face{display:flex;flex-direction:column;gap:6px;min-width:0;margin:0} .sp-face-cap{font-size:.75rem;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .sp-face-cap b{color:var(--accent);font-weight:600} + .sp-face-broken{border:1px solid var(--danger);background:rgba(239,68,68,.06)} + .sp-broken-tile{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:8px;aspect-ratio:1;border-radius:13px;overflow:hidden;border:1px solid var(--border);background:var(--bg);padding:10px} + .sp-broken-icon{width:42px;height:42px;border-radius:10px;background:rgba(239,68,68,.12);color:#ef4444;display:flex;align-items:center;justify-content:center;font-size:20px} + .sp-broken-name{font-size:.68rem;color:#ef4444;text-align:center;overflow:hidden;text-overflow:ellipsis;max-width:140px} .sp-loading{display:flex;align-items:center;justify-content:center;gap:10px;color:var(--muted);padding:60px 16px} .sp-loading svg{width:20px;height:20px;animation:spin 1s linear infinite} .sp-error{text-align:center;padding:60px 16px;color:#ef4444} diff --git a/server.js b/server.js index ea8af34..07d3f54 100644 --- a/server.js +++ b/server.js @@ -67,6 +67,7 @@ const { lessonReportWriteBlocked } = require('./lib/lesson-reports'); const { groupOwnedBy } = require('./lib/groups'); const { ensureProjectFileSizeColumn, backfillProjectFileSizes } = require('./lib/file-sizes'); const { resolveImgbbEndpoint, friendlyApiError } = require('./lib/feedback-imgbb'); +const { findBrokenFaceRefs, deleteFaceRef } = require('./lib/photo-cleanup'); const { ensureDocsTables, docsTree, @@ -11786,6 +11787,79 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => { }); }); +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 } }); +}); + +app.delete('/api/photo-faces/:faceId/broken', requireAuth, requireAdmin, async (req, res) => { + let faceId; + try { + faceId = reqInt(req.params.faceId); + } catch { + return res.status(400).json({ error: 'Неверный id лица' }); + } + const { rows } = await pool.query('SELECT student_id, photo_path FROM photo_faces WHERE id = $1', [faceId]); + if (!rows.length) { + return res.status(404).json({ error: 'Лицо не найдено' }); + } + const acc = await studentProfileAccess(req.user, rows[0].student_id); + if (!acc.found) { + return res.status(acc.forbidden ? 403 : 404).json({ error: 'Нет доступа к этому ученику' }); + } + const deleted = await deleteFaceRef(pool, storage, { table: 'photo_faces', id: faceId }); + await logAudit(req, 'photo_face.delete_broken', { face_id: faceId, student_id: rows[0].student_id, photo_path: deleted.photo_path }); + res.json({ ok: true, deleted: { id: deleted.id, photo_path: deleted.photo_path } }); +}); + +app.post('/api/faces/cleanup', requireAuth, requireAdmin, async (req, res) => { + const studentId = req.body.student_id ? reqInt(req.body.student_id) : null; + const limit = Math.min(5000, Math.max(1, safeId(req.body.limit) || 500)); + const broken = await findBrokenFaceRefs(pool, storage, { studentId, limit }); + let deleted = 0; + const errors = []; + for (const item of broken) { + try { + await deleteFaceRef(pool, storage, { table: item.table, id: item.id }); + deleted++; + } catch (e) { + errors.push({ table: item.table, id: item.id, error: e.message }); + } + } + await logAudit(req, 'faces.cleanup_broken', { student_id: studentId || null, deleted, total: broken.length, errors: errors.length }); + res.json({ deleted, total: broken.length, errors }); +}); app.post('/api/faces/scan-unscanned', requireAuth, requireAdmin, async (req, res) => { if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });