Вынести домен уведомлений в 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
This commit is contained in:
@@ -111,8 +111,8 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
|||||||
- **Сессии**: `loadUserByToken` кэширует пользователя на 30 с. Любая мутация `users` / `sessions` / `user_branches` обязана вызывать `invalidateSessions()` или удалять `session:<token>`, иначе деактивированный пользователь сохранит доступ
|
- **Сессии**: `loadUserByToken` кэширует пользователя на 30 с. Любая мутация `users` / `sessions` / `user_branches` обязана вызывать `invalidateSessions()` или удалять `session:<token>`, иначе деактивированный пользователь сохранит доступ
|
||||||
- **Секреты**: пароль только в `REDIS_URL` / `REDIS_PASSWORD`, порт 6379 публикуется лишь на `127.0.0.1`
|
- **Секреты**: пароль только в `REDIS_URL` / `REDIS_PASSWORD`, порт 6379 публикуется лишь на `127.0.0.1`
|
||||||
|
|
||||||
### 3c. Уведомления (`server.js`, `worker.js`, `public/`)
|
### 3c. Уведомления (`lib/notifications.js`, `server.js`, `worker.js`, `public/`)
|
||||||
- **Каталог событий** — только `NOTIFY_TYPES` в `server.js` (тип → `label`, `hint`, `icon`, `level`, `enabled` по умолчанию, `admin`); фронтенд берёт список из `GET /api/notifications/meta`, дублировать каталог в HTML нельзя
|
- **Каталог событий** — только `NOTIFY_TYPES` в `lib/notifications.js` (тип → `label`, `hint`, `icon`, `level`, `enabled` по умолчанию, `admin`); фронтенд берёт список из `GET /api/notifications/meta`, дублировать каталог в HTML нельзя. Домен целиком живёт в `lib/notifications.js`: `createNotificationService({ pool, cache, getSetting, branchScope })` отдаёт `pushNotification`/`notifyEntry`/`purgeOldNotifications`/`ensureNotificationsTable` и запросы списка/прочтения, а `registerNotificationRoutes(deps)` регистрирует `/api/notifications*` и SSE-подписку `NOTIFY_CHANNEL`
|
||||||
- **Таблицы**: `notifications` (событие, `admin_only`, `branch_id`, `user_id` для личных событий) + `notification_reads` (прочтение на пользователя). Изменения схемы — в `db/init.sql` и `db/migration.sql` и в `ensureNotificationsTable()`; индекс по `user_id` — в обоих SQL-файлах
|
- **Таблицы**: `notifications` (событие, `admin_only`, `branch_id`, `user_id` для личных событий) + `notification_reads` (прочтение на пользователя). Изменения схемы — в `db/init.sql` и `db/migration.sql` и в `ensureNotificationsTable()`; индекс по `user_id` — в обоих SQL-файлах
|
||||||
- **Настройки**: `notify_enabled` (общий), `notify_retention_days` (1–365), `notify_<тип>` (точки типа заменяются на `_`, см. `notifySettingKey`). Значения только `'true'` / `'false'` — `PUT /api/settings` это валидирует
|
- **Настройки**: `notify_enabled` (общий), `notify_retention_days` (1–365), `notify_<тип>` (точки типа заменяются на `_`, см. `notifySettingKey`). Значения только `'true'` / `'false'` — `PUT /api/settings` это валидирует
|
||||||
- **Создание события** — только через `pushNotification()` / `notifyEntry()`; они сами проверяют переключатели и при выключенном типе возвращают `null`. `notifyEntry` подставляет `{student}` и `{group}` и определяет филиал по группе записи
|
- **Создание события** — только через `pushNotification()` / `notifyEntry()`; они сами проверяют переключатели и при выключенном типе возвращают `null`. `notifyEntry` подставляет `{student}` и `{group}` и определяет филиал по группе записи
|
||||||
@@ -309,7 +309,7 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
|
|||||||
- **Ручные эндпоинты больше не сканируют синхронно**: `POST /api/faces/scan-unscanned`, `POST /api/{entries,groups}/:id/photos/scan-faces`, `POST /api/photos/:sourceType/:sourceId/faces/rescan` только ставят задачи и отвечают `{ queued, skipped, total }`. Фронт (`public/js/groups.js`) на это и переписан — не ждёт результата
|
- **Ручные эндпоинты больше не сканируют синхронно**: `POST /api/faces/scan-unscanned`, `POST /api/{entries,groups}/:id/photos/scan-faces`, `POST /api/photos/:sourceType/:sourceId/faces/rescan` только ставят задачи и отвечают `{ queued, skipped, total }`. Фронт (`public/js/groups.js`) на это и переписан — не ждёт результата
|
||||||
- **Наблюдаемость**: `GET /api/faces/queue` (`requireAuth, requireAdmin`) — `totals` по статусам, `busy`, `getInfo()` воркера и последние 15 задач; `POST /api/faces/queue/retry` возвращает `error`-задачи в `pending`. UI — блок «Фоновая очередь проверки» в `#sec-faces` (`#faceQueueHint`, `#faceQueueRefreshBtn`, `#faceQueueRetryBtn`), опрос раз в 5 с
|
- **Наблюдаемость**: `GET /api/faces/queue` (`requireAuth, requireAdmin`) — `totals` по статусам, `busy`, `getInfo()` воркера и последние 15 задач; `POST /api/faces/queue/retry` возвращает `error`-задачи в `pending`. UI — блок «Фоновая очередь проверки» в `#sec-faces` (`#faceQueueHint`, `#faceQueueRefreshBtn`, `#faceQueueRetryBtn`), опрос раз в 5 с
|
||||||
- **Хвост очереди чистится воркером**: каждые 50 задач `DELETE ... WHERE status IN ('done','error') AND updated_at < now() - FACE_KEEP_DONE_MS` (7 суток, env `FACE_SCAN_KEEP_DONE_MS`)
|
- **Хвост очереди чистится воркером**: каждые 50 задач `DELETE ... WHERE status IN ('done','error') AND updated_at < now() - FACE_KEEP_DONE_MS` (7 суток, env `FACE_SCAN_KEEP_DONE_MS`)
|
||||||
- **Уведомления** (`NOTIFY_TYPES` в `server.js`, сид `notify_face_*` в обоих SQL, иконки в `NOTIFY_ICONS` в `public/admin.js`), событие — в `onFaceScanDone`:
|
- **Уведомления** (`NOTIFY_TYPES` в `lib/notifications.js`, сид `notify_face_*` в обоих SQL, иконки в `NOTIFY_ICONS` в `public/admin.js`), событие — в `onFaceScanDone`:
|
||||||
- `face.scan.done` («Найдено лиц на фото: N») — **по умолчанию выключено**: при загрузке каждого фото оно превратилось бы в поток
|
- `face.scan.done` («Найдено лиц на фото: N») — **по умолчанию выключено**: при загрузке каждого фото оно превратилось бы в поток
|
||||||
- `face.recognized` («Распознаны: <имена>») — по умолчанию включено, и только когда есть хотя бы одно имя; имена берутся из `matched_names`, который копит `scanFacesForPhoto` из `loadFaceRefs`
|
- `face.recognized` («Распознаны: <имена>») — по умолчанию включено, и только когда есть хотя бы одно имя; имена берутся из `matched_names`, который копит `scanFacesForPhoto` из `loadFaceRefs`
|
||||||
- `face.scan.error` («Не удалось проверить лица») — по умолчанию включено
|
- `face.scan.error` («Не удалось проверить лица») — по умолчанию включено
|
||||||
@@ -712,6 +712,7 @@ guards against.
|
|||||||
| `public/digest.html` | Дайджест: список важных сообщений, модалка создания/редактирования |
|
| `public/digest.html` | Дайджест: список важных сообщений, модалка создания/редактирования |
|
||||||
| `public/js/digest.js` | Дайджест: загрузка, создание, редактирование, удаление, закрепление сообщений |
|
| `public/js/digest.js` | Дайджест: загрузка, создание, редактирование, удаление, закрепление сообщений |
|
||||||
| `lib/digest.js` | Бизнес-логика дайджеста: таблица `digests`, CRUD, права доступа, закрепление |
|
| `lib/digest.js` | Бизнес-логика дайджеста: таблица `digests`, CRUD, права доступа, закрепление |
|
||||||
|
| `lib/notifications.js` | Домен уведомлений: каталог `NOTIFY_TYPES`, `createNotificationService` (создание событий, видимость/скоуп, чистка, `ensureNotificationsTable`) и `registerNotificationRoutes` (`/api/notifications*` + SSE-канал `whatido:notifications`) |
|
||||||
| `lib/calendar.js` | Календарь: таблица `calendar_events`, валидация, повторение через `generate_series`, личные события и источники «Из системы» |
|
| `lib/calendar.js` | Календарь: таблица `calendar_events`, валидация, повторение через `generate_series`, личные события и источники «Из системы» |
|
||||||
| `public/calendar.html` | Календарь: 4 вида (день/неделя/месяц/повестка), мини-календарь, источники, модалка события (page-local CSS) |
|
| `public/calendar.html` | Календарь: 4 вида (день/неделя/месяц/повестка), мини-календарь, источники, модалка события (page-local CSS) |
|
||||||
| `public/js/calendar.js` | Календарь: сетка CSS Grid, drag-to-create, раскладка пересечений, CRUD, localStorage (`calView`/`calAnchor`/`calSources`) |
|
| `public/js/calendar.js` | Календарь: сетка CSS Grid, drag-to-create, раскладка пересечений, CRUD, localStorage (`calView`/`calAnchor`/`calSources`) |
|
||||||
|
|||||||
@@ -575,7 +575,7 @@ node api-keys.selftest.js # внешний API и API-ключи (нужен з
|
|||||||
|
|
||||||
## Уведомления
|
## Уведомления
|
||||||
|
|
||||||
Система уведомлений — журнал событий (`notifications`, в том числе личные с `user_id`) с отметками прочтения на пользователя (`notification_reads`) плюс каталог типов событий `NOTIFY_TYPES` в `server.js`.
|
Система уведомлений — журнал событий (`notifications`, в том числе личные с `user_id`) с отметками прочтения на пользователя (`notification_reads`) плюс каталог типов событий `NOTIFY_TYPES` в `lib/notifications.js`.
|
||||||
|
|
||||||
| Тип | Событие | Кому видно |
|
| Тип | Событие | Кому видно |
|
||||||
|-----|---------|------------|
|
|-----|---------|------------|
|
||||||
|
|||||||
@@ -0,0 +1,474 @@
|
|||||||
|
'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,
|
||||||
|
};
|
||||||
@@ -149,6 +149,7 @@ const {
|
|||||||
} = require('./lib/calendar');
|
} = require('./lib/calendar');
|
||||||
const { parseTaskKey, getTaskStates, getClosures, saveStepState, closeTask, reopenTask, ensurePostLessonTaskTables } = require('./lib/post-lesson-tasks');
|
const { parseTaskKey, getTaskStates, getClosures, saveStepState, closeTask, reopenTask, ensurePostLessonTaskTables } = require('./lib/post-lesson-tasks');
|
||||||
const { normalizeEntryClientId, findEntryByClientId, entryExistsByClientId } = require('./lib/entry-submit');
|
const { normalizeEntryClientId, findEntryByClientId, entryExistsByClientId } = require('./lib/entry-submit');
|
||||||
|
const { createNotificationService, registerNotificationRoutes } = require('./lib/notifications');
|
||||||
|
|
||||||
const https = require('https');
|
const https = require('https');
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
@@ -396,251 +397,15 @@ function invalidateStats() { cacheDrop('stats:'); cacheDrop('dashboard:'); cache
|
|||||||
function invalidateAll() { cache.clear().catch(err => console.error('Cache clear failed:', err.message)); }
|
function invalidateAll() { cache.clear().catch(err => console.error('Cache clear failed:', err.message)); }
|
||||||
|
|
||||||
// --- Notifications ---
|
// --- Notifications ---
|
||||||
const NOTIFY_CHANNEL = 'whatido:notifications';
|
const notifications = createNotificationService({ pool, cache, getSetting, branchScope });
|
||||||
const NOTIFY_RETENTION_DEFAULT_DAYS = 30;
|
const {
|
||||||
|
pushNotification,
|
||||||
const NOTIFY_TYPES = {
|
notifyEntry,
|
||||||
'entry.new': { label: 'Новая запись в журнале', hint: 'Ответ ученика отправлен через форму или запись добавлена вручную', icon: 'book-open', level: 'info', enabled: true, admin: false },
|
notifyEntryCreated,
|
||||||
'entry.ai.corrected': { label: 'ИИ исправил текст', hint: 'Автопроверка изменила текст записи', icon: 'sparkles', level: 'info', enabled: false, admin: false },
|
notifyEntryAi,
|
||||||
'entry.ai.error': { label: 'Ошибка автопроверки текста', hint: 'ИИ не смог обработать запись после всех попыток', icon: 'bot', level: 'warning', enabled: true, admin: false },
|
purgeOldNotifications,
|
||||||
'photo.job.done': { label: 'Фото обработано', hint: 'Нейросеть или сервер улучшили фото в записи', icon: 'image', level: 'info', enabled: true, admin: false },
|
ensureNotificationsTable,
|
||||||
'photo.job.error': { label: 'Ошибка обработки фото', hint: 'Очередь улучшения фото исчерпала попытки', icon: 'image-off', level: 'warning', enabled: true, admin: false },
|
} = notifications;
|
||||||
'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,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
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';
|
|
||||||
}
|
|
||||||
|
|
||||||
const notifyClients = new Set();
|
|
||||||
|
|
||||||
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 publishNotification(row) {
|
|
||||||
cache.publish(NOTIFY_CHANNEL, row).catch(err => console.error('Notify publish failed:', err.message));
|
|
||||||
}
|
|
||||||
|
|
||||||
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); }
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
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']
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const CHAT_RETENTION_DEFAULT_DAYS = 365;
|
const CHAT_RETENTION_DEFAULT_DAYS = 365;
|
||||||
const CHAT_BODY_MAX = 5000;
|
const CHAT_BODY_MAX = 5000;
|
||||||
@@ -734,32 +499,6 @@ async function purgeOldChat() {
|
|||||||
if (msgs.rowCount) console.log(`Chat pruned: ${msgs.rowCount} messages, ${rows.length} files (older than ${days} days)`);
|
if (msgs.rowCount) console.log(`Chat pruned: ${msgs.rowCount} messages, ${rows.length} files (older than ${days} days)`);
|
||||||
}
|
}
|
||||||
|
|
||||||
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];
|
|
||||||
}
|
|
||||||
|
|
||||||
const BAN_TTL_MS = 24 * 60 * 60 * 1000;
|
const BAN_TTL_MS = 24 * 60 * 60 * 1000;
|
||||||
const FAIL_WINDOW_MS = 15 * 60 * 1000;
|
const FAIL_WINDOW_MS = 15 * 60 * 1000;
|
||||||
const banKey = ip => 'ban:' + ip;
|
const banKey = ip => 'ban:' + ip;
|
||||||
@@ -3094,131 +2833,14 @@ app.delete('/api/bans/:ip', requireAuth, requireAdmin, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// --- Notifications ---
|
// --- Notifications ---
|
||||||
const notificationLimiter = rateLimit({
|
registerNotificationRoutes({
|
||||||
windowMs: 15 * 60 * 1000,
|
app,
|
||||||
max: 600,
|
cache,
|
||||||
standardHeaders: true,
|
requireAuth,
|
||||||
legacyHeaders: false,
|
requireAdmin,
|
||||||
store: cache.rateLimitStore('notify', 15 * 60 * 1000),
|
logAudit,
|
||||||
message: { error: 'Слишком много запросов. Попробуйте позже.' },
|
loadUserByToken,
|
||||||
});
|
notifications,
|
||||||
|
|
||||||
app.get('/api/notifications', requireAuth, notificationLimiter, async (req, res) => {
|
|
||||||
const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 30, 1), 100);
|
|
||||||
const offset = Math.max(parseInt(req.query.offset, 10) || 0, 0);
|
|
||||||
const unreadOnly = req.query.unread === '1';
|
|
||||||
const scope = notificationsScope(req.user);
|
|
||||||
const params = [req.user.id, ...scope.params];
|
|
||||||
const where = [];
|
|
||||||
if (scope.cond) where.push(scope.cond);
|
|
||||||
if (unreadOnly) 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(limit)} OFFSET $${params.push(offset)}`,
|
|
||||||
params
|
|
||||||
);
|
|
||||||
const counts = await notificationsCounts(req.user);
|
|
||||||
res.json({ items: rows, total: counts.total, unread: counts.unread });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get('/api/notifications/meta', requireAdmin, async (_, res) => {
|
|
||||||
res.json({
|
|
||||||
enabled: String(await getSetting('notify_enabled', 'true')) !== 'false',
|
|
||||||
retention_days: parseInt(await getSetting('notify_retention_days', String(NOTIFY_RETENTION_DEFAULT_DAYS)), 10) || NOTIFY_RETENTION_DEFAULT_DAYS,
|
|
||||||
types: notifyCatalog(),
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
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);
|
|
||||||
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 scope = notificationsScope(req.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`,
|
|
||||||
[req.user.id, ...scope.params]
|
|
||||||
);
|
|
||||||
const counts = await notificationsCounts(req.user);
|
|
||||||
res.json({ ok: true, marked: rowCount, unread: counts.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 scope = notificationsScope(req.user);
|
|
||||||
const params = [req.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 res.status(404).json({ error: 'Not found' });
|
|
||||||
await pool.query(
|
|
||||||
`INSERT INTO notification_reads (user_id, notification_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`,
|
|
||||||
[req.user.id, id]
|
|
||||||
);
|
|
||||||
res.json({ ok: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post('/api/notifications/test', requireAdmin, notificationLimiter, async (req, res) => {
|
|
||||||
const row = await pushNotification({
|
|
||||||
type: 'system.test',
|
|
||||||
title: 'Тестовое уведомление',
|
|
||||||
body: `Отправлено из настроек пользователем ${req.user.username}`,
|
|
||||||
link: 'notifications.html',
|
|
||||||
adminOnly: true,
|
|
||||||
});
|
|
||||||
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 { rowCount } = await pool.query(
|
|
||||||
'DELETE FROM notifications WHERE id = $1 AND (user_id IS NULL OR user_id = $2)',
|
|
||||||
[id, req.user.id]
|
|
||||||
);
|
|
||||||
if (!rowCount) 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 { rowCount } = await pool.query('DELETE FROM notifications WHERE user_id IS NULL OR user_id = $1', [req.user.id]);
|
|
||||||
await logAudit(req, 'notifications.clear', { deleted: rowCount });
|
|
||||||
res.json({ ok: true, deleted: rowCount });
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// --- Chat (тьютор ↔ админ) ---
|
// --- Chat (тьютор ↔ админ) ---
|
||||||
|
|||||||
Reference in New Issue
Block a user