Files
WhatIDo/lib/notifications.js
dev 4bd10b2945 Вынести домен уведомлений в lib/notifications.js
- createNotificationService + NOTIFY_TYPES + все роуты /api/notifications*
  и SSE-канал whatido:notifications перенесены из server.js
- server.js вызывает registerNotificationRoutes(...) с передачей зависимостей
- AGENTS.md и README.md: ссылка на NOTIFY_TYPES перенесена в lib/notifications.js
2026-12-03 12:30:26 +03:00

475 lines
22 KiB
JavaScript

'use strict';
const rateLimit = require('express-rate-limit');
const NOTIFY_CHANNEL = 'whatido:notifications';
const NOTIFY_RETENTION_DEFAULT_DAYS = 30;
const NOTIFY_TYPES = {
'entry.new': { label: 'Новая запись в журнале', hint: 'Ответ ученика отправлен через форму или запись добавлена вручную', icon: 'book-open', level: 'info', enabled: true, admin: false },
'entry.ai.corrected': { label: 'ИИ исправил текст', hint: 'Автопроверка изменила текст записи', icon: 'sparkles', level: 'info', enabled: false, admin: false },
'entry.ai.error': { label: 'Ошибка автопроверки текста', hint: 'ИИ не смог обработать запись после всех попыток', icon: 'bot', level: 'warning', enabled: true, admin: false },
'photo.job.done': { label: 'Фото обработано', hint: 'Нейросеть или сервер улучшили фото в записи', icon: 'image', level: 'info', enabled: true, admin: false },
'photo.job.error': { label: 'Ошибка обработки фото', hint: 'Очередь улучшения фото исчерпала попытки', icon: 'image-off', level: 'warning', enabled: true, admin: false },
'ip.ban': { label: 'IP отправлен в бан', hint: 'Автоблокировка за спам или подбор пароля либо блокировка вручную', icon: 'shield-off', level: 'warning', enabled: true, admin: true },
'backup.restore': { label: 'Восстановление из бэкапа', hint: 'Данные системы заменены содержимым архива', icon: 'database', level: 'critical', enabled: true, admin: true },
'backup.create': { label: 'Создан архив бэкапа', hint: 'Архив данных скачан из админ-панели', icon: 'download', level: 'info', enabled: false, admin: true },
'system.test': { label: 'Тестовое уведомление', hint: 'Проверка доставки уведомлений из настроек', icon: 'send', level: 'info', enabled: true, admin: true, hidden: true },
'lesson.report': { label: 'Отчёт о занятии', hint: 'Тьютор сохранил отчёт о том, что прошли на занятии', icon: 'notebook-pen', level: 'info', enabled: true, admin: false },
'lesson.ai.formatted': { label: 'Отчёт оформлен по шаблону', hint: 'ИИ привёл текст отчёта о занятии к деловому виду', icon: 'file-check', level: 'info', enabled: false, admin: false },
'feedback.ai.ready': { label: 'Отзыв сгенерирован', hint: 'ИИ сформировал отзыв по результатам занятия', icon: 'message-square-heart', level: 'info', enabled: true, admin: false },
'feedback.ai.error': { label: 'Ошибка генерации отзыва', hint: 'ИИ не смог обработать отзыв после всех попыток', icon: 'message-square-x', level: 'warning', enabled: true, admin: false },
'farewell.ai.done': { label: 'Прощальное сообщение готово', hint: 'ИИ сформировал прощальное сообщение об ученике', icon: 'mail-x', level: 'info', enabled: true, admin: true },
'farewell.ai.error': { label: 'Ошибка прощального сообщения', hint: 'ИИ не смог сформировать прощальное сообщение после всех попыток', icon: 'mail-warning', level: 'warning', enabled: true, admin: true },
'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 },
'photo.broken_link': { label: 'Битые ссылки на фото лиц', hint: 'В базе остались ссылки на фото, файлы которых удалены. Требуется очистка ссылок', icon: 'image-off', level: 'warning', enabled: true, admin: true },
'chat.message': { label: 'Новое сообщение в чате', hint: 'Тьютор написал в личный чат администрации', icon: 'bell', level: 'info', enabled: true, admin: true },
'digest.published': { label: 'Новый дайджест', hint: 'Опубликован новый дайджест с важными сообщениями', icon: 'newspaper', level: 'info', enabled: true, admin: false },
'calendar.reminder': { label: 'Напоминание о событии', hint: 'За выбранное время до события в личном или общем календаре', icon: 'bell-ring', level: 'info', enabled: true, admin: false },
};
function notifySettingKey(type) {
return 'notify_' + String(type).replace(/\./g, '_');
}
function notifyCatalog() {
return Object.entries(NOTIFY_TYPES)
.filter(([, spec]) => !spec.hidden)
.map(([type, spec]) => ({
type,
key: notifySettingKey(type),
label: spec.label,
hint: spec.hint,
icon: spec.icon,
level: spec.level || 'info',
admin_only: !!spec.admin,
default_enabled: spec.enabled !== false,
}));
}
function notificationVisible(user, n) {
if (!user) return false;
if (n.user_id != null) return Number(user.id) === Number(n.user_id);
if (user.role === 'admin') return true;
if (n.admin_only) return false;
if (n.branch_id === null || n.branch_id === undefined) return true;
return (user.branch_ids || []).map(Number).includes(Number(n.branch_id));
}
function writeNotifyFrame(client, event, data) {
client.res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
function createNotificationService({ pool, cache, getSetting, branchScope }) {
async function notifyTypeEnabled(type) {
const spec = NOTIFY_TYPES[type];
if (!spec) return false;
if (String(await getSetting('notify_enabled', 'true')) === 'false') return false;
const def = spec.enabled !== false ? 'true' : 'false';
return String(await getSetting(notifySettingKey(type), def)) !== 'false';
}
function publishNotification(row) {
cache.publish(NOTIFY_CHANNEL, row).catch(err => console.error('Notify publish failed:', err.message));
}
async function pushNotification({ type, title, body, link, target, branchId, level, adminOnly, userId }) {
const spec = NOTIFY_TYPES[type];
if (!spec) return null;
if (!(await notifyTypeEnabled(type))) return null;
try {
const { rows } = await pool.query(
`INSERT INTO notifications (type, level, title, body, link, target, admin_only, branch_id, user_id)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
RETURNING id, type, level, title, body, link, target, admin_only, branch_id, user_id, created_at`,
[
type,
level || spec.level || 'info',
String(title || spec.label).slice(0, 200),
body ? String(body).slice(0, 2000) : null,
link || null,
target && Object.keys(target).length ? JSON.stringify(target) : null,
adminOnly === undefined ? !!spec.admin : !!adminOnly,
branchId || null,
Number.isInteger(Number(userId)) && Number(userId) > 0 ? Number(userId) : null,
]
);
const row = rows[0];
publishNotification(row);
return row;
} catch (e) {
console.error('Notification failed:', type, e.message);
return null;
}
}
async function notifyEntry(entryIdOrJob, { type, title, body, link, target, level }) {
if (entryIdOrJob && typeof entryIdOrJob === 'object' && !Array.isArray(entryIdOrJob)) {
const job = entryIdOrJob;
if (job.group_photo_id) {
return notifyGroupPhoto(job.group_photo_id, { type, title, body, link, target, level });
}
return notifyEntry(job.entry_id, { type, title, body, link, target, level });
}
const entryId = entryIdOrJob;
const id = parseInt(entryId, 10);
if (!Number.isInteger(id) || id < 1) return null;
const { rows } = await pool.query(
`SELECT e.id, e.student_name, e.group_id, g.name AS group_name, g.branch_id
FROM entries e LEFT JOIN groups g ON g.id = e.group_id WHERE e.id = $1`,
[id]
);
if (!rows.length) return null;
const ctx = rows[0];
const fill = s => String(s === null || s === undefined ? '' : s)
.replace(/\{student\}/g, ctx.student_name || '—')
.replace(/\{group\}/g, ctx.group_name || '—');
return pushNotification({
type,
level,
title: fill(title),
body: fill(body),
link: link || 'journal.html',
target: Object.assign({ entry_id: ctx.id, student_name: ctx.student_name, group_name: ctx.group_name }, target || {}),
branchId: ctx.branch_id,
});
}
async function notifyGroupPhoto(groupPhotoId, { type, title, body, link, target, level }) {
const id = parseInt(groupPhotoId, 10);
if (!Number.isInteger(id) || id < 1) return null;
const { rows } = await pool.query(
`SELECT gp.id, gp.group_id, g.name AS group_name, g.branch_id
FROM group_photos gp LEFT JOIN groups g ON g.id = gp.group_id WHERE gp.id = $1`,
[id]
);
if (!rows.length) return null;
const ctx = rows[0];
const fill = s => String(s === null || s === undefined ? '' : s)
.replace(/\{student\}/g, '')
.replace(/\{group\}/g, ctx.group_name || '—');
return pushNotification({
type,
level,
title: fill(title),
body: fill(body),
link: link || 'groups.html',
target: Object.assign({ group_photo_id: ctx.id, group_id: ctx.group_id, group_name: ctx.group_name }, target || {}),
branchId: ctx.branch_id,
});
}
async function notifyEntryCreated(entryId) {
return notifyEntry(entryId, {
type: 'entry.new',
title: 'Новая запись: {student}',
body: 'Группа {group}',
});
}
async function notifyEntryAi(payload) {
const status = payload && payload.status;
if (status !== 'done' && status !== 'error') return null;
if (status === 'done' && String(payload.description ?? '') === String(payload.description_original ?? '')) return null;
if (status === 'error') {
const err = payload.error ? ' · ' + String(payload.error).slice(0, 300) : '';
return notifyEntry(payload.id, {
type: 'entry.ai.error',
title: 'ИИ не смог проверить текст: {student}',
body: `Группа {group}${err}`,
target: { error: payload.error || null },
});
}
return notifyEntry(payload.id, {
type: 'entry.ai.corrected',
title: 'ИИ исправил текст: {student}',
body: 'Группа {group}',
});
}
async function purgeOldNotifications() {
const raw = parseInt(await getSetting('notify_retention_days', String(NOTIFY_RETENTION_DEFAULT_DAYS)), 10);
const days = Number.isFinite(raw) && raw >= 1 ? Math.min(raw, 365) : NOTIFY_RETENTION_DEFAULT_DAYS;
const { rowCount } = await pool.query(
`DELETE FROM notifications WHERE created_at < now() - ($1 || ' days')::interval`,
[String(days)]
);
if (rowCount) console.log(`Notifications pruned: ${rowCount} (older than ${days} days)`);
}
async function ensureNotificationsTable() {
await pool.query(`CREATE TABLE IF NOT EXISTS notifications (
id SERIAL PRIMARY KEY,
type VARCHAR(50) NOT NULL,
level VARCHAR(20) NOT NULL DEFAULT 'info',
title VARCHAR(200) NOT NULL,
body TEXT,
link VARCHAR(255),
target JSONB,
admin_only BOOLEAN NOT NULL DEFAULT false,
branch_id INT REFERENCES branches(id) ON DELETE SET NULL,
user_id INT REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query(`ALTER TABLE notifications ADD COLUMN IF NOT EXISTS user_id INT REFERENCES users(id) ON DELETE CASCADE`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_notifications_created_at ON notifications(created_at DESC)`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_notifications_branch_id ON notifications(branch_id)`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id) WHERE user_id IS NOT NULL`);
await pool.query(`CREATE TABLE IF NOT EXISTS notification_reads (
user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
notification_id INT NOT NULL REFERENCES notifications(id) ON DELETE CASCADE,
read_at TIMESTAMPTZ DEFAULT now(),
PRIMARY KEY (user_id, notification_id)
)`);
await pool.query(`CREATE INDEX IF NOT EXISTS idx_notification_reads_user ON notification_reads(user_id)`);
await pool.query(`INSERT INTO settings (key, value) VALUES ('notify_enabled', 'true') ON CONFLICT (key) DO NOTHING`);
await pool.query(
`INSERT INTO settings (key, value) VALUES ('notify_retention_days', $1) ON CONFLICT (key) DO NOTHING`,
[String(NOTIFY_RETENTION_DEFAULT_DAYS)]
);
for (const [type, spec] of Object.entries(NOTIFY_TYPES)) {
await pool.query(
`INSERT INTO settings (key, value) VALUES ($1, $2) ON CONFLICT (key) DO NOTHING`,
[notifySettingKey(type), spec.enabled !== false ? 'true' : 'false']
);
}
}
function notificationsScope(user) {
const s = branchScope(user);
if (s.admin) return { cond: '(n.user_id IS NULL OR n.user_id = $1)', params: [] };
const params = [];
let branch = 'n.admin_only = false';
if (s.ids.length) {
branch += ` AND (n.branch_id IS NULL OR n.branch_id IN (${s.ids.map(id => '$' + (params.push(id) + 1)).join(',')}))`;
} else {
branch += ' AND n.branch_id IS NULL';
}
return { cond: `(n.user_id = $1 OR (n.user_id IS NULL AND ${branch}))`, params };
}
async function notificationsCounts(user) {
const scope = notificationsScope(user);
const { rows } = await pool.query(
`SELECT count(*)::int AS total,
count(*) FILTER (WHERE r.user_id IS NULL)::int AS unread
FROM notifications n
LEFT JOIN notification_reads r ON r.notification_id = n.id AND r.user_id = $1
${scope.cond ? 'WHERE ' + scope.cond : ''}`,
[user.id, ...scope.params]
);
return rows[0];
}
async function notifyMeta() {
const enabled = String(await getSetting('notify_enabled', 'true')) !== 'false';
const retention = parseInt(await getSetting('notify_retention_days', String(NOTIFY_RETENTION_DEFAULT_DAYS)), 10) || NOTIFY_RETENTION_DEFAULT_DAYS;
return { enabled, retention_days: retention, types: notifyCatalog() };
}
async function listNotifications(user, { limit = 30, offset = 0, unread = false } = {}) {
const lim = Math.min(Math.max(parseInt(limit, 10) || 30, 1), 100);
const off = Math.max(parseInt(offset, 10) || 0, 0);
const scope = notificationsScope(user);
const params = [user.id, ...scope.params];
const where = [];
if (scope.cond) where.push(scope.cond);
if (unread) where.push('r.user_id IS NULL');
const { rows } = await pool.query(
`SELECT n.id, n.type, n.level, n.title, n.body, n.link, n.target, n.admin_only, n.branch_id, n.user_id, n.created_at,
(r.user_id IS NOT NULL) AS read
FROM notifications n
LEFT JOIN notification_reads r ON r.notification_id = n.id AND r.user_id = $1
${where.length ? 'WHERE ' + where.join(' AND ') : ''}
ORDER BY n.id DESC LIMIT $${params.push(lim)} OFFSET $${params.push(off)}`,
params
);
const counts = await notificationsCounts(user);
return { items: rows, total: counts.total, unread: counts.unread };
}
async function markAllNotificationsRead(user) {
const scope = notificationsScope(user);
const { rowCount } = await pool.query(
`INSERT INTO notification_reads (user_id, notification_id)
SELECT $1, n.id FROM notifications n
WHERE NOT EXISTS (
SELECT 1 FROM notification_reads r WHERE r.notification_id = n.id AND r.user_id = $1
)${scope.cond ? ' AND (' + scope.cond + ')' : ''}
ON CONFLICT DO NOTHING`,
[user.id, ...scope.params]
);
const counts = await notificationsCounts(user);
return { marked: rowCount, unread: counts.unread };
}
async function markNotificationRead(user, id) {
const scope = notificationsScope(user);
const params = [user.id, ...scope.params, id];
const { rows } = await pool.query(
`SELECT n.id FROM notifications n WHERE n.id = $${params.length}${scope.cond ? ' AND (' + scope.cond + ')' : ''}`,
params
);
if (!rows.length) return false;
await pool.query(
`INSERT INTO notification_reads (user_id, notification_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
[user.id, id]
);
return true;
}
async function deleteNotification(user, id) {
const { rowCount } = await pool.query(
'DELETE FROM notifications WHERE id = $1 AND (user_id IS NULL OR user_id = $2)',
[id, user.id]
);
return rowCount > 0;
}
async function clearNotifications(user) {
const { rowCount } = await pool.query('DELETE FROM notifications WHERE user_id IS NULL OR user_id = $1', [user.id]);
return rowCount;
}
async function sendTestNotification(user) {
return pushNotification({
type: 'system.test',
title: 'Тестовое уведомление',
body: `Отправлено из настроек пользователем ${user.username}`,
link: 'notifications.html',
adminOnly: true,
});
}
return {
publishNotification,
pushNotification,
notifyEntry,
notifyGroupPhoto,
notifyEntryCreated,
notifyEntryAi,
purgeOldNotifications,
ensureNotificationsTable,
notificationsScope,
notificationsCounts,
notifyMeta,
listNotifications,
markAllNotificationsRead,
markNotificationRead,
deleteNotification,
clearNotifications,
sendTestNotification,
};
}
function registerNotificationRoutes({ app, cache, requireAuth, requireAdmin, logAudit, loadUserByToken, notifications }) {
const notifyClients = new Set();
cache.on(NOTIFY_CHANNEL, message => {
let payload = null;
try { payload = JSON.parse(message); } catch (e) { return; }
if (!payload || !payload.id) return;
for (const client of [...notifyClients]) {
if (!notificationVisible(client.user, payload)) continue;
try { writeNotifyFrame(client, 'notification', payload); } catch (e) { notifyClients.delete(client); }
}
});
const notificationLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 600,
standardHeaders: true,
legacyHeaders: false,
store: cache.rateLimitStore('notify', 15 * 60 * 1000),
message: { error: 'Слишком много запросов. Попробуйте позже.' },
});
app.get('/api/notifications', requireAuth, notificationLimiter, async (req, res) => {
const data = await notifications.listNotifications(req.user, {
limit: req.query.limit,
offset: req.query.offset,
unread: req.query.unread === '1',
});
res.json(data);
});
app.get('/api/notifications/meta', requireAdmin, async (_, res) => {
res.json(await notifications.notifyMeta());
});
app.get('/api/notifications/stream', async (req, res) => {
let user = null;
try {
const token = req.headers['x-auth-token'] || req.query.token;
user = await loadUserByToken(token);
} catch (e) {
return res.status(500).end();
}
if (!user || !user.is_active) return res.status(401).end();
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache, no-transform',
Connection: 'keep-alive',
'X-Accel-Buffering': 'no',
});
res.write(':ok\n\n');
const client = { res, user };
notifyClients.add(client);
notifications.notificationsCounts(user)
.then(counts => writeNotifyFrame(client, 'ready', counts))
.catch(err => console.error('Notify counts failed:', err.message));
const ping = setInterval(() => {
try { res.write(':ping\n\n'); } catch (e) { clearInterval(ping); notifyClients.delete(client); }
}, 25000);
req.on('close', () => { clearInterval(ping); notifyClients.delete(client); });
});
app.post('/api/notifications/read-all', requireAuth, notificationLimiter, async (req, res) => {
const out = await notifications.markAllNotificationsRead(req.user);
res.json({ ok: true, marked: out.marked, unread: out.unread });
});
app.post('/api/notifications/:id/read', requireAuth, notificationLimiter, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
const ok = await notifications.markNotificationRead(req.user, id);
if (!ok) return res.status(404).json({ error: 'Not found' });
res.json({ ok: true });
});
app.post('/api/notifications/test', requireAdmin, notificationLimiter, async (req, res) => {
const row = await notifications.sendTestNotification(req.user);
res.json({ ok: true, id: row ? row.id : null, delivered: !!row });
});
app.delete('/api/notifications/:id', requireAdmin, async (req, res) => {
const id = parseInt(req.params.id, 10);
if (!Number.isInteger(id) || id < 1) return res.status(400).json({ error: 'Invalid id' });
const ok = await notifications.deleteNotification(req.user, id);
if (!ok) return res.status(404).json({ error: 'Not found' });
await logAudit(req, 'notifications.delete', { id });
res.json({ ok: true });
});
app.delete('/api/notifications', requireAdmin, async (req, res) => {
const deleted = await notifications.clearNotifications(req.user);
await logAudit(req, 'notifications.clear', { deleted });
res.json({ ok: true, deleted });
});
return { notificationLimiter };
}
module.exports = {
NOTIFY_CHANNEL,
NOTIFY_RETENTION_DEFAULT_DAYS,
NOTIFY_TYPES,
notifySettingKey,
notifyCatalog,
notificationVisible,
createNotificationService,
registerNotificationRoutes,
};