add face library: face recognition, student refs, manual assign
Сервис face-id (insightface/ArcFace) ищет лица на фото групп и записей, сравнивает их с эталонными фото учеников и предлагает привязки по процентам косинусного сходства. - face-id/: FastAPI-сервис /detect, /compare, /health, ленивая загрузка модели - таблицы photo_faces + student_face_refs, face_scanned_at в фото групп и записей - настройки: face_id_enabled, face_scan_on_upload, face_id_threshold - пересчёт привязок по всем фото rematchFaces(): считает по сохранённым эмбеддингам, сервис face-id не нужен; автозапуск после добавления эталона плюс кнопка в настройках - просмотрщик фото: рамки с процентом сходства, подсказка-кандидат, ручная привязка по всем группам - бэкап/restore, sweep сиротских файлов, удаление лиц вместе с фото
This commit is contained in:
@@ -1536,7 +1536,7 @@ async function removeEntryFiles(entryId) {
|
||||
async function sweepOrphanedUploads() {
|
||||
const dir = UPLOADS_DIR;
|
||||
try { fs.mkdirSync(dir, { recursive: true }); } catch {}
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }] = await Promise.all([
|
||||
const [{ rows: photos }, { rows: files }, { rows: gphotos }, { rows: gporiginals }, { rows: ephotos }, { rows: pendingJobs }, { rows: mphotos }, { rows: sphotos }, { rows: logos }, { rows: studentAvatars }, { rows: groupCovers }, { rows: originals }, { rows: jobBefore }, { rows: chatFiles }, { rows: bmarkPhotos }, { rows: faceRefs }] = 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'),
|
||||
@@ -1552,9 +1552,10 @@ async function sweepOrphanedUploads() {
|
||||
pool.query('SELECT before_path AS p FROM photo_jobs WHERE before_path IS NOT NULL'),
|
||||
pool.query('SELECT path AS p FROM chat_attachments'),
|
||||
pool.query('SELECT photo_path AS p FROM bookmarks WHERE photo_path IS NOT NULL'),
|
||||
pool.query('SELECT photo_path AS p FROM student_face_refs'),
|
||||
]);
|
||||
const refs = new Set();
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos].forEach(r => {
|
||||
[...photos, ...files, ...gphotos, ...gporiginals, ...ephotos, ...pendingJobs, ...mphotos, ...sphotos, ...logos, ...studentAvatars, ...groupCovers, ...originals, ...jobBefore, ...chatFiles, ...bmarkPhotos, ...faceRefs].forEach(r => {
|
||||
const key = storage.keyFromPath(r.p);
|
||||
if (key) refs.add(key);
|
||||
});
|
||||
@@ -1699,6 +1700,245 @@ async function ensurePhotoOriginalColumn() {
|
||||
await pool.query(`ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS photo_original_path VARCHAR(255)`);
|
||||
}
|
||||
|
||||
async function ensureFaceTables() {
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS student_face_refs (
|
||||
id SERIAL PRIMARY KEY,
|
||||
student_id INT NOT NULL REFERENCES students(id) ON DELETE CASCADE,
|
||||
photo_path VARCHAR(255) NOT NULL,
|
||||
embedding JSONB NOT NULL,
|
||||
det_score REAL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_student_face_refs_student ON student_face_refs(student_id)');
|
||||
await pool.query(`CREATE TABLE IF NOT EXISTS photo_faces (
|
||||
id SERIAL PRIMARY KEY,
|
||||
source_type VARCHAR(20) NOT NULL,
|
||||
source_id INT NOT NULL,
|
||||
photo_path VARCHAR(255) NOT NULL,
|
||||
bbox JSONB NOT NULL,
|
||||
embedding JSONB NOT NULL,
|
||||
det_score REAL DEFAULT 0,
|
||||
student_id INT REFERENCES students(id) ON DELETE SET NULL,
|
||||
confidence REAL DEFAULT 0,
|
||||
created_at TIMESTAMPTZ DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ DEFAULT now()
|
||||
)`);
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source ON photo_faces(source_type, source_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_student ON photo_faces(student_id)');
|
||||
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source_student ON photo_faces(source_type, source_id, student_id)');
|
||||
await pool.query('ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ');
|
||||
await pool.query('ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ');
|
||||
}
|
||||
|
||||
function faceIdConfigured() {
|
||||
return Boolean(String(process.env.FACE_ID_URL || '').trim());
|
||||
}
|
||||
|
||||
function faceIdUrl() {
|
||||
return String(process.env.FACE_ID_URL || '').trim().replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
async function faceIdDetect(key, refs) {
|
||||
if (!faceIdConfigured()) return null;
|
||||
const buf = await storage.getBuffer(key);
|
||||
if (!buf) return null;
|
||||
const form = new FormData();
|
||||
const name = String(key).split('/').pop() || 'photo.jpg';
|
||||
form.append('file', new Blob([buf]), name);
|
||||
const endpoint = refs && refs.length ? '/compare' : '/detect';
|
||||
if (refs && refs.length) form.append('refs', JSON.stringify(refs));
|
||||
const ctrl = new AbortController();
|
||||
const t = setTimeout(() => ctrl.abort(), FACE_ID_TIMEOUT_MS);
|
||||
try {
|
||||
const r = await fetch(faceIdUrl() + endpoint, { method: 'POST', body: form, signal: ctrl.signal });
|
||||
if (!r.ok) throw new Error(`face-id ${endpoint}: HTTP ${r.status}`);
|
||||
const data = await r.json();
|
||||
return Array.isArray(data.faces) ? data.faces : [];
|
||||
} finally {
|
||||
clearTimeout(t);
|
||||
}
|
||||
}
|
||||
|
||||
function cosineSimilarity(a, b) {
|
||||
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
|
||||
let dot = 0, na = 0, nb = 0;
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
const x = Number(a[i]) || 0;
|
||||
const y = Number(b[i]) || 0;
|
||||
dot += x * y; na += x * x; nb += y * y;
|
||||
}
|
||||
if (!na || !nb) return 0;
|
||||
return dot / (Math.sqrt(na) * Math.sqrt(nb));
|
||||
}
|
||||
|
||||
function faceThreshold(v) {
|
||||
const n = parseFloat(v);
|
||||
if (!Number.isFinite(n)) return 0.6;
|
||||
return Math.min(0.99, Math.max(0.3, n));
|
||||
}
|
||||
|
||||
function safeId(v) {
|
||||
const n = parseInt(v, 10);
|
||||
return Number.isFinite(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
async function loadFaceRefs() {
|
||||
try {
|
||||
const { rows } = await pool.query(
|
||||
`SELECT r.id, r.student_id, r.embedding, s.name AS student_name
|
||||
FROM student_face_refs r
|
||||
LEFT JOIN students s ON s.id = r.student_id
|
||||
WHERE s.deleted_at IS NULL`
|
||||
);
|
||||
return rows.filter(r => r.embedding && r.embedding.length)
|
||||
.map(r => ({ student_id: r.student_id, name: r.student_name || 'Ученик', emb: r.embedding }));
|
||||
} catch (e) {
|
||||
console.error('Face refs load failed:', e.message);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function matchFaceToStudent(embedding, refs, threshold) {
|
||||
let studentId = null;
|
||||
let best = 0;
|
||||
let bestId = null;
|
||||
let bestName = '';
|
||||
for (const ref of refs) {
|
||||
const score = cosineSimilarity(embedding, ref.emb);
|
||||
if (score > best) {
|
||||
best = score;
|
||||
bestId = ref.student_id;
|
||||
bestName = ref.name || '';
|
||||
}
|
||||
}
|
||||
if (bestId && best >= threshold) studentId = bestId;
|
||||
return { student_id: studentId, confidence: best, best_id: bestId, best_name: bestName };
|
||||
}
|
||||
|
||||
function bestFaceCandidate(embedding, refs) {
|
||||
const m = matchFaceToStudent(embedding, refs, Infinity);
|
||||
return { score: m.confidence, student_id: m.best_id, name: m.best_name };
|
||||
}
|
||||
|
||||
async function photoFaceGroupId(sourceType, sourceId) {
|
||||
if (sourceType === 'entry') {
|
||||
const { rows } = await pool.query('SELECT e.group_id FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]);
|
||||
return rows.length ? rows[0].group_id : null;
|
||||
}
|
||||
const { rows } = await pool.query('SELECT group_id FROM group_photos WHERE id = $1', [sourceId]);
|
||||
return rows.length ? rows[0].group_id : null;
|
||||
}
|
||||
|
||||
async function rematchFaces(opts = {}) {
|
||||
const threshold = faceThreshold(await getSetting('face_id_threshold', '0.6'));
|
||||
const refs = await loadFaceRefs();
|
||||
const batch = Math.min(2000, Math.max(100, safeId(opts.limit) || 1000));
|
||||
const client = await pool.connect();
|
||||
let scanned = 0;
|
||||
let matched = 0;
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
let lastId = 0;
|
||||
for (;;) {
|
||||
const { rows } = await client.query(
|
||||
'SELECT id, embedding FROM photo_faces WHERE student_id IS NULL AND id > $1 ORDER BY id LIMIT $2',
|
||||
[lastId, batch]
|
||||
);
|
||||
if (!rows.length) break;
|
||||
lastId = rows[rows.length - 1].id;
|
||||
scanned += rows.length;
|
||||
for (const r of rows) {
|
||||
const m = matchFaceToStudent(r.embedding, refs, threshold);
|
||||
if (!m.student_id) continue;
|
||||
await client.query(
|
||||
'UPDATE photo_faces SET student_id = $1, confidence = $2, updated_at = now() WHERE id = $3',
|
||||
[m.student_id, m.confidence, r.id]
|
||||
);
|
||||
matched++;
|
||||
}
|
||||
if (rows.length < batch) break;
|
||||
}
|
||||
await client.query('COMMIT');
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
console.error('Face rematch failed:', e.message);
|
||||
return { scanned, matched, threshold, error: e.message };
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
return { scanned, matched, threshold };
|
||||
}
|
||||
|
||||
async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
|
||||
if (!faceIdConfigured()) return null;
|
||||
const key = storage.keyFromPath(photoPath);
|
||||
if (!key) return null;
|
||||
let faces;
|
||||
try {
|
||||
faces = await faceIdDetect(key, null);
|
||||
} catch (e) {
|
||||
console.error(`Face detect failed (${sourceType} ${sourceId}):`, e.message);
|
||||
return null;
|
||||
}
|
||||
if (!faces) return null;
|
||||
const threshold = faceThreshold(await getSetting('face_id_threshold', '0.6'));
|
||||
const refs = opts.noMatch ? [] : await loadFaceRefs();
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
await client.query('DELETE FROM photo_faces WHERE source_type = $1 AND source_id = $2', [sourceType, sourceId]);
|
||||
for (const f of faces) {
|
||||
if (!Array.isArray(f.embedding) || !f.embedding.length) continue;
|
||||
const m = matchFaceToStudent(f.embedding, refs, threshold);
|
||||
const b = Array.isArray(f.bbox) ? f.bbox : [];
|
||||
await client.query(
|
||||
`INSERT INTO photo_faces (source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
|
||||
[sourceType, sourceId, photoPath, JSON.stringify({ x: b[0] || 0, y: b[1] || 0, w: b[2] || 0, h: b[3] || 0 }),
|
||||
JSON.stringify(f.embedding), Number(f.det_score) || 0, m.student_id, m.confidence]
|
||||
);
|
||||
}
|
||||
await client.query(
|
||||
sourceType === 'entry'
|
||||
? 'UPDATE entry_photos SET face_scanned_at = now() WHERE id = $1'
|
||||
: 'UPDATE group_photos SET face_scanned_at = now() WHERE id = $1',
|
||||
[sourceId]
|
||||
);
|
||||
await client.query('COMMIT');
|
||||
return faces.length;
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
console.error(`Face scan failed (${sourceType} ${sourceId}):`, e.message);
|
||||
return null;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function scanFacesBackground(sourceType, sourceId, photoPath) {
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
if ((await getSetting('face_id_enabled', 'false')) !== 'true') return;
|
||||
if ((await getSetting('face_scan_on_upload', 'true')) !== 'true') return;
|
||||
await scanFacesForPhoto(sourceType, sourceId, photoPath);
|
||||
} catch (e) {
|
||||
console.error('Face background scan failed:', e.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function rematchFacesBackground() {
|
||||
setImmediate(async () => {
|
||||
try {
|
||||
if ((await getSetting('face_id_enabled', 'false')) !== 'true') return;
|
||||
await rematchFaces();
|
||||
} catch (e) {
|
||||
console.error('Face background rematch failed:', e.message);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
async function ensureEntryAiColumns() {
|
||||
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS description_original TEXT`);
|
||||
await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS description_ai TEXT`);
|
||||
@@ -4136,6 +4376,12 @@ app.put('/api/settings', requireAdmin, async (req, res) => {
|
||||
return res.status(400).json({ error: 'notify_retention_days должен быть целым числом от 1 до 365' });
|
||||
}
|
||||
}
|
||||
if (key === 'face_id_threshold') {
|
||||
const n = parseFloat(String(value));
|
||||
if (!Number.isFinite(n) || n < 0.3 || n > 0.99) {
|
||||
return res.status(400).json({ error: 'Порог совпадения должен быть числом от 0.3 до 0.99' });
|
||||
}
|
||||
}
|
||||
if (key === 'lesson_ai_enabled' && !['true', 'false'].includes(String(value))) {
|
||||
return res.status(400).json({ error: 'lesson_ai_enabled должен быть true или false' });
|
||||
}
|
||||
@@ -4410,6 +4656,7 @@ const tar = require('tar');
|
||||
const os = require('os');
|
||||
const AI_URL = process.env.AI_URL || 'http://text-corrector:8080';
|
||||
const PHOTO_AI_URL = process.env.PHOTO_AI_URL || '';
|
||||
const FACE_ID_TIMEOUT_MS = Math.max(1000, parseInt(process.env.FACE_ID_TIMEOUT_MS || '30000', 10) || 30000);
|
||||
const PHOTO_AI_FACE_MODEL = process.env.PHOTO_AI_FACE_MODEL || 'gfpgan';
|
||||
const PHOTO_AI_FACE_TIMEOUT_MS = Math.max(1000, parseInt(process.env.PHOTO_AI_FACE_TIMEOUT_MS || '600000', 10) || 600000);
|
||||
const PHOTO_AI_DEFAULT_MODEL = 'x2plus';
|
||||
@@ -4652,7 +4899,7 @@ function sweepBackupStorage() {
|
||||
async function buildBackupArchive() {
|
||||
const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'wido-bk-'));
|
||||
try {
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm] = await Promise.all([
|
||||
const [g, s, e, st, pf, br, us, ub, gp, ep, md, sp, sl, pj, lr, lrv, al, nt, nr, bi, ct, cm, ca, sm, fb, uss, un, bm, sfr, pfcs] = await Promise.all([
|
||||
pool.query('SELECT * FROM groups ORDER BY id'),
|
||||
pool.query('SELECT * FROM students ORDER BY id'),
|
||||
pool.query('SELECT * FROM entries ORDER BY id'),
|
||||
@@ -4681,6 +4928,8 @@ async function buildBackupArchive() {
|
||||
pool.query('SELECT * FROM user_settings ORDER BY user_id, key'),
|
||||
pool.query('SELECT * FROM user_notes ORDER BY id'),
|
||||
pool.query('SELECT * FROM bookmarks ORDER BY id'),
|
||||
pool.query('SELECT * FROM student_face_refs ORDER BY id'),
|
||||
pool.query('SELECT * FROM photo_faces ORDER BY id'),
|
||||
]);
|
||||
const settings = {};
|
||||
st.rows.forEach(r => { settings[r.key] = r.value; });
|
||||
@@ -4698,8 +4947,9 @@ async function buildBackupArchive() {
|
||||
chat_threads: ct.rowCount, chat_messages: cm.rowCount, chat_attachments: ca.rowCount,
|
||||
short_messages: sm.rowCount, feedbacks: fb.rowCount, user_settings: uss.rowCount, user_notes: un.rowCount,
|
||||
bookmarks: bm.rowCount,
|
||||
student_face_refs: sfr.rowCount, photo_faces: pfcs.rowCount,
|
||||
},
|
||||
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows,
|
||||
groups: g.rows, students: s.rows, entries: e.rows, settings, project_files: pf.rows, branches: br.rows, users: us.rows, user_branches: ub.rows, group_photos: gp.rows, entry_photos: ep.rows, modules: md.rows, student_photos: sp.rows, share_links: sl.rows, photo_jobs: pj.rows, lesson_reports: lr.rows, lesson_report_versions: lrv.rows, audit_log: al.rows, notifications: nt.rows, notification_reads: nr.rows, banned_ips: bi.rows, chat_threads: ct.rows, chat_messages: cm.rows, chat_attachments: ca.rows, short_messages: sm.rows, feedbacks: fb.rows, user_settings: uss.rows, user_notes: un.rows, bookmarks: bm.rows, student_face_refs: sfr.rows, photo_faces: pfcs.rows,
|
||||
};
|
||||
fs.writeFileSync(path.join(staging, 'data.json'), JSON.stringify(payload));
|
||||
const files = await storage.downloadAll(path.join(staging, 'uploads'));
|
||||
@@ -4882,6 +5132,8 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
await client.query('DELETE FROM user_settings');
|
||||
await client.query('DELETE FROM user_notes');
|
||||
await client.query('DELETE FROM bookmarks');
|
||||
await client.query('DELETE FROM photo_faces');
|
||||
await client.query('DELETE FROM student_face_refs');
|
||||
await client.query('DELETE FROM users');
|
||||
await client.query('DELETE FROM branches');
|
||||
for (const x of ndata.branches) {
|
||||
@@ -4942,6 +5194,14 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
[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.student_face_refs || [])) {
|
||||
const ex = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
await client.query(
|
||||
'INSERT INTO student_face_refs (id, student_id, photo_path, embedding, det_score, created_at) VALUES ($1,$2,$3,$4::jsonb,$5,$6)',
|
||||
[x.id, x.student_id, x.photo_path, JSON.stringify(x.embedding || []), x.det_score || 0, x.created_at || null]
|
||||
);
|
||||
}
|
||||
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)',
|
||||
@@ -5003,6 +5263,21 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
|
||||
[x.id, x.entry_id, x.photo_path, x.caption, x.sort_order, x.created_at]
|
||||
);
|
||||
}
|
||||
for (const x of (ndata.photo_faces || [])) {
|
||||
const tbl = x.source_type === 'entry' ? 'entry_photos' : 'group_photos';
|
||||
const ex = await client.query(`SELECT 1 FROM ${tbl} WHERE id = $1`, [x.source_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
if (x.student_id != null) {
|
||||
const st = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
|
||||
if (!st.rowCount) continue;
|
||||
}
|
||||
await client.query(
|
||||
`INSERT INTO photo_faces (id, source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, created_at, updated_at)
|
||||
VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7,$8,$9,$10,$11)`,
|
||||
[x.id, x.source_type, x.source_id, x.photo_path, JSON.stringify(x.bbox || {}), JSON.stringify(x.embedding || []),
|
||||
x.det_score || 0, x.student_id, x.confidence || 0, x.created_at || null, x.updated_at || null]
|
||||
);
|
||||
}
|
||||
for (const x of ndata.student_photos) {
|
||||
const ex = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
|
||||
if (!ex.rowCount) continue;
|
||||
@@ -5594,6 +5869,14 @@ async function hardDeleteGroup(groupId) {
|
||||
[groupId]
|
||||
);
|
||||
const files = eres.rows.concat(gres.rows);
|
||||
await client.query(
|
||||
`DELETE FROM photo_faces WHERE source_type = 'group' AND source_id IN (SELECT id FROM group_photos WHERE group_id = $1)`,
|
||||
[groupId]
|
||||
);
|
||||
await client.query(
|
||||
`DELETE FROM photo_faces WHERE source_type = 'entry' AND source_id IN (SELECT ep.id FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE e.group_id = $1)`,
|
||||
[groupId]
|
||||
);
|
||||
await client.query('DELETE FROM group_photos WHERE group_id = $1', [groupId]);
|
||||
await client.query('DELETE FROM lesson_reports WHERE group_id = $1', [groupId]);
|
||||
await client.query('DELETE FROM entries WHERE group_id = $1', [groupId]);
|
||||
@@ -5757,21 +6040,53 @@ app.get('/api/groups/:id/photos', requireAuth, async (req, res) => {
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, req.params.id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
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 sort_order ASC, 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 });
|
||||
const { limit, offset, student_id, unassigned_faces } = req.query;
|
||||
try {
|
||||
const conds = ['gp.group_id = $1'];
|
||||
const fparams = [req.params.id];
|
||||
if (student_id) {
|
||||
fparams.push(safeId(student_id));
|
||||
conds.push(`EXISTS (SELECT 1 FROM photo_faces pf WHERE pf.source_type = 'group' AND pf.source_id = gp.id AND pf.student_id = $${fparams.length})`);
|
||||
}
|
||||
if (unassigned_faces === '1') {
|
||||
conds.push(`EXISTS (SELECT 1 FROM photo_faces pf WHERE pf.source_type = 'group' AND pf.source_id = gp.id AND pf.student_id IS NULL)`);
|
||||
}
|
||||
const where = ` WHERE ${conds.join(' AND ')}`;
|
||||
const { rows: crows } = await pool.query(
|
||||
`SELECT count(*)::int AS n FROM group_photos gp${where}`,
|
||||
fparams
|
||||
);
|
||||
const total = crows[0].n;
|
||||
let q = `SELECT gp.* FROM group_photos gp${where}
|
||||
ORDER BY gp.sort_order ASC, gp.taken_at DESC NULLS LAST, gp.created_at DESC`;
|
||||
const qparams = fparams.slice();
|
||||
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);
|
||||
const withFaces = await pool.query(
|
||||
`SELECT pf.source_id, count(*)::int AS faces,
|
||||
count(*) FILTER (WHERE pf.student_id IS NULL)::int AS unassigned
|
||||
FROM photo_faces pf
|
||||
WHERE pf.source_type = 'group' AND pf.source_id = ANY($1::int[])
|
||||
GROUP BY pf.source_id`,
|
||||
[rows.length ? rows.map(r => r.id) : [0]]
|
||||
);
|
||||
const faceMap = {};
|
||||
withFaces.rows.forEach(r => { faceMap[r.source_id] = { faces: r.faces, unassigned: r.unassigned }; });
|
||||
res.json({
|
||||
photos: rows.map(r => ({
|
||||
...r,
|
||||
face_count: faceMap[r.id] ? faceMap[r.id].faces : 0,
|
||||
face_unassigned: faceMap[r.id] ? faceMap[r.id].unassigned : 0,
|
||||
})),
|
||||
total,
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('GET /api/groups/:id/photos:', e);
|
||||
res.status(500).json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
const groupPhotoUpload = upload.single('photo');
|
||||
@@ -5811,6 +6126,7 @@ app.post('/api/groups/:id/photos', requireAuth, (req, res, next) => {
|
||||
invalidateGroups();
|
||||
invalidateStats();
|
||||
res.status(201).json(rows[0]);
|
||||
scanFacesBackground('group', rows[0].id, rows[0].photo_path);
|
||||
} catch (e) {
|
||||
safeUnlink(`uploads/${req.file.filename}`);
|
||||
console.error('POST /api/groups/:id/photos:', e);
|
||||
@@ -5893,6 +6209,7 @@ app.delete('/api/groups/:id/photos/:photoId', requireAuth, async (req, res) => {
|
||||
safeUnlink(rows[0].photo_path);
|
||||
if (rows[0].photo_original_path) safeUnlink(rows[0].photo_original_path);
|
||||
await pool.query('UPDATE groups SET cover_path = NULL WHERE id = $1 AND cover_path = $2', [req.params.id, rows[0].photo_path]);
|
||||
await pool.query("DELETE FROM photo_faces WHERE source_type = 'group' AND source_id = $1", [req.params.photoId]);
|
||||
await pool.query('DELETE FROM group_photos WHERE id = $1', [req.params.photoId]);
|
||||
await logAudit(req, 'group.photo.delete', { group_id: req.params.id, photo_id: req.params.photoId });
|
||||
invalidateShare();
|
||||
@@ -8085,13 +8402,310 @@ app.get('/api/files/:token', fileLimiter, async (req, res) => {
|
||||
}
|
||||
});
|
||||
|
||||
app.post('/api/students/:id/face-refs', requireAuth, (req, res, next) => {
|
||||
studentPhotoUpload(req, res, (err) => {
|
||||
if (err) return res.status(400).json({ error: 'Недопустимый файл' });
|
||||
next();
|
||||
});
|
||||
}, async (req, res) => {
|
||||
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
||||
if (!req.file) return res.status(400).json({ error: 'Файл обязателен' });
|
||||
let id;
|
||||
try {
|
||||
id = reqInt(req.params.id);
|
||||
} catch {
|
||||
removeUpload(req.file);
|
||||
return res.status(400).json({ error: 'Неверный id ученика' });
|
||||
}
|
||||
const acc = await studentProfileAccess(req.user, id);
|
||||
if (!acc.found) {
|
||||
removeUpload(req.file);
|
||||
return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
|
||||
}
|
||||
try {
|
||||
await convertPhoto(req.file);
|
||||
const faces = await faceIdDetect(req.file.filename, null);
|
||||
if (!faces) {
|
||||
removeUpload(req.file);
|
||||
return res.status(503).json({ error: 'Face-ID сервис недоступен' });
|
||||
}
|
||||
if (!faces.length) {
|
||||
removeUpload(req.file);
|
||||
return res.status(400).json({ error: 'Лицо не найдено на фото. Загрузите фото анфас' });
|
||||
}
|
||||
const best = faces.reduce((a, b) => ((b.det_score || 0) > (a.det_score || 0) ? b : a));
|
||||
const photoPath = `/uploads/${req.file.filename}`;
|
||||
const { rows } = await pool.query(
|
||||
`INSERT INTO student_face_refs (student_id, photo_path, embedding, det_score) VALUES ($1, $2, $3, $4) RETURNING id, student_id, photo_path, det_score, created_at`,
|
||||
[id, photoPath, JSON.stringify(best.embedding), Number(best.det_score) || 0]
|
||||
);
|
||||
await logAudit(req, 'student.face_ref.create', { student_id: id, ref_id: rows[0].id });
|
||||
res.status(201).json(rows[0]);
|
||||
rematchFacesBackground();
|
||||
} catch (e) {
|
||||
safeUnlink(`uploads/${req.file.filename}`);
|
||||
console.error('POST /api/students/:id/face-refs:', e);
|
||||
res.status(500).json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/students/:id/face-refs', 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 { rows } = await pool.query(
|
||||
'SELECT id, student_id, photo_path, det_score, created_at FROM student_face_refs WHERE student_id = $1 ORDER BY id',
|
||||
[id]
|
||||
);
|
||||
res.json({ refs: rows });
|
||||
});
|
||||
|
||||
app.delete('/api/students/:id/face-refs/:refId', requireAuth, 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 { rows } = await pool.query('SELECT photo_path FROM student_face_refs WHERE id = $1 AND student_id = $2', [refId, id]);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Референс не найден' });
|
||||
await pool.query('DELETE FROM student_face_refs WHERE id = $1 AND student_id = $2', [refId, id]);
|
||||
safeUnlink(rows[0].photo_path.replace(/^\/?uploads\//, 'uploads/'));
|
||||
await logAudit(req, 'student.face_ref.delete', { student_id: id, ref_id: refId });
|
||||
res.json({ ok: true });
|
||||
});
|
||||
|
||||
|
||||
app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res) => {
|
||||
const sourceType = req.params.sourceType === 'entry' ? 'entry' : 'group';
|
||||
let sourceId;
|
||||
try {
|
||||
sourceId = reqInt(req.params.sourceId);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id' });
|
||||
}
|
||||
let groupId = null;
|
||||
if (sourceType === 'group') {
|
||||
const { rows } = await pool.query('SELECT group_id FROM group_photos WHERE id = $1', [sourceId]);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
groupId = rows[0].group_id;
|
||||
} else {
|
||||
const { rows } = await pool.query('SELECT e.group_id FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
groupId = rows[0].group_id;
|
||||
}
|
||||
if (req.user.role !== 'admin' && groupId && !(await groupBelongsToBranches(req.user, groupId))) {
|
||||
return res.status(403).json({ error: 'Нет доступа' });
|
||||
}
|
||||
const { rows } = await pool.query(
|
||||
`SELECT pf.id, pf.bbox, pf.student_id, pf.confidence, pf.det_score, pf.embedding, s.name AS student_name
|
||||
FROM photo_faces pf
|
||||
LEFT JOIN students s ON s.id = pf.student_id
|
||||
WHERE pf.source_type = $1 AND pf.source_id = $2
|
||||
ORDER BY (pf.bbox->>'y')::int ASC, (pf.bbox->>'x')::int ASC`,
|
||||
[sourceType, sourceId]
|
||||
);
|
||||
const refs = await loadFaceRefs();
|
||||
res.json({
|
||||
faces: rows.map(r => {
|
||||
const best = r.student_id
|
||||
? { score: Number(r.confidence) || 0, student_id: r.student_id, name: r.student_name }
|
||||
: bestFaceCandidate(r.embedding, refs);
|
||||
return {
|
||||
id: r.id,
|
||||
x: r.bbox.x || 0, y: r.bbox.y || 0, w: r.bbox.w || 0, h: r.bbox.h || 0,
|
||||
student_id: r.student_id,
|
||||
student_name: r.student_name,
|
||||
confidence: Number(r.confidence) || 0,
|
||||
det_score: r.det_score,
|
||||
manual: r.student_id ? Number(r.confidence) >= 1 : false,
|
||||
best_score: best.score || 0,
|
||||
best_student_id: best.student_id || null,
|
||||
best_student_name: best.name || null,
|
||||
};
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/faces/rematch', requireAuth, requireAdmin, async (req, res) => {
|
||||
const out = await rematchFaces();
|
||||
await logAudit(req, 'faces.rematch', out);
|
||||
if (out.error) return res.status(500).json({ error: 'Не удалось пересчитать лица', detail: out.error });
|
||||
res.json(out);
|
||||
});
|
||||
|
||||
app.put('/api/photo-faces/:faceId/assign', requireAuth, async (req, res) => {
|
||||
let faceId;
|
||||
try {
|
||||
faceId = reqInt(req.params.faceId);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id' });
|
||||
}
|
||||
const studentId = safeId(req.body.student_id);
|
||||
if (studentId) {
|
||||
const chk = await pool.query('SELECT id, group_id FROM students WHERE id = $1 AND deleted_at IS NULL', [studentId]);
|
||||
if (!chk.rows.length) return res.status(400).json({ error: 'Ученик не найден' });
|
||||
if (req.user.role !== 'admin' && chk.rows[0].group_id && !(await groupBelongsToBranches(req.user, chk.rows[0].group_id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому ученику' });
|
||||
}
|
||||
}
|
||||
const { rows: chk } = await pool.query('SELECT id, student_id, source_type, source_id FROM photo_faces WHERE id = $1', [faceId]);
|
||||
if (!chk.length) return res.status(404).json({ error: 'Лицо не найдено' });
|
||||
const faceGroupId = await photoFaceGroupId(chk[0].source_type === 'entry' ? 'entry' : 'group', chk[0].source_id);
|
||||
if (!faceGroupId) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, faceGroupId))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этому фото' });
|
||||
}
|
||||
await pool.query('UPDATE photo_faces SET student_id = $1, confidence = 1, updated_at = now() WHERE id = $2', [studentId || null, faceId]);
|
||||
await logAudit(req, 'photo_face.assign', { face_id: faceId, student_id: studentId || null, was: chk[0].student_id });
|
||||
res.json({ ok: true, student_id: studentId || null });
|
||||
});
|
||||
|
||||
app.get('/api/students/:id/face-photos', 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 { rows } = await pool.query(
|
||||
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
|
||||
gp.group_id, e.id AS entry_ref, g.name AS group_name,
|
||||
COALESCE(gp.created_at, ep.created_at) AS created_at, pf.confidence
|
||||
FROM photo_faces pf
|
||||
LEFT JOIN group_photos gp ON gp.id = pf.source_id AND pf.source_type = 'group'
|
||||
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.source_type = 'entry'
|
||||
LEFT JOIN entries e ON e.id = ep.entry_id
|
||||
LEFT JOIN groups g ON g.id = COALESCE(gp.group_id, e.group_id)
|
||||
WHERE pf.student_id = $1
|
||||
ORDER BY pf.source_type, pf.source_id, COALESCE(gp.created_at, ep.created_at) DESC`,
|
||||
[id]
|
||||
);
|
||||
res.json({
|
||||
photos: rows.map(r => ({
|
||||
source_type: r.source_type,
|
||||
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
|
||||
path: r.photo_path,
|
||||
group_name: r.group_name,
|
||||
created_at: r.created_at,
|
||||
confidence: r.confidence,
|
||||
})),
|
||||
total: rows.length,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
app.post('/api/faces/scan-unscanned', requireAuth, requireAdmin, async (req, res) => {
|
||||
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
||||
const limit = Math.min(500, Math.max(1, safeId(req.body.limit) || 50));
|
||||
const g = await pool.query('SELECT id, photo_path FROM group_photos WHERE face_scanned_at IS NULL ORDER BY id LIMIT $1', [limit]);
|
||||
const e = await pool.query('SELECT id, photo_path FROM entry_photos WHERE face_scanned_at IS NULL ORDER BY id LIMIT $1', [limit]);
|
||||
let scanned = 0;
|
||||
let failed = 0;
|
||||
for (const p of g.rows) {
|
||||
const n = await scanFacesForPhoto('group', p.id, p.photo_path);
|
||||
if (n === null) failed++;
|
||||
else scanned++;
|
||||
}
|
||||
for (const p of e.rows) {
|
||||
const n = await scanFacesForPhoto('entry', p.id, p.photo_path);
|
||||
if (n === null) failed++;
|
||||
else scanned++;
|
||||
}
|
||||
await logAudit(req, 'faces.scan_unscanned', { scanned, failed, total: g.rows.length + e.rows.length });
|
||||
res.json({ scanned, failed, total: g.rows.length + e.rows.length });
|
||||
});
|
||||
|
||||
app.post('/api/entries/:id/photos/scan-faces', requireAuth, async (req, res) => {
|
||||
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
||||
let eid;
|
||||
try {
|
||||
eid = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id записи' });
|
||||
}
|
||||
const { rows: ent } = await pool.query('SELECT id, group_id FROM entries WHERE id = $1', [eid]);
|
||||
if (!ent.length) return res.status(404).json({ error: 'Запись не найдена' });
|
||||
if (req.user.role !== 'admin' && ent[0].group_id && !(await groupBelongsToBranches(req.user, ent[0].group_id))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой записи' });
|
||||
}
|
||||
const rescans = Boolean(req.body.rescan);
|
||||
const { rows } = await pool.query(
|
||||
rescans
|
||||
? 'SELECT id, photo_path FROM entry_photos WHERE entry_id = $1 ORDER BY id'
|
||||
: 'SELECT id, photo_path FROM entry_photos WHERE entry_id = $1 AND face_scanned_at IS NULL ORDER BY id',
|
||||
[eid]
|
||||
);
|
||||
let scanned = 0;
|
||||
let failed = 0;
|
||||
for (const p of rows) {
|
||||
const n = await scanFacesForPhoto('entry', p.id, p.photo_path);
|
||||
if (n === null) failed++;
|
||||
else scanned++;
|
||||
}
|
||||
await logAudit(req, 'entry.photos.scan_faces', { entry_id: eid, scanned, failed, rescans });
|
||||
res.json({ scanned, failed, total: rows.length });
|
||||
});
|
||||
|
||||
app.post('/api/groups/:id/photos/scan-faces', requireAuth, async (req, res) => {
|
||||
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
|
||||
let gid;
|
||||
try {
|
||||
gid = reqInt(req.params.id);
|
||||
} catch {
|
||||
return res.status(400).json({ error: 'Неверный id группы' });
|
||||
}
|
||||
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, gid))) {
|
||||
return res.status(403).json({ error: 'Нет доступа к этой группе' });
|
||||
}
|
||||
const rescans = Boolean(req.body.rescan);
|
||||
const { rows } = await pool.query(
|
||||
rescans
|
||||
? 'SELECT id, photo_path FROM group_photos WHERE group_id = $1 ORDER BY id'
|
||||
: 'SELECT id, photo_path FROM group_photos WHERE group_id = $1 AND face_scanned_at IS NULL ORDER BY id',
|
||||
[gid]
|
||||
);
|
||||
let scanned = 0;
|
||||
let failed = 0;
|
||||
for (const p of rows) {
|
||||
const n = await scanFacesForPhoto('group', p.id, p.photo_path);
|
||||
if (n === null) failed++;
|
||||
else scanned++;
|
||||
}
|
||||
await logAudit(req, 'group.photos.scan_faces', { group_id: gid, scanned, failed, rescans });
|
||||
res.json({ scanned, failed, total: rows.length });
|
||||
});
|
||||
|
||||
|
||||
app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
const { search, student_name, group_id, date_from, date_to, limit, offset } = req.query;
|
||||
const { search, student_name, group_id, date_from, date_to, student_id, unassigned_faces, limit, offset } = req.query;
|
||||
try {
|
||||
const conditions = [];
|
||||
const params = [];
|
||||
if (search) { params.push(`%${search}%`); conditions.push(`t.title ILIKE $${params.length}`); }
|
||||
if (student_name) { params.push(student_name); conditions.push(`t.student_name = $${params.length}`); }
|
||||
if (group_id) { params.push(group_id); conditions.push(`t.group_id = $${params.length}`); }
|
||||
if (student_id) {
|
||||
params.push(safeId(student_id));
|
||||
conditions.push(`EXISTS (SELECT 1 FROM photo_faces pf WHERE pf.student_id = $${params.length}
|
||||
AND ((t.source_type = 'group_photo' AND pf.source_type = 'group' AND pf.photo_path = t.path)
|
||||
OR (t.source_type = 'entry_photo' AND pf.source_type = 'entry' AND pf.photo_path = t.path)))`);
|
||||
}
|
||||
if (unassigned_faces === '1') {
|
||||
conditions.push(`EXISTS (SELECT 1 FROM photo_faces pf WHERE pf.student_id IS NULL
|
||||
AND ((t.source_type = 'group_photo' AND pf.source_type = 'group' AND pf.photo_path = t.path)
|
||||
OR (t.source_type = 'entry_photo' AND pf.source_type = 'entry' AND pf.photo_path = t.path)))`);
|
||||
}
|
||||
if (date_from) { params.push(date_from); conditions.push(`t.created_at >= ${tzDayStart(params.length)}`); }
|
||||
if (date_to) { params.push(date_to); conditions.push(`t.created_at < ${tzDayEnd(params.length)}`); }
|
||||
if (req.user.role !== 'admin') {
|
||||
@@ -8166,6 +8780,10 @@ app.get('/api/photos', requireAuth, async (req, res) => {
|
||||
created_at: r.created_at
|
||||
}));
|
||||
res.json({ photos, total });
|
||||
} catch (e) {
|
||||
console.error('GET /api/photos:', e);
|
||||
res.status(500).json({ error: e.message });
|
||||
}
|
||||
});
|
||||
|
||||
app.get('/api/stats', requireAuth, async (req, res) => {
|
||||
@@ -8516,6 +9134,13 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
|
||||
invalidateStats();
|
||||
broadcastEntryChanged();
|
||||
res.status(201).json({ ...rows[0], files: projectFiles.length, photos: photos.length });
|
||||
for (let i = 0; i < photos.length; i++) {
|
||||
const { rows: ep } = await pool.query(
|
||||
'SELECT id FROM entry_photos WHERE entry_id = $1 AND photo_path = $2 ORDER BY sort_order LIMIT 1',
|
||||
[rows[0].id, `/uploads/${photos[i].filename}`]
|
||||
);
|
||||
if (ep.length) scanFacesBackground('entry', ep[0].id, `/uploads/${photos[i].filename}`);
|
||||
}
|
||||
} catch (e) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
photos.forEach(removeUpload);
|
||||
@@ -8666,6 +9291,7 @@ app.delete('/api/entries/:id/photos/:photoId', requireAuth, async (req, res) =>
|
||||
const { rows } = await pool.query('SELECT photo_path, sort_order FROM entry_photos WHERE id = $1 AND entry_id = $2', [req.params.photoId, req.params.id]);
|
||||
if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' });
|
||||
const { photo_path: photoPath, sort_order: photoSort } = rows[0];
|
||||
await pool.query("DELETE FROM photo_faces WHERE source_type = 'entry' AND source_id = $1", [req.params.photoId]);
|
||||
await pool.query('DELETE FROM entry_photos WHERE id = $1 AND entry_id = $2', [req.params.photoId, req.params.id]);
|
||||
safeUnlink(photoPath);
|
||||
await pool.query('UPDATE entry_photos SET sort_order = sort_order - 1 WHERE entry_id = $1 AND sort_order > $2', [req.params.id, photoSort]);
|
||||
@@ -10461,6 +11087,7 @@ if (fs.existsSync(certPath) && fs.existsSync(keyPath)) {
|
||||
try { await ensureEntryPhotosTable(); } catch (err) { console.error('Entry photos table:', err); }
|
||||
try { await ensureStudentPhotosTable(); } catch (err) { console.error('Student photos table:', err); }
|
||||
try { await ensurePhotoOriginalColumn(); } catch (err) { console.error('Entry original photo column:', err); }
|
||||
try { await ensureFaceTables(); } catch (err) { console.error('Face tables:', err); }
|
||||
try { await ensureEntryAiColumns(); } catch (err) { console.error('Entry AI columns:', err); }
|
||||
try { await ensurePhotoJobsTable(); } catch (err) { console.error('Photo jobs table:', err); }
|
||||
try { await ensureLessonReportsTable(); } catch (err) { console.error('Lesson reports table:', err); }
|
||||
|
||||
Reference in New Issue
Block a user