Implement photo-related enhancements and chat updates

This commit is contained in:
dev
2026-10-28 09:01:49 +03:00
parent 12034812ec
commit 617ed60e65
10 changed files with 567 additions and 102 deletions
+150 -56
View File
@@ -334,6 +334,7 @@ const NOTIFY_TYPES = {
'face.scan.done': { label: 'Найдены лица на фото', hint: 'Фоновая проверка нашла лица на загруженном фото. Сколько именно — в тексте уведомления', icon: 'scan-face', level: 'info', enabled: false, admin: false },
'face.recognized': { label: 'Ученики распознаны на фото', hint: 'Фоновая проверка сопоставила лица с эталонами и назвала учеников', icon: 'user-round-check', level: 'info', enabled: true, admin: false },
'face.scan.error': { label: 'Ошибка проверки лиц', hint: 'Сервис face-id недоступен или очередь проверки исчерпала попытки', icon: 'scan-search', level: 'warning', enabled: true, admin: false },
'chat.message': { label: 'Новое сообщение в чате', hint: 'Тьютор написал в личный чат администрации', icon: 'bell', level: 'info', enabled: true, admin: true },
};
function notifySettingKey(type) {
@@ -569,16 +570,21 @@ function chatUploadFilter(req, file, cb) {
async function ensureChatTables() {
await pool.query(`CREATE TABLE IF NOT EXISTS chat_threads (
id SERIAL PRIMARY KEY,
tutor_id INT NOT NULL UNIQUE REFERENCES users(id) ON DELETE CASCADE,
tutor_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
peer_id INT REFERENCES users(id) ON DELETE CASCADE,
last_message_at TIMESTAMPTZ DEFAULT now(),
last_message_text VARCHAR(300),
tutor_unread INT NOT NULL DEFAULT 0,
admin_unread INT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now()
created_at TIMESTAMPTZ DEFAULT now(),
UNIQUE (tutor_id, peer_id)
)`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_chat_threads_last_message ON chat_threads(last_message_at DESC)`);
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS deleted_at TIMESTAMPTZ');
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS purge_at TIMESTAMPTZ');
await pool.query('ALTER TABLE chat_threads DROP CONSTRAINT IF EXISTS chat_threads_tutor_id_key');
await pool.query('ALTER TABLE chat_threads ADD COLUMN IF NOT EXISTS peer_id INT REFERENCES users(id) ON DELETE CASCADE');
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_chat_threads_pair ON chat_threads (tutor_id, peer_id)');
await pool.query(`CREATE TABLE IF NOT EXISTS chat_messages (
id SERIAL PRIMARY KEY,
thread_id INT NOT NULL REFERENCES chat_threads(id) ON DELETE CASCADE,
@@ -866,7 +872,7 @@ async function sendImageThumb(res, key) {
}
}
app.get('/uploads/thumb/:name', fileLimiter, async (req, res) => {
app.get('/uploads/thumb/:name', async (req, res) => {
const name = req.params.name;
if (!/^[A-Za-z0-9._-]+$/.test(name)) return res.status(400).end();
return sendImageThumb(res, name);
@@ -3042,10 +3048,11 @@ app.delete('/api/notifications', requireAdmin, async (req, res) => {
const CHAT_CHANNEL = 'whatido:chat';
const chatClients = new Set();
function chatVisible(user, tutorId) {
function chatVisible(user, a, b) {
if (!user) return false;
if (user.role === 'admin') return true;
return Number(user.id) === Number(tutorId);
const id = Number(user.id);
return id === Number(a) || (b != null && id === Number(b));
}
function writeChatFrame(client, event, data) {
@@ -3063,20 +3070,24 @@ cache.on(CHAT_CHANNEL, async message => {
try { payload = JSON.parse(message); } catch (e) { return; }
if (!payload || !payload.thread_id) return;
const event = CHAT_EVENTS.has(payload.type) ? payload.type : 'message';
const tutorId = payload.tutor_id === null || payload.tutor_id === undefined
? (await chatThreadTutor(payload.thread_id))
: payload.tutor_id;
if (tutorId === null) return;
let tutorId = payload.tutor_id;
let peerId = payload.peer_id;
if (tutorId === undefined || peerId === undefined) {
const t = await chatThreadParticipants(payload.thread_id);
tutorId = t ? t.tutor_id : null;
peerId = t ? t.peer_id : null;
}
if (tutorId === null && peerId === null) return;
for (const client of [...chatClients]) {
if (!chatVisible(client.user, tutorId)) continue;
if (!chatVisible(client.user, tutorId, peerId)) continue;
try { writeChatFrame(client, event, payload); } catch (e) { chatClients.delete(client); }
}
});
async function chatThreadTutor(threadId) {
async function chatThreadParticipants(threadId) {
try {
const { rows } = await pool.query('SELECT tutor_id FROM chat_threads WHERE id = $1', [threadId]);
return rows.length ? rows[0].tutor_id : null;
const { rows } = await pool.query('SELECT tutor_id, peer_id FROM chat_threads WHERE id = $1', [threadId]);
return rows.length ? { tutor_id: rows[0].tutor_id, peer_id: rows[0].peer_id } : null;
} catch (e) {
return null;
}
@@ -3104,15 +3115,17 @@ async function chatThreadFor(user, threadId) {
const id = parseInt(threadId, 10);
if (!Number.isInteger(id) || id < 1) return { error: 400, message: 'Invalid thread' };
const { rows } = await pool.query(
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at,
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at,
t.deleted_at,
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
LEFT JOIN users p ON p.id = t.peer_id
WHERE t.id = $1`,
[id]
);
if (!rows.length) return { error: 404, message: 'Диалог не найден' };
if (user.role !== 'admin' && rows[0].tutor_id !== user.id) return { error: 403, message: 'Нет доступа к диалогу' };
if (user.role !== 'admin' && rows[0].tutor_id !== user.id && rows[0].peer_id !== user.id) return { error: 403, message: 'Нет доступа к диалогу' };
return { thread: rows[0] };
}
@@ -3169,9 +3182,13 @@ function chatThreadJson(t, unread) {
return {
id: t.id,
tutor_id: t.tutor_id,
peer_id: t.peer_id || null,
tutor_username: t.tutor_username,
tutor_name: t.tutor_name || t.tutor_username,
tutor_active: t.tutor_active !== false,
peer_username: t.peer_username || null,
peer_name: (t.peer_name || t.peer_username) || null,
peer_active: t.peer_active !== false,
last_message_at: t.last_message_at,
last_message_text: t.last_message_text || '',
unread: unread === undefined ? 0 : unread,
@@ -3182,37 +3199,55 @@ function chatThreadJson(t, unread) {
async function chatUnread(user) {
if (user.role === 'admin') {
const { rows } = await pool.query('SELECT COALESCE(SUM(admin_unread), 0)::int AS n FROM chat_threads WHERE deleted_at IS NULL');
const { rows } = await pool.query(
`SELECT COALESCE(SUM(CASE WHEN tutor_id = $1 THEN tutor_unread ELSE admin_unread END), 0)::int AS n
FROM chat_threads WHERE deleted_at IS NULL AND (tutor_id = $1 OR peer_id = $1 OR peer_id IS NULL)`,
[user.id]
);
return rows[0] ? rows[0].n : 0;
}
const { rows } = await pool.query('SELECT tutor_unread AS n FROM chat_threads WHERE tutor_id = $1', [user.id]);
return rows.length ? rows[0].n : 0;
const { rows } = await pool.query(
`SELECT COALESCE(SUM(CASE WHEN tutor_id = $1 THEN tutor_unread ELSE admin_unread END), 0)::int AS n
FROM chat_threads WHERE deleted_at IS NULL AND (tutor_id = $1 OR peer_id = $1)`,
[user.id]
);
return rows[0] ? rows[0].n : 0;
}
app.get('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
try {
const isAdmin = req.user.role === 'admin';
const showDeleted = isAdmin && (req.query.deleted === '1' || req.query.deleted === 'true');
const peerJoin = `LEFT JOIN users p ON p.id = t.peer_id`;
const { rows } = isAdmin
? await pool.query(
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.admin_unread, t.created_at, t.deleted_at,
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.admin_unread, t.tutor_unread, t.created_at, t.deleted_at,
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
${peerJoin}
WHERE t.deleted_at IS ${showDeleted ? 'NOT NULL' : 'NULL'}
ORDER BY COALESCE(t.last_message_at, t.created_at) DESC`
)
: await pool.query(
`SELECT t.id, t.tutor_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.created_at, t.deleted_at,
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active
`SELECT t.id, t.tutor_id, t.peer_id, t.last_message_at, t.last_message_text, t.tutor_unread, t.admin_unread, t.created_at, t.deleted_at,
u.username AS tutor_username, u.name AS tutor_name, u.is_active AS tutor_active,
p.username AS peer_username, p.name AS peer_name, p.is_active AS peer_active
FROM chat_threads t JOIN users u ON u.id = t.tutor_id
WHERE t.tutor_id = $1`,
${peerJoin}
WHERE (t.tutor_id = $1 OR t.peer_id = $1) AND t.deleted_at IS NULL`,
[req.user.id]
);
const hidden = isAdmin && !showDeleted
? (await pool.query('SELECT COUNT(*)::int AS n FROM chat_threads WHERE deleted_at IS NOT NULL')).rows[0].n
: 0;
res.json({
items: rows.map(t => chatThreadJson(t, isAdmin ? t.admin_unread : t.tutor_unread)),
items: rows.map(t => {
const unread = isAdmin
? t.admin_unread
: (Number(req.user.id) === Number(t.tutor_id) ? t.tutor_unread : t.admin_unread);
return chatThreadJson(t, unread);
}),
unread: await chatUnread(req.user),
hidden,
hidden_mode: !!showDeleted,
@@ -3224,19 +3259,34 @@ app.get('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
app.post('/api/chat/threads', requireAuth, chatLimiter, async (req, res) => {
try {
let tutorId = req.user.id;
if (req.user.role === 'admin') {
const wanted = parseInt(req.body?.user_id, 10);
if (!Number.isInteger(wanted) || wanted < 1) return res.status(400).json({ error: 'Некорректный пользователь' });
const { rows } = await pool.query('SELECT id FROM users WHERE id = $1', [wanted]);
let recipientId = null;
const wanted = req.body?.user_id;
if (wanted !== undefined && wanted !== null && wanted !== '') {
const w = parseInt(wanted, 10);
if (!Number.isInteger(w) || w < 1) return res.status(400).json({ error: 'Некорректный пользователь' });
const { rows } = await pool.query('SELECT id FROM users WHERE id = $1 AND is_active IS NOT FALSE', [w]);
if (!rows.length) return res.status(404).json({ error: 'Пользователь не найден' });
tutorId = rows[0].id;
recipientId = w;
} else {
// default recipient: an admin (for tutors creating "chat with admins")
const { rows } = await pool.query("SELECT id FROM users WHERE role = 'admin' AND is_active IS NOT FALSE ORDER BY id LIMIT 1");
if (!rows.length) return res.status(404).json({ error: 'Нет доступного собеседника' });
recipientId = rows[0].id;
if (recipientId === req.user.id) {
// self is the only admin; allow self-thread? reject instead
const { rows: r2 } = await pool.query("SELECT id FROM users WHERE id <> $1 AND is_active IS NOT FALSE ORDER BY id LIMIT 1", [req.user.id]);
if (!r2.length) return res.status(400).json({ error: 'Нет доступного собеседника' });
recipientId = r2[0].id;
}
}
const a = Math.min(req.user.id, recipientId);
const b = Math.max(req.user.id, recipientId);
// tutor_id = a (participant A), peer_id = b (participant B)
const { rows: ins } = await pool.query(
`INSERT INTO chat_threads (tutor_id) VALUES ($1)
ON CONFLICT (tutor_id) DO UPDATE SET tutor_id = EXCLUDED.tutor_id
`INSERT INTO chat_threads (tutor_id, peer_id) VALUES ($1, $2)
ON CONFLICT (tutor_id, peer_id) DO UPDATE SET tutor_id = EXCLUDED.tutor_id
RETURNING id`,
[tutorId]
[a, b]
);
const acc = await chatThreadFor(req.user, ins[0].id);
if (acc.error) return res.status(acc.error).json({ error: acc.message });
@@ -3306,7 +3356,7 @@ app.get('/api/chat/threads/:id/messages', requireAuth, chatLimiter, async (req,
reply_file_token: m.reply_deleted_at ? null : (m.reply_file_token || null),
files: m.deleted_at ? [] : (byMessage.get(m.id) || []),
}));
const unreadCol = req.user.role === 'admin' ? acc.thread.admin_unread : acc.thread.tutor_unread;
const unreadCol = (Number(req.user.id) === Number(acc.thread.tutor_id) && req.user.role !== 'admin') ? acc.thread.tutor_unread : acc.thread.admin_unread;
res.json({ items, thread: chatThreadJson(acc.thread, unreadCol) });
} catch (e) {
res.status(500).json({ error: e.message });
@@ -3323,8 +3373,8 @@ app.delete('/api/chat/threads/:id', requireAuth, requireAdmin, chatLimiter, asyn
[String(days), acc.thread.id]
);
if (!r.rowCount) return res.status(400).json({ error: 'Диалог уже скрыт' });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: '1' });
await logAudit(req, 'chat.thread.hide', { id: acc.thread.id, tutor_id: acc.thread.tutor_id, purge_days: days });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: '1' });
await logAudit(req, 'chat.thread.hide', { id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, purge_days: days });
res.json({ ok: true, thread: chatThreadJson({ ...acc.thread, deleted_at: 'now' }, acc.thread.admin_unread) });
});
@@ -3336,7 +3386,7 @@ app.put('/api/chat/threads/:id/restore', requireAuth, requireAdmin, chatLimiter,
[acc.thread.id]
);
if (!r.rowCount) return res.status(400).json({ error: 'Диалог не скрыт' });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: null });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: null });
await logAudit(req, 'chat.thread.restore', { id: acc.thread.id, tutor_id: acc.thread.tutor_id });
res.json({ ok: true, thread: chatThreadJson({ ...acc.thread, deleted_at: null }, acc.thread.admin_unread) });
});
@@ -3362,7 +3412,7 @@ app.delete('/api/chat/threads/:id/permanent', requireAuth, requireAdmin, chatLim
[String(await trashPurgeDays()), acc.thread.id]
);
if (!r.rowCount) return res.status(400).json({ error: 'Диалог не скрыт или уже запланирован к удалению' });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: '1' });
publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: '1' });
await logAudit(req, 'chat.thread.schedule', { id: acc.thread.id, tutor_id: acc.thread.tutor_id });
res.json({ ok: true });
});
@@ -3430,6 +3480,11 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
const client = await pool.connect();
let created;
const byTutor = req.user.role !== 'admin';
const senderIsA = Number(req.user.id) === Number(acc.thread.tutor_id);
const senderIsB = Number(req.user.id) === Number(acc.thread.peer_id);
const selfThread = senderIsA && senderIsB;
const incA = (!selfThread && senderIsB) ? 1 : 0;
const incB = (!selfThread && senderIsA) ? 1 : 0;
try {
await client.query('BEGIN');
const mr = await client.query(
@@ -3454,7 +3509,7 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
deleted_at = CASE WHEN $5::boolean THEN NULL ELSE deleted_at END,
purge_at = CASE WHEN $5::boolean THEN NULL ELSE purge_at END
WHERE id = $1`,
[acc.thread.id, chatPreviewText(body, files), byTutor ? 0 : 1, byTutor ? 1 : 0, byTutor]
[acc.thread.id, chatPreviewText(body, files), incA, incB, byTutor]
);
await client.query('COMMIT');
} catch (e) {
@@ -3464,7 +3519,7 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
} finally {
client.release();
}
if (byTutor && acc.thread.deleted_at) publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, deleted_at: null });
if (byTutor && acc.thread.deleted_at) publishChat({ type: 'thread_update', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, deleted_at: null });
const { rows: frows } = await pool.query(
'SELECT id, token, name, size FROM chat_attachments WHERE message_id = $1 ORDER BY id',
@@ -3508,7 +3563,17 @@ app.post('/api/chat/threads/:id/messages', requireAuth, chatLimiter, (req, res,
reply_file_token: replyFileToken,
files: frows.map(f => ({ id: f.id, token: f.token, name: f.name, size: f.size })),
};
publishChat({ type: 'message', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, message });
publishChat({ type: 'message', thread_id: acc.thread.id, tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id, message });
if (byTutor) {
await pushNotification({
type: 'chat.message',
title: 'Новое сообщение в чате',
body: `${req.user.name || req.user.username}: ${body}`,
link: 'chat.html',
target: { thread_id: acc.thread.id },
adminOnly: true,
});
}
await logAudit(req, 'chat.message.create', { thread_id: acc.thread.id, message_id: created.id, files: frows.length });
res.json({ message });
}));
@@ -3562,7 +3627,7 @@ app.put('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter, a
publishChat({
type: 'message_update',
thread_id: acc.thread.id,
tutor_id: acc.thread.tutor_id,
tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id,
message: payload,
preview,
});
@@ -3611,7 +3676,7 @@ app.delete('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter
publishChat({
type: 'message_delete',
thread_id: acc.thread.id,
tutor_id: acc.thread.tutor_id,
tutor_id: acc.thread.tutor_id, peer_id: acc.thread.peer_id,
message: {
id: rows[0].id,
sender_id: rows[0].sender_id,
@@ -3638,7 +3703,7 @@ app.delete('/api/chat/threads/:id/messages/:messageId', requireAuth, chatLimiter
app.post('/api/chat/threads/:id/read', requireAuth, chatLimiter, asyncRoute(async (req, res) => {
const acc = await chatThreadFor(req.user, req.params.id);
if (acc.error) return res.status(acc.error).json({ error: acc.message });
const col = req.user.role === 'admin' ? 'admin_unread' : 'tutor_unread';
const col = Number(req.user.id) === Number(acc.thread.tutor_id) ? 'tutor_unread' : 'admin_unread';
await pool.query(`UPDATE chat_threads SET ${col} = 0 WHERE id = $1`, [acc.thread.id]);
res.json({ ok: true, unread: await chatUnread(req.user) });
}));
@@ -3682,7 +3747,7 @@ app.get('/api/chat/files/:token', fileLimiter, async (req, res) => {
}
if (!user || !user.is_active) return res.status(401).json({ error: 'Требуется вход' });
const { rows } = await pool.query(
`SELECT a.token, a.path, a.name, t.tutor_id
`SELECT a.token, a.path, a.name, t.tutor_id, t.peer_id
FROM chat_attachments a
JOIN chat_messages m ON m.id = a.message_id
JOIN chat_threads t ON t.id = m.thread_id
@@ -3691,7 +3756,7 @@ app.get('/api/chat/files/:token', fileLimiter, async (req, res) => {
);
if (!rows.length) return res.status(404).json({ error: 'Файл не найден' });
const r = rows[0];
if (!chatVisible(user, r.tutor_id)) return res.status(403).json({ error: 'Нет доступа к файлу' });
if (!chatVisible(user, r.tutor_id, r.peer_id)) return res.status(403).json({ error: 'Нет доступа к файлу' });
const key = storage.keyFromPath(r.path);
if (!key) return res.status(404).json({ error: 'Файл не найден' });
if (isImageName(r.name)) {
@@ -4418,6 +4483,23 @@ app.get('/api/users/tutors', requireAuth, async (_, res) => {
res.json(rows);
});
app.get('/api/users/search', requireAuth, async (req, res) => {
const q = String(req.query.q || '').trim().slice(0, 80);
const params = [];
let where = 'is_active IS NOT FALSE';
if (q) {
params.push('%' + q + '%');
where += ` AND (name ILIKE $${params.length} OR username ILIKE $${params.length})`;
}
params.push(req.user.id);
where += ` AND id <> $${params.length}`;
const { rows } = await pool.query(
`SELECT id, name, username, role FROM users WHERE ${where} ORDER BY COALESCE(NULLIF(name, ''), username) LIMIT 20`,
params
);
res.json(rows);
});
app.get('/api/users/branches', requireAuth, async (req, res) => {
const s = branchScope(req.user);
const params = [];
@@ -6901,8 +6983,8 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b
const ex = await client.query('SELECT 1 FROM users WHERE id = $1', [x.tutor_id]);
if (!ex.rowCount) continue;
await client.query(
'INSERT INTO chat_threads (id, tutor_id, last_message_at, last_message_text, tutor_unread, admin_unread, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)',
[x.id, x.tutor_id, x.last_message_at, x.last_message_text, x.tutor_unread || 0, x.admin_unread || 0, x.deleted_at || null, x.purge_at || null, x.created_at]
'INSERT INTO chat_threads (id, tutor_id, peer_id, last_message_at, last_message_text, tutor_unread, admin_unread, deleted_at, purge_at, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)',
[x.id, x.tutor_id, x.peer_id || null, x.last_message_at, x.last_message_text, x.tutor_unread || 0, x.admin_unread || 0, x.deleted_at || null, x.purge_at || null, x.created_at]
);
}
const restoredMsgIds = new Set();
@@ -11082,7 +11164,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
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
e.description AS title,
'entry'::text AS face_source_type,
(SELECT ep.id FROM entry_photos ep WHERE ep.entry_id = e.id AND ep.photo_path = e.photo_path LIMIT 1) AS face_photo_id
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
@@ -11090,7 +11174,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
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)
COALESCE(NULLIF(ep.caption, ''), e.description),
'entry'::text AS face_source_type,
ep.id AS face_photo_id
FROM entry_photos ep
JOIN entries e ON e.id = ep.entry_id
JOIN groups g ON g.id = e.group_id
@@ -11099,14 +11185,18 @@ app.get('/api/photos', requireAuth, async (req, res) => {
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)
COALESCE(NULLIF(gp.caption, ''), g.name),
'group'::text AS face_source_type,
gp.id AS face_photo_id
FROM group_photos gp
JOIN groups g ON g.id = gp.group_id
UNION ALL
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
s.name,
NULL::text AS face_source_type,
NULL::int AS face_photo_id
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
@@ -11114,14 +11204,16 @@ app.get('/api/photos', requireAuth, async (req, res) => {
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
m.name,
NULL::text AS face_source_type,
NULL::int AS face_photo_id
FROM modules m
WHERE m.photo_path IS NOT NULL
) 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.photo_key, t.photo_id, t.student_name,
t.group_id, t.group_name, t.created_at, t.title ${from}${where}
t.group_id, t.group_name, t.created_at, t.title, t.face_source_type, t.face_photo_id ${from}${where}
ORDER BY t.created_at DESC`;
const qparams = params.slice();
const lim = parseInt(limit, 10);
@@ -11140,7 +11232,9 @@ app.get('/api/photos', requireAuth, async (req, res) => {
student_name: r.student_name || null,
group_id: r.group_id || null,
group_name: r.group_name || null,
created_at: r.created_at
created_at: r.created_at,
face_source_type: r.face_source_type || null,
face_photo_id: r.face_photo_id == null ? null : r.face_photo_id
}));
res.json({ photos, total });
} catch (e) {