From cde281fd89fceea694e2433f3203825cd327c5dd Mon Sep 17 00:00:00 2001 From: dev Date: Fri, 27 Nov 2026 09:56:11 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9A=D0=B0=D0=BB=D0=B5=D0=BD=D0=B4=D0=B0?= =?UTF-8?q?=D1=80=D1=8C:=20=D0=BD=D0=B0=D0=BF=D0=BE=D0=BC=D0=B8=D0=BD?= =?UTF-8?q?=D0=B0=D0=BD=D0=B8=D1=8F=20=D0=BB=D0=B8=D1=87=D0=BD=D1=8B=D0=BC?= =?UTF-8?q?=D0=B8=20=D1=83=D0=B2=D0=B5=D0=B4=D0=BE=D0=BC=D0=BB=D0=B5=D0=BD?= =?UTF-8?q?=D0=B8=D1=8F=D0=BC=D0=B8=20=D0=B8=20=D1=82=D1=91=D0=BC=D0=BD?= =?UTF-8?q?=D0=B0=D1=8F=20=D1=82=D0=B5=D0=BC=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + AGENTS.md | 9 +- API.md | 10 +- README.md | 7 +- backup-restore.js | 1 + backup.selftest.js | 3 +- db/init.sql | 15 + db/migration.sql | 15 + docs/tasks/calendar-handoff.md | 26 +- lib/calendar.js | 146 +++++ public/admin-dark.css | 1101 ++++++++++++++++++++++++++++++++ public/admin.js | 1 + public/calendar.html | 6 +- public/js/calendar.js | 2 +- server.js | 51 +- 15 files changed, 1349 insertions(+), 45 deletions(-) create mode 100644 public/admin-dark.css diff --git a/.gitignore b/.gitignore index 692655b..365941d 100644 --- a/.gitignore +++ b/.gitignore @@ -7,6 +7,7 @@ *.crt certs/ wg/ +tmp/ # --- Run-time data / uploads --- uploads/ diff --git a/AGENTS.md b/AGENTS.md index b86bce8..621e3ed 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -113,12 +113,13 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo ### 3c. Уведомления (`server.js`, `worker.js`, `public/`) - **Каталог событий** — только `NOTIFY_TYPES` в `server.js` (тип → `label`, `hint`, `icon`, `level`, `enabled` по умолчанию, `admin`); фронтенд берёт список из `GET /api/notifications/meta`, дублировать каталог в HTML нельзя -- **Таблицы**: `notifications` (событие, `admin_only`, `branch_id`) + `notification_reads` (прочтение на пользователя). Изменения схемы — в `db/init.sql` и `db/migration.sql` и в `ensureNotificationsTable()` +- **Таблицы**: `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` это валидирует - **Создание события** — только через `pushNotification()` / `notifyEntry()`; они сами проверяют переключатели и при выключенном типе возвращают `null`. `notifyEntry` подставляет `{student}` и `{group}` и определяет филиал по группе записи - **Хук в фото-воркере называется `notifyEvent`** — имя `notify` внутри `createPhotoEnhanceWorker` уже занято будильником воркера (`photoWorker.notify()` из `POST /api/photo-jobs/wake`), объявление функции перекрыло бы параметр -- **Видимость**: админ видит всё; остальные — `admin_only = false` и `branch_id IS NULL` или филиал из `user_branches` -- **Доставка**: запись в БД → `cache.publish('whatido:notifications', row)` → SSE `GET /api/notifications/stream` (клиенты фильтруются по `notificationVisible`). Redis недоступен — работает in-memory pub/sub +- **Видимость**: `user_id IS NOT NULL` — личное событие, его видит только этот пользователь (включая админа); `notificationVisible` и `notificationsScope` проверяют `user_id` раньше ролей и филиалов. Для `user_id IS NULL`: админ видит всё; остальные — `admin_only = false` и `branch_id IS NULL` или филиал из `user_branches`. Админские роуты удаления тоже не трогают чужие личные события +- **Доставка**: запись в БД → `cache.publish('whatido:notifications', row)` → SSE `GET /api/notifications/stream` (клиенты фильтруются по `notificationVisible`, личные события идут тем же каналом). Redis недоступен — работает in-memory pub/sub +- **Личные события**: `pushNotification({ ..., userId })` — единственный способ отправить уведомление конкретному пользователю; сейчас так доставляются напоминания календаря (`calendar.reminder`) - **Очистка**: `purgeOldNotifications()` при старте и раз в час по `notify_retention_days`; чтения удаляются каскадом - **Новое событие добавляется вместе с**: записью в `NOTIFY_TYPES`, строками `INSERT INTO settings` в `db/init.sql` + `db/migration.sql`, вызовом `pushNotification`/`notifyEntry` в точке события и парой `icon` из Lucide - **Аудит**: удаление/очистка уведомлений логируется (`notifications.delete`, `notifications.clear`) @@ -443,7 +444,7 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **Read-only источники «Из системы»** — `groups` (занятия по `day_of_week`/`time_start`/`time_end`), `lesson_reports` (DATE + TIME), `digests` (опубликованные, не скрытые `hide_at`). Список приходит в `{ sources }` того же `GET /api/calendar/events`, цвета `green`/`purple`/`orange`, клик ведёт в `groups.html` / `lessons.html` / `digest.html`, а не в редактор. Не-admin фильтруется `branchScope` (пустой список филиалов → `1 = 0`); digests видны всем авторизованным. Чекбоксы источников и личного календаря хранятся в `localStorage.calSources` как список **скрытых** id (включая `personal`); вид и якорь — `calView`/`calAnchor` - **REST вместо SSE** — `/api/events` уже занят SSE, календарные роуты только `/api/calendar/events*` (`apiLimiter` только на GET). Нового SSE-канала и Redis-кэша нет: данных мало, а инвалидация на каждую мутацию — лишний риск и лишнее соединение в бюджете HTTP/1.1. Все даты/время на клиенте — только хелперы `public/js/datetime.js`: `todayIso`, `isoAddDays`, `isoDow`, `fmtHmStr`, `fmtDateOnlyLongIso`, `fmtDayMonthIso`, `fmtMonthYearIso`, `dtToLocalInput`, `dtInputToIso`. Прямых `toLocale*`/`new Date('YYYY-MM-DD')` в `calendar.js` быть не должно; «сейчас» и красная линия — по зоне приложения (`nowHm()`), обновляются раз в минуту - **Бэкап** — `calendar_events` в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, выгружается в `buildBackupArchive`, нормализуется в `backup-restore.js` (цвет/повтор/напоминания по allowlist, `deleted_at`/`purge_at` сохраняются), в restore удаляется до `DELETE FROM users` и вставляется после пользователей с проверкой владельца; проверка — `backup.selftest.js` -- **Напоминания** — `reminder_minutes` только хранятся (0/5/10/15/30/60/120/1440, максимум 5); доставка через `calendar.reminder` и таблицу дедупликации — отдельный этап, в MVP не делать +- **Напоминания** — `reminder_minutes` (0/5/10/15/30/60/120/1440, максимум 5) доставляются воркером `createCalendarReminderWorker` из `lib/calendar.js`: тик раз в 60 с, окно 24 ч назад, зона через `bindTz`/`appTimezone()`. Дедупликация — таблица `calendar_reminder_sent(event_id, user_id, occurrence_at, minutes)`, строки старше 7 суток чистятся; при ошибке доставки запись удаляется, чтобы тик мог повторить. Удалённые события и прошедшие вхождения не отправляются. Уведомление персональное (`userId` владельца, иконка `bell-ring`, `link: 'calendar.html'`), идёт через общий SSE уведомлений; новый SSE-канал и Redis-кэш не заводятся. Производная таблица `calendar_reminder_sent` в бэкап не входит ### 4. API Patterns - **Middleware**: `requireAuth` — читает `X-Auth-Token`, 401 без валидной активной сессии. `requireAdmin` — самодостаточный (внутри вызывает `requireAuth`, если `req.user` ещё нет), 403 при `role !== 'admin'`. `optionalAuth` — для публичных страниц с персонализацией diff --git a/API.md b/API.md index e40c319..e79730c 100644 --- a/API.md +++ b/API.md @@ -701,9 +701,9 @@ X-Accel-Buffering: no Формат кадра — `writeNotifyFrame` (`server.js:278-280`), тот же `event:` / `data:` JSON. -Поля строки уведомления (по выборке в `GET /api/notifications`, `server.js:1729`): `id, type, level, title, body, link, target, admin_only, branch_id, created_at, read`. +Поля строки уведомления (по выборке в `GET /api/notifications`): `id, type, level, title, body, link, target, admin_only, branch_id, user_id, created_at, read`. -**Фильтрация по видимости** (`notificationVisible`, `server.js:270-276`): админ видит всё; остальные — только `admin_only = false` **и** (`branch_id IS NULL` или филиал из `user_branches` клиента). Невидимые кадры не отправляются вовсе. +**Фильтрация по видимости** (`notificationVisible`): сначала проверяется `user_id` — если он задан, уведомление видит только этот пользователь, включая админа. Для остальных: админ видит всё; остальные — только `admin_only = false` **и** (`branch_id IS NULL` или филиал из `user_branches` клиента). Невидимые кадры не отправляются вовсе. Транспорт: канал `whatido:notifications` (`NOTIFY_CHANNEL`, `server.js:224`); запись в БД → `cache.publish` → рассылка подключённым клиентам с фильтрацией. При недоступном Redis работает in-memory pub/sub. @@ -778,14 +778,14 @@ off = parseInt(offset, 10); if (off > 0) { OFFSET $n } ## 11. Уведомления -Общий лимитер `notificationLimiter`: 600 / 15 мин, `cache.rateLimitStore('notify')`, сообщение «Слишком много запросов. Попробуйте позже.». Видимость (`notificationsScope`): админ видит всё; не-admin — только `admin_only = false` и (`branch_id IS NULL` или филиал из `user_branches`). +Общий лимитер `notificationLimiter`: 600 / 15 мин, `cache.rateLimitStore('notify')`, сообщение «Слишком много запросов. Попробуйте позже.». Видимость (`notificationsScope`): уведомления с `user_id` доступны только этому пользователю (админ — тоже только своим); для остальных админ видит всё, не-admin — только `admin_only = false` и (`branch_id IS NULL` или филиал из `user_branches`). Админские `DELETE /api/notifications/:id` и `DELETE /api/notifications` не удаляют чужие личные уведомления. ### `GET /api/notifications` - **Доступ:** `requireAuth` + `notificationLimiter`. - **Query:** `limit` (1…100, дефолт 30), `offset` (≥0, дефолт 0), `unread` (`'1'` — только непрочитанные). - **Тело:** нет. -- **Ответ 200:** `{ items, total, unread }`. `items` — строки `{ id, type, level, title, body, link, target, admin_only, branch_id, created_at, read }` (`read` считается LEFT JOIN'ом на `notification_reads` текущего пользователя), сортировка `n.id DESC`; `total` и `unread` — из `notificationsCounts` по всей видимой выборке, а не по странице. +- **Ответ 200:** `{ items, total, unread }`. `items` — строки `{ id, type, level, title, body, link, target, admin_only, branch_id, user_id, created_at, read }` (`read` считается LEFT JOIN'ом на `notification_reads` текущего пользователя), сортировка `n.id DESC`; `total` и `unread` — из `notificationsCounts` по всей видимой выборке, а не по странице. - **Ошибки:** 401 / 429. ### `GET /api/notifications/meta` @@ -801,7 +801,7 @@ off = parseInt(offset, 10); if (off > 0) { OFFSET $n } - **Ответ 200:** `Content-Type: text/event-stream`, заголовки `Cache-Control: no-cache, no-transform`, `Connection: keep-alive`, `X-Accel-Buffering: no`. - **События:** `ready` — сразу после подключения, `data` = JSON `{ total, unread }` (из `notificationsCounts`); `notification` — при публикации в Redis-канал уведомлений, `data` = JSON строки уведомления (публикуется вся строка БД). Служебные кадры (не события): `:ok` при открытии и `:ping` раз в 25 с. Формат кадра: `event: <имя>\ndata: \n\n`. - **Ошибки:** 401 пустым ответом без тела (нет валидной сессии); 500 при ошибке БД. -- **Примечания:** клиент кладётся в `notifyClients`, рассылка фильтруется по `notificationVisible(user, payload)` (админ — всё, иначе `!admin_only` и филиал из `branch_ids`), удаляется из сета на `req.on('close')`. Rate limit на этот маршрут не навешен. +- **Примечания:** клиент кладётся в `notifyClients`, рассылка фильтруется по `notificationVisible(user, payload)` (сначала `user_id`, затем админ — всё, иначе `!admin_only` и филиал из `branch_ids`), удаляется из сета на `req.on('close')`. Rate limit на этот маршрут не навешен. ### `POST /api/notifications/read-all` diff --git a/README.md b/README.md index 8676ea1..fd2a3ee 100644 --- a/README.md +++ b/README.md @@ -575,7 +575,7 @@ node api-keys.selftest.js # внешний API и API-ключи (нужен з ## Уведомления -Система уведомлений — журнал событий (`notifications`) с отметками прочтения на пользователя (`notification_reads`) плюс каталог типов событий `NOTIFY_TYPES` в `server.js`. +Система уведомлений — журнал событий (`notifications`, в том числе личные с `user_id`) с отметками прочтения на пользователя (`notification_reads`) плюс каталог типов событий `NOTIFY_TYPES` в `server.js`. | Тип | Событие | Кому видно | |-----|---------|------------| @@ -587,12 +587,15 @@ node api-keys.selftest.js # внешний API и API-ключи (нужен з | `ip.ban` | IP отправлен в бан (авто или вручную) | только админ | | `backup.restore` | восстановление из бэкапа | только админ | | `backup.create` | создан архив бэкапа (по умолчанию выключено) | только админ | +| `calendar.reminder` | напоминание о событии личного календаря | только владелец события (админ — только о своём) | Где видно: «колокольчик» в боковом меню (панель последних событий, бейдж непрочитанных, опциональные уведомления браузера) и страница `notifications.html` (фильтр «непрочитанные», отметка «прочитано», удаление и полная очистка для админа). Новые события приходят в реальном времени по SSE (`GET /api/notifications/stream`), транспорт — Redis pub/sub с in-memory fallback. Что настраивается в «Настройках» → «Уведомления» (ключи таблицы `settings`): общий выключатель `notify_enabled`, срок хранения `notify_retention_days` (1–365 дней, старые уведомления удаляются ежечасно) и отдельный переключатель `notify_<тип>` для каждого события. Там же кнопка тестового уведомления. -Видимость: администратор видит все уведомления, остальные — только события своего филиала (или без филиала) и никогда — события с пометкой `admin_only`. +Видимость: уведомления с `user_id` личные — их видит только этот пользователь, включая администратора. Остальные: администратор видит все, остальные — только события своего филиала (или без филиала) и никогда — события с пометкой `admin_only`. + +Напоминания календаря приходят за заданное число минут до события: воркер раз в минуту смотрит окно 24 часа назад, дедуплицирует отправку по `(event_id, user_id, occurrence_at, minutes)` и не шлёт напоминания по удалённым событиям. После простоя дольше суток пропущенные напоминания не восстанавливаются — они уже вне окна сканирования. ## Бэкапы diff --git a/backup-restore.js b/backup-restore.js index f398280..5aec17c 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -484,6 +484,7 @@ function normalizeRestoreData(data) { target: optJsonText(x.target, 20000), admin_only: !!x.admin_only, branch_id: optInt(x.branch_id, 0, 2147483647), + user_id: optInt(x.user_id, 0, 2147483647), created_at: optTs(x.created_at), })); const notification_reads = (data.notification_reads || []).map(x => ({ diff --git a/backup.selftest.js b/backup.selftest.js index 9f18cc9..c0c0f9f 100644 --- a/backup.selftest.js +++ b/backup.selftest.js @@ -114,13 +114,14 @@ ok('entries.purge_at больше не теряется', e.entries[0].purge_at const nt = normalizeRestoreData({ ...base, - notifications: [{ id: 5, type: 'entry.new', level: 'warning', title: 'T', body: 'B', link: 'l', target: { a: 1 }, admin_only: true, branch_id: 2 }], + notifications: [{ id: 5, type: 'entry.new', level: 'warning', title: 'T', body: 'B', link: 'l', target: { a: 1 }, admin_only: true, branch_id: 2, user_id: 3 }], notification_reads: [{ user_id: 1, notification_id: 5 }], audit_log: [{ id: 7, user_id: 1, action: 'backup.download', target: { size: 5 }, ip: '1.2.3.4' }], banned_ips: [{ ip: '203.0.113.7', reason: 'manual', banned_until: '2026-05-05T00:00:00.000Z' }], }); ok('notifications нормализуются', nt.notifications[0].level === 'warning' && nt.notifications[0].title === 'T', nt.notifications[0]); ok('notifications.target остаётся JSON-строкой', nt.notifications[0].target === '{"a":1}', nt.notifications[0].target); +ok('notifications.user_id сохраняется', nt.notifications[0].user_id === 3, nt.notifications[0].user_id); ok('notification_reads нормализуются', nt.notification_reads[0].notification_id === 5); ok('audit_log нормализуется', nt.audit_log[0].action === 'backup.download' && nt.audit_log[0].target === '{"size":5}', nt.audit_log[0]); ok('banned_ips нормализуются', nt.banned_ips[0].ip === '203.0.113.7'); diff --git a/db/init.sql b/db/init.sql index 1050478..73187ca 100644 --- a/db/init.sql +++ b/db/init.sql @@ -427,11 +427,13 @@ CREATE TABLE IF NOT EXISTS notifications ( 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() ); CREATE INDEX IF NOT EXISTS idx_notifications_created_at ON notifications(created_at DESC); CREATE INDEX IF NOT EXISTS idx_notifications_branch_id ON notifications(branch_id); +CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id) WHERE user_id IS NOT NULL; CREATE TABLE IF NOT EXISTS notification_reads ( user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, @@ -515,6 +517,8 @@ INSERT INTO settings (key, value) VALUES ('notify_backup_create', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('notify_system_test', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_calendar_reminder', 'true') +ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('lesson_ai_enabled', 'true') ON CONFLICT (key) DO NOTHING; @@ -873,3 +877,14 @@ CREATE TABLE IF NOT EXISTS calendar_events ( CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common; CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL; + +CREATE TABLE IF NOT EXISTS calendar_reminder_sent ( + id BIGSERIAL PRIMARY KEY, + event_id INT NOT NULL REFERENCES calendar_events(id) ON DELETE CASCADE, + user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + occurrence_at TIMESTAMPTZ NOT NULL, + minutes INT NOT NULL, + sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (event_id, user_id, occurrence_at, minutes) +); +CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at); diff --git a/db/migration.sql b/db/migration.sql index 8ec4a83..701f2bd 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -418,11 +418,14 @@ CREATE TABLE IF NOT EXISTS notifications ( 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() ); +ALTER TABLE notifications ADD COLUMN IF NOT EXISTS user_id INT REFERENCES users(id) ON DELETE CASCADE; CREATE INDEX IF NOT EXISTS idx_notifications_created_at ON notifications(created_at DESC); CREATE INDEX IF NOT EXISTS idx_notifications_branch_id ON notifications(branch_id); +CREATE INDEX IF NOT EXISTS idx_notifications_user_id ON notifications(user_id) WHERE user_id IS NOT NULL; CREATE TABLE IF NOT EXISTS notification_reads ( user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, @@ -982,6 +985,7 @@ INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON C INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('notify_chat_message', 'true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('notify_photo_broken_link', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_calendar_reminder', 'true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('faces_broken_scan_enabled', 'true') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('faces_broken_scan_interval_hours', '6') ON CONFLICT (key) DO NOTHING; @@ -1164,3 +1168,14 @@ ALTER TABLE calendar_events ADD COLUMN IF NOT EXISTS is_common BOOLEAN NOT NULL CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL; CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common; CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL; + +CREATE TABLE IF NOT EXISTS calendar_reminder_sent ( + id BIGSERIAL PRIMARY KEY, + event_id INT NOT NULL REFERENCES calendar_events(id) ON DELETE CASCADE, + user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + occurrence_at TIMESTAMPTZ NOT NULL, + minutes INT NOT NULL, + sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (event_id, user_id, occurrence_at, minutes) +); +CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at); diff --git a/docs/tasks/calendar-handoff.md b/docs/tasks/calendar-handoff.md index 5a2e34e..5c2b7f5 100644 --- a/docs/tasks/calendar-handoff.md +++ b/docs/tasks/calendar-handoff.md @@ -5,7 +5,7 @@ **Статус:** реализовано, коммит `bcd3738` (ветка `feature/calendar-page`); приложение пересобрано и запущено **Исполнитель:** следующий агент/разработчик. Этот документ — единственный источник требований; при расхождении с `AGENTS.md` приоритет у `AGENTS.md`, а расхождение нужно отдельно отметить в финальном отчёте. -**Что проверено после реализации:** `node -c` по всем изменённым JS, `node backup.selftest.js`, миграция в откатываемой транзакции, SQL повторений и источников на живой БД, HTTP CRUD `/api/calendar/events` (401/400/POST/GET/PUT/soft-delete/restore/permanent), изоляция чужих событий, загрузка `calendar.html`/`js/calendar.js`. Напоминания пока только хранятся, доставка не реализована (см. §7). +**Что проверено после реализации:** `node -c` по всем изменённым JS, `node backup.selftest.js`, миграция в откатываемой транзакции, SQL повторений и источников на живой БД, HTTP CRUD `/api/calendar/events` (401/400/POST/GET/PUT/soft-delete/restore/permanent), изоляция чужих событий, загрузка `calendar.html`/`js/calendar.js`. Напоминания доставляются личными уведомлениями `calendar.reminder` (см. §7.2). --- @@ -38,7 +38,7 @@ Нужна новая страница «Календарь» в общем сайдбаре (пункт между «Журналом» и «Отчётами о занятиях»): - **4 вида:** Day / Week / Month / Agenda. Неделя — основная. -- **Личные события** пользователя: создание, редактирование, удаление, цвет, место, заметки, повтор, напоминания (хранение; доставка — этап 2). +- **Личные события** пользователя: создание, редактирование, удаление, цвет, место, заметки, повтор, напоминания (хранение и доставка личными уведомлениями). - **Создание перетаскиванием** по сетке (dashed-выделение, как на `week-new-event.png`) и кнопкой «Новое событие». - **Read-only слои из системы** («Из системы» в левой панели) — занятия групп, отчёты о занятиях, дайджест. Включаются/выключаются чекбоксами. - **Мини-календарь** месяца в левой панели, навигация «Сегодня / ← / →», текущая дата и красная линия «сейчас». @@ -132,7 +132,7 @@ 5. Строка «Личный календарь» + палитра цветов (8 кружков, выбранный — с кольцом). 6. `Добавить место` → input места. 7. `Добавить заметки` → textarea (автовысота, лимит 5000). -8. Напоминания: чипы `за 10 минут ×` + `+ Добавить напоминание` (набор: 0, 5, 10, 15, 30, 60, 120, 1440 минут). Хранится, доставка — этап 2. +8. Напоминания: чипы `за 10 минут ×` + `+ Добавить напоминание` (набор: 0, 5, 10, 15, 30, 60, 120, 1440 минут). Доставляются уведомлением `calendar.reminder` владельцу события. 9. Футер: `Удалить` слева (только при редактировании), `Отмена`, `Сохранить`. Поведение: `Esc` закрывает, фокус при открытии — в заголовок, `Ctrl/Cmd+Enter` — сохранить. Редактирование повторяющегося события меняет **всю серию** (исключений/«только это событие» в MVP нет). @@ -526,15 +526,13 @@ goPrev()/goNext()/goToday()/setView(v) **Файловых колонок у календаря нет** → `sweepOrphanedUploads()` и `BROKEN_IMAGE_SOURCES` трогать не нужно. Если в будущем появятся обложки/вложения — это отдельная задача с обязательной правкой обоих мест. -### 7.2. Уведомления и напоминания — этап 2 (не делать в MVP) +### 7.2. Уведомления и напоминания — реализовано -Если дойдёт до реализации: - -- `NOTIFY_TYPES['calendar.reminder'] = { label: 'Напоминание о событии', hint: 'За N минут до события в личном календаре', icon: 'bell-ring', level: 'info', enabled: true, admin: false }`. -- Сиды `notify_calendar_reminder` в `db/init.sql` + `db/migration.sql` (цикл в `ensureNotificationsTable()` подстрахует, но SQL-строки обязательны по правилам). -- Дедупликация отправки — отдельная таблица `calendar_reminder_sent(event_id, occurrence_at, minutes, sent_at, UNIQUE(event_id, occurrence_at, minutes))`; иначе повторный тик каждую минуту будет спамить. -- Планировщик — `setInterval` в `server.js` рядом с `purgeScheduledDeletions()` (`:15636-15637`) или отдельная функция в `lib/calendar.js`, вызываемая оттуда; окно сканирования 2 минуты, разворот повторов — тем же SQL, что в §5.2. -- Удалённые события и прошедшие `occurrence` не отправлять. +- `NOTIFY_TYPES['calendar.reminder']` в `server.js` (иконка `bell-ring`, `admin: false`), сид `notify_calendar_reminder` в `db/init.sql` + `db/migration.sql`. +- Доставка — личное уведомление: `pushNotification({ ..., userId })` пишет `notifications.user_id`; SSE-канал и маршруты уведомлений не менялись, кадры фильтруются по `notificationVisible` (личные видит только владелец, включая админа). +- Дедупликация — производная таблица `calendar_reminder_sent(event_id, user_id, occurrence_at, minutes, sent_at)` с `UNIQUE (event_id, user_id, minutes, occurrence_at)`; в бэкап не входит, строки старше 7 суток чистятся. При ошибке доставки запись удаляется, чтобы следующий тик повторил отправку. +- Планировщик — `createCalendarReminderWorker` в `lib/calendar.js`, запускается из `server.js`; тик раз в 60 с, окно сканирования 24 часа назад, зона через `bindTz`/`appTimezone()`, разворот повторов — тем же SQL, что в §5.2. После простоя дольше суток пропущенные напоминания не восстанавливаются. +- Удалённые события и прошедшие `occurrence` не отправлять; для общих событий (`is_common`) уведомление получают все активные пользователи. ### 7.3. Корзина @@ -621,7 +619,7 @@ curl -s -X PUT -H "X-Auth-Token: $TOKEN" http://localhost:3003/api/calendar/e ## 10. Definition of Done - [ ] 4 вида работают, неделя — основная; переключение сохраняется. -- [ ] Личные события: создание/редактирование/удаление, цвет, место, заметки, повтор, напоминания (хранение). +- [ ] Личные события: создание/редактирование/удаление, цвет, место, заметки, повтор, напоминания (хранение и доставка). - [ ] Drag-to-create с шагом 30 минут и ghost-выделением. - [ ] Строка «Весь день», красная линия «сейчас», подсветка сегодня. - [ ] Пересечения раскладываются по колонкам. @@ -641,11 +639,11 @@ curl -s -X PUT -H "X-Auth-Token: $TOKEN" http://localhost:3003/api/calendar/e ## 11. Открытые вопросы (решаются по ходу, не блокируют старт) -1. **Напоминания** — только хранить в MVP или сразу доставлять уведомления? Документ исходит из «хранить» (этап 2, см. §7.2). +1. **Напоминания** — решено доставлять личными уведомлениями `calendar.reminder` (см. §7.2); окно сканирования 24 часа, дедупликация в `calendar_reminder_sent`. 2. **Событие через полночь** — обрезать по дню или рисовать «продолжение» в следующем дне? Для MVP допустим вариант «обрезать + пометка», но выбранный вариант нужно явно описать. 3. **Несколько календарей** («Новый календарь» в референсе) — не делаем. Один личный календарь. 4. **Шаринг/публичная ссылка** — не делаем. -5. **Уведомления о событиях через SSE** — не делаем, см. §3.5 и бюджет соединений в `AGENTS.md` §4. +5. **Отдельный SSE-канал для событий календаря** — не делаем, см. §3.5 и бюджет соединений в `AGENTS.md` §4; напоминания идут через существующий SSE уведомлений. 6. **Перетаскивание/ресайз существующих событий** — не в MVP (только создание перетаскиванием). Если останется время — ресайз за нижний край, но только после §9. --- diff --git a/lib/calendar.js b/lib/calendar.js index e8c91ce..ec10ca8 100644 --- a/lib/calendar.js +++ b/lib/calendar.js @@ -17,6 +17,9 @@ const CALENDAR_TITLE_MAX = 200; const CALENDAR_NOTES_MAX = 5000; const CALENDAR_LOCATION_MAX = 200; const CALENDAR_REMINDERS_MAX = 5; +const CALENDAR_REMINDER_LOOKBACK_MS = 24 * 60 * 60 * 1000; +const CALENDAR_REMINDER_INTERVAL_MS = 60 * 1000; +const CALENDAR_REMINDER_KEEP_DAYS = 7; const CALENDAR_RANGE_MAX_DAYS = 62; const CALENDAR_MAX_DURATION_MS = 31 * 24 * 60 * 60 * 1000; const CALENDAR_SOURCES = ['groups', 'lesson_reports', 'digests']; @@ -228,6 +231,16 @@ async function ensureCalendarEventsTable(pool) { await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_user_start ON calendar_events(user_id, starts_at) WHERE deleted_at IS NULL'); await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_common_start ON calendar_events(starts_at) WHERE deleted_at IS NULL AND is_common'); await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_events_purge ON calendar_events(purge_at) WHERE purge_at IS NOT NULL'); + await pool.query(`CREATE TABLE IF NOT EXISTS calendar_reminder_sent ( + id BIGSERIAL PRIMARY KEY, + event_id INT NOT NULL REFERENCES calendar_events(id) ON DELETE CASCADE, + user_id INT NOT NULL REFERENCES users(id) ON DELETE CASCADE, + occurrence_at TIMESTAMPTZ NOT NULL, + minutes INT NOT NULL, + sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (event_id, user_id, occurrence_at, minutes) + )`); + await pool.query('CREATE INDEX IF NOT EXISTS idx_calendar_reminder_sent_sent_at ON calendar_reminder_sent(sent_at)'); } async function listCalendarEvents(pool, { userId, isAdmin, targetUser, fromIso, toIso, tz }) { @@ -494,6 +507,136 @@ async function listWorkspaceSources(pool, { admin, branchIds, fromIso, toIso, tz return out; } +async function listDueCalendarReminders(pool, { fromIso, toIso, tz }) { + const bound = bindTz(` + WITH occurrences AS ( + SELECT e.id AS event_id, e.user_id, e.is_common, e.title, e.location, + s.occ_start, + e.reminder_minutes + FROM calendar_events e + CROSS JOIN LATERAL ( + SELECT g.local_start AT TIME ZONE $TZ$ AS occ_start + FROM ( + SELECT gs AS local_start + FROM generate_series( + (e.starts_at AT TIME ZONE $TZ$), + (($2::timestamptz AT TIME ZONE $TZ$) + interval '1 day')::timestamp, + CASE e.repeat_rule + WHEN 'daily' THEN interval '1 day' + WHEN 'weekly' THEN interval '1 week' + WHEN 'monthly' THEN interval '1 month' + WHEN 'yearly' THEN interval '1 year' + END + ) AS gs + WHERE e.repeat_rule <> 'none' + ) g + WHERE e.repeat_until IS NULL OR g.local_start::date <= e.repeat_until + UNION ALL + SELECT e.starts_at AS occ_start WHERE e.repeat_rule = 'none' + ) s + WHERE e.deleted_at IS NULL AND cardinality(e.reminder_minutes) > 0 + ) + SELECT o.event_id, r.user_id, o.title, o.location, o.occ_start, m.minutes AS reminder_minutes + FROM occurrences o + CROSS JOIN LATERAL unnest(o.reminder_minutes) AS m(minutes) + CROSS JOIN LATERAL ( + SELECT o.user_id AS user_id WHERE NOT o.is_common + UNION ALL + SELECT u.id FROM users u WHERE o.is_common AND u.is_active IS NOT FALSE + ) r + WHERE o.occ_start - (m.minutes || ' minutes')::interval BETWEEN $1::timestamptz AND $2::timestamptz + AND EXISTS (SELECT 1 FROM users u WHERE u.id = r.user_id AND u.is_active IS NOT FALSE) + AND NOT EXISTS ( + SELECT 1 FROM calendar_reminder_sent s + WHERE s.event_id = o.event_id AND s.user_id = r.user_id + AND s.occurrence_at = o.occ_start AND s.minutes = m.minutes + ) + ORDER BY o.occ_start, r.user_id, m.minutes + `, [fromIso, toIso], tz); + const { rows } = await pool.query(bound.sql, bound.params); + return rows.map(r => ({ + event_id: r.event_id, + user_id: r.user_id, + title: r.title, + location: r.location || '', + occurrence_at: r.occ_start, + minutes: r.reminder_minutes, + })); +} + +function reminderTime(instant, tz) { + try { + return new Intl.DateTimeFormat('ru-RU', { + timeZone: tz || 'UTC', hour: '2-digit', minute: '2-digit', hour12: false, + }).format(new Date(instant)); + } catch { + return String(instant).slice(11, 16); + } +} + +async function sendDueCalendarReminders(pool, { notify, tz, now, lookbackMs }) { + if (typeof notify !== 'function') return { scanned: 0, sent: 0 }; + const at = now instanceof Date && !Number.isNaN(now.getTime()) ? now : new Date(); + const windowMs = Number.isFinite(lookbackMs) ? lookbackMs : CALENDAR_REMINDER_LOOKBACK_MS; + const fromIso = new Date(at.getTime() - windowMs).toISOString(); + const toIso = at.toISOString(); + const due = await listDueCalendarReminders(pool, { fromIso, toIso, tz: tz || 'UTC' }); + let sent = 0; + for (const item of due) { + const { rows } = await pool.query( + `INSERT INTO calendar_reminder_sent (event_id, user_id, occurrence_at, minutes) + VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING RETURNING id`, + [item.event_id, item.user_id, item.occurrence_at, item.minutes] + ); + if (!rows.length) continue; + const time = reminderTime(item.occurrence_at, tz); + const place = item.location ? ` · ${item.location}` : ''; + try { + await notify({ + type: 'calendar.reminder', + title: `Напоминание: ${item.title}`, + body: `Начало в ${time}${place}`, + link: 'calendar.html', + target: { event_id: item.event_id, occurrence_at: item.occurrence_at, minutes: item.minutes }, + userId: item.user_id, + adminOnly: false, + }); + sent += 1; + } catch (e) { + console.error('Calendar reminder notify:', e.message); + try { + await pool.query('DELETE FROM calendar_reminder_sent WHERE id = $1', [rows[0].id]); + } catch (cleanupError) { + console.error('Calendar reminder dedup cleanup:', cleanupError.message); + } + } + } + await pool.query(`DELETE FROM calendar_reminder_sent WHERE sent_at < now() - ($1 || ' days')::interval`, [String(CALENDAR_REMINDER_KEEP_DAYS)]); + return { scanned: due.length, sent }; +} + +function createCalendarReminderWorker({ pool, notify, timezone }) { + let timer = null; + let stopped = false; + async function tick() { + if (stopped) return; + try { + const tz = await (timezone || (() => 'UTC'))(); + const result = await sendDueCalendarReminders(pool, { notify, tz }); + if (result.sent) console.log(`Calendar reminders sent: ${result.sent} (of ${result.scanned} due)`); + } catch (e) { + console.error('Calendar reminder tick:', e.message); + } + if (!stopped) timer = setTimeout(tick, CALENDAR_REMINDER_INTERVAL_MS); + } + function start() { stopped = false; tick(); } + function stop() { stopped = true; if (timer) { clearTimeout(timer); timer = null; } } + function getInfo() { + return { interval_ms: CALENDAR_REMINDER_INTERVAL_MS, lookback_ms: CALENDAR_REMINDER_LOOKBACK_MS, stopped }; + } + return { start, stop, getInfo }; +} + module.exports = { CALENDAR_COLORS, CALENDAR_COLOR_HEX, @@ -505,6 +648,9 @@ module.exports = { CALENDAR_LOCATION_MAX, CALENDAR_RANGE_MAX_DAYS, ensureCalendarEventsTable, + listDueCalendarReminders, + sendDueCalendarReminders, + createCalendarReminderWorker, normalizeCalendarRange, validateCalendarEvent, resolveCalendarUser, diff --git a/public/admin-dark.css b/public/admin-dark.css new file mode 100644 index 0000000..054c64c --- /dev/null +++ b/public/admin-dark.css @@ -0,0 +1,1101 @@ + +/* ========================================================= + MIDNIGHT NEON — Custom Dark Theme + / Admin Dashboard + ========================================================= */ + +/* --- 1. Цветовая система --- */ + +:root { + color-scheme: dark; + + --bg: #0b0d14; + --card: #131722; + --border: #252c3b; + + --accent: #8b5cf6; + --text: #f1f5f9; + --muted: #929db2; + + --radius: 14px; + --sidebar: 250px; + + --accent-hover: #a78bfa; + --accent-soft: rgba(139, 92, 246, .13); + --accent-glow: rgba(139, 92, 246, .25); + + --surface-2: #191f2d; + --surface-3: #20283a; + + --success: #34d399; + --warning: #fbbf24; + --danger: #fb7185; + --info: #38bdf8; +} + +/* --- 2. Основной интерфейс --- */ + +html, +body { + background: var(--bg); + color: var(--text); +} + +body { + background-image: + radial-gradient( + ellipse at 15% 0%, + rgba(124, 58, 237, .07), + transparent 40% + ), + radial-gradient( + ellipse at 100% 100%, + rgba(14, 165, 233, .035), + transparent 40% + ); +} + +::selection { + background: rgba(139, 92, 246, .35); + color: #fff; +} + +/* --- 3. Боковая панель --- */ + +.sidebar { + background: #10131c; + border-right: 1px solid #242a39; + box-shadow: 8px 0 32px rgba(0, 0, 0, .12); +} + +.sidebar .logo, +.user-box, +.sidebar .bottom { + background: #10131c; + border-color: #242a39; +} + +.sidebar .logo { + letter-spacing: -.035em; +} + +.sidebar .logo-ic { + background: linear-gradient( + 135deg, + #8b5cf6, + #6366f1 + ); + border: none; + box-shadow: 0 0 18px rgba(139, 92, 246, .2); +} + +.nav-group-title { + color: #69758c; + letter-spacing: .1em; +} + +.nav-divider { + background: #252c3b; +} + +.sidebar nav a, +.sidebar .bottom-actions a { + color: #929db2; + border-radius: 9px; + transition: + background .2s ease, + color .2s ease, + transform .2s ease; +} + +.sidebar nav a:hover, +.sidebar .bottom-actions a:hover { + background: #1b2130; + color: #f1f5f9; + transform: translateX(2px); +} + +.sidebar nav a.active { + color: #c4b5fd; + background: linear-gradient( + 90deg, + rgba(139, 92, 246, .2), + rgba(99, 102, 241, .07) + ); + box-shadow: inset 0 0 0 1px rgba(139, 92, 246, .12); +} + +.sidebar nav a.active::before { + background: #a78bfa; + box-shadow: 0 0 12px rgba(167, 139, 250, .6); +} + +.sidebar nav a.active svg { + color: #a78bfa; +} + +.user-box .user-avatar { + background: rgba(139, 92, 246, .15); + color: #c4b5fd; +} + +.sidebar .bottom-footer { + border-color: #252c3b; +} + +/* --- 4. Основной контент --- */ + +.main { + background: transparent; +} + +.main h2 { + color: #f8fafc; + font-weight: 700; + letter-spacing: -.035em; +} + +h1, +h2, +h3, +h4, +h5 { + color: #f1f5f9; +} + +/* --- 5. Карточки и панели --- */ + +.stat, +.card, +.journal-card, +.item, +.group-card, +.settings-card, +.stu-filters { + background: linear-gradient( + 145deg, + #161b28, + #121621 + ); + border: 1px solid #272e40; + border-radius: var(--radius); + box-shadow: 0 8px 24px rgba(0, 0, 0, .12); + transition: + border-color .2s ease, + box-shadow .2s ease, + transform .2s ease; +} + +.stat:hover, +.card:hover, +.group-card:hover { + border-color: #39435b; +} + +.stat .num { + color: #a78bfa; +} + +.stat .label, +.stat .stat-sub { + color: var(--muted); +} + +.stat-bar { + background: #252c3b; +} + +.stat-bar i { + background: linear-gradient( + 90deg, + #8b5cf6, + #38bdf8 + ); + box-shadow: 0 0 12px rgba(139, 92, 246, .25); +} + +/* --- 6. Поля ввода --- */ + +input, +select, +textarea, +.search-input, +.filters select, +.filters input[type="date"] { + background-color: #0e121c; + color: #e2e8f0; + border-color: #2b3346; +} + +input::placeholder, +textarea::placeholder { + color: #68748b; +} + +input:focus, +select:focus, +textarea:focus, +.search-input:focus, +.filters select:focus, +.filters input:focus { + border-color: #8b5cf6 !important; + box-shadow: 0 0 0 3px rgba(139, 92, 246, .15); + outline: none; +} + +#studentFilter, +#linkStudent, +#moduleFilter { + background: #0e121c; + color: #e2e8f0; + border-color: #2b3346; +} + +/* --- 7. Кнопки --- */ + +button, +.btn-link, +.btn-primary { + transition: + background .2s ease, + border-color .2s ease, + box-shadow .2s ease, + transform .15s ease; +} + +.add-row button, +.student-actions .btn-save, +.stu-item .btn-save, +.stu-item .stu-open, +.group-card .save-sched, +.settings-card .btn-link, +.edit-modal .save, +.pager button.active { + background: linear-gradient( + 135deg, + #8b5cf6, + #6366f1 + ); + color: #fff; + border-color: transparent; + box-shadow: 0 4px 14px rgba(139, 92, 246, .18); +} + +.add-row button:hover, +.student-actions .btn-save:hover, +.stu-item .btn-save:hover, +.group-card .save-sched:hover, +.settings-card .btn-link:hover, +.edit-modal .save:hover { + background: linear-gradient( + 135deg, + #a78bfa, + #818cf8 + ); + box-shadow: 0 5px 20px rgba(139, 92, 246, .3); + transform: translateY(-1px); +} + +.btn-link, +.add-row .btn-ghost, +.stu-tool-acts .btn-link { + background: #191f2d; + color: #c4b5fd; + border-color: #30394e; +} + +.btn-link:hover, +.add-row .btn-ghost:hover { + background: #222a3c; + border-color: #8b5cf6; +} + +/* --- 8. Списки и строки --- */ + +.item:hover, +.stu-item:hover, +.pf-row:hover { + border-color: rgba(139, 92, 246, .4); +} + +.stu-item:focus-within { + border-color: #8b5cf6; + box-shadow: 0 0 0 3px rgba(139, 92, 246, .1); +} + +.stu-item .group-select, +.stu-item .stu-status-select, +.group-card .name-input, +.group-schedule select, +.group-schedule input[type="time"] { + background: #0e121c; + border-color: #2b3346; + color: #e2e8f0; +} + +.stu-item .stu-open { + color: #fff; +} + +.stu-menu { + background: #171d2a; + border-color: #30394e; + box-shadow: 0 16px 40px rgba(0, 0, 0, .45); +} + +.stu-menu-item { + color: #cbd5e1; +} + +.stu-menu-item:hover { + background: #252d40; + color: #c4b5fd; +} + +/* --- 9. Журнал и фотографии --- */ + +.journal-card { + overflow: hidden; +} + +.journal-card .body { + background: transparent; +} + +.journal-card .foot { + background: #111622; + border-color: #272e40; +} + +.journal-card .no-photo, +.img-media, +.img-media .img-skeleton { + background: #0e121c; +} + +.group-badge { + background: rgba(15, 18, 30, .8); + border: 1px solid rgba(255, 255, 255, .1); + backdrop-filter: blur(12px); +} + +.entry-files .f-item, +.entry-files a { + background: #191f2d; + border-color: #2b3346; + color: #cbd5e1; +} + +/* --- 10. Модальные окна --- */ + +.modal-overlay { + background: rgba(3, 5, 12, .78); + backdrop-filter: blur(8px); +} + +.edit-modal, +.video-modal { + background: linear-gradient( + 145deg, + #191f2d, + #121621 + ); + border: 1px solid #30394e; + border-radius: 18px; + box-shadow: + 0 24px 80px rgba(0, 0, 0, .5), + 0 0 30px rgba(139, 92, 246, .05); +} + +.edit-modal label { + color: #a0aec0; +} + +.edit-modal input, +.edit-modal select, +.edit-modal textarea { + background: #0e121c; + border-color: #2b3346; + color: #e2e8f0; +} + +.edit-modal .cancel, +.edit-modal .cancel-btn { + background: #252c3b; + color: #cbd5e1; +} + +/* --- 11. Профиль ученика --- */ + +.pf-head, +.pf-foot { + background: #141925; + border-color: #2b3346; +} + +.pf-tabs { + background: #111622; + border-color: #2b3346; +} + +.pf-tab { + color: #929db2; +} + +.pf-tab:hover { + background: #20283a; + color: #f1f5f9; +} + +.pf-tab.is-active { + background: rgba(139, 92, 246, .15); + color: #c4b5fd; + border-color: rgba(139, 92, 246, .3); +} + +.pf-tile, +.pf-row, +.pf-chip { + background: #171d2a; + border-color: #2b3346; +} + +.pf-f input, +.pf-f textarea, +.pf-f select { + background: #0e121c; + border-color: #2b3346; + color: #e2e8f0; +} + +.pf-meter { + background: #2b3346; +} + +.pf-meter i { + background: linear-gradient( + 90deg, + #8b5cf6, + #38bdf8 + ); +} + +/* --- 12. Скроллбары --- */ + +* { + scrollbar-color: #39435b #111622; + scrollbar-width: thin; +} + +::-webkit-scrollbar { + width: 8px; + height: 8px; +} + +::-webkit-scrollbar-track { + background: #111622; +} + +::-webkit-scrollbar-thumb { + background: #39435b; + border-radius: 8px; +} + +::-webkit-scrollbar-thumb:hover { + background: #596782; +} + +/* --- 13. Микроанимации --- */ + +@keyframes neonPulse { + 0%, 100% { + box-shadow: 0 0 8px rgba(139, 92, 246, .1); + } + 50% { + box-shadow: 0 0 18px rgba(139, 92, 246, .2); + } +} + +.sidebar nav a.active { + animation: neonPulse 4s ease-in-out infinite; +} + +@media (prefers-reduced-motion: reduce) { + *, + *::before, + *::after { + animation-duration: .01ms !important; + animation-iteration-count: 1 !important; + transition-duration: .01ms !important; + } +} +/* ========================================================= + MIDNIGHT NEON — DARK THEME + Включение: html.midnight-neon + ========================================================= */ + + +/* --------------------------------------------------------- + 1. Цветовая палитра + --------------------------------------------------------- */ + +html.midnight-neon { + color-scheme: dark; + + --bg: #0b0d12; + --card: #131722; + --border: #252c3a; + + --accent: #8b5cf6; + --text: #edf0f7; + --muted: #929bb0; + + --radius: 12px; + + --sc-primary: #8b5cf6; + --sc-primary-soft: rgba(139, 92, 246, 0.12); + --sc-border: #2b3142; + + --dark-bg: #0b0d12; + --dark-card: #131722; + --dark-card-hover: #1a2030; + + --purple: #8b5cf6; + --purple-hover: #a78bfa; + --blue: #38bdf8; + --green: #34d399; + --red: #fb7185; + --orange: #fb923c; +} + + +/* --------------------------------------------------------- + 2. Основная страница + --------------------------------------------------------- */ + +html.midnight-neon body { + background: var(--bg) !important; + color: var(--text) !important; + color-scheme: dark; +} + +html.midnight-neon body, +html.midnight-neon button, +html.midnight-neon input, +html.midnight-neon select, +html.midnight-neon textarea { + font-family: inherit; +} + +html.midnight-neon * { + scrollbar-color: #343b4d #10131b; +} + +html.midnight-neon *::-webkit-scrollbar { + width: 8px; + height: 8px; +} + +html.midnight-neon *::-webkit-scrollbar-track { + background: #10131b; +} + +html.midnight-neon *::-webkit-scrollbar-thumb { + background: #343b4d; + border-radius: 10px; +} + +html.midnight-neon *::-webkit-scrollbar-thumb:hover { + background: #4b556b; +} + + +/* --------------------------------------------------------- + 3. Основные контейнеры + --------------------------------------------------------- */ + +html.midnight-neon .layout { + background: var(--bg); + color: var(--text); +} + +html.midnight-neon main, +html.midnight-neon .main, +html.midnight-neon .main-content, +html.midnight-neon .content, +html.midnight-neon .page-content { + background: var(--bg); + color: var(--text); +} + +html.midnight-neon section, +html.midnight-neon article { + color: var(--text); +} + + +/* --------------------------------------------------------- + 4. Боковая панель + --------------------------------------------------------- */ + +html.midnight-neon .sidebar { + background: #10131b !important; + border-right: 1px solid #252b3a !important; + box-shadow: 5px 0 25px rgba(0, 0, 0, 0.12); +} + +html.midnight-neon .sidebar .logo { + background: #10131b !important; + border-bottom-color: #252b3a !important; + color: #f1f5f9 !important; +} + +html.midnight-neon .sidebar .logo-ic { + background: #191e2b !important; + border-color: #30384b !important; +} + +html.midnight-neon .user-box { + background: #10131b !important; + border-bottom-color: #252b3a !important; +} + +html.midnight-neon .user-box .user-name { + color: #f1f5f9 !important; +} + +html.midnight-neon .user-box .user-role { + color: #929bb0 !important; +} + +html.midnight-neon .user-box .user-avatar { + background: rgba(139, 92, 246, 0.14) !important; + color: #a78bfa !important; +} + +html.midnight-neon .sidebar a, +html.midnight-neon .sidebar button { + color: #a8b0c2; + transition: + background 0.18s ease, + color 0.18s ease, + border-color 0.18s ease; +} + +html.midnight-neon .sidebar a:hover, +html.midnight-neon .sidebar button:hover { + background: #1a2030 !important; + color: #ffffff !important; +} + +html.midnight-neon .sidebar a.active, +html.midnight-neon .sidebar .active { + background: rgba(139, 92, 246, 0.16) !important; + color: #c4b5fd !important; + border-color: rgba(139, 92, 246, 0.28) !important; +} + + +/* --------------------------------------------------------- + 5. Карточки и панели + --------------------------------------------------------- */ + +html.midnight-neon .card, +html.midnight-neon .panel, +html.midnight-neon .modal-content, +html.midnight-neon .dropdown-menu, +html.midnight-neon .popover, +html.midnight-neon .report-fields__panel { + background: var(--card) !important; + color: var(--text) !important; + border-color: var(--border) !important; +} + +html.midnight-neon .card, +html.midnight-neon .panel { + border-radius: var(--radius); +} + +html.midnight-neon .card-header, +html.midnight-neon .card-footer, +html.midnight-neon .panel-header, +html.midnight-neon .panel-footer { + background: #171c29 !important; + color: var(--text) !important; + border-color: var(--border) !important; +} + + +/* --------------------------------------------------------- + 6. Таблицы + --------------------------------------------------------- */ + +html.midnight-neon table { + color: var(--text) !important; + border-color: var(--border) !important; +} + +html.midnight-neon table th { + background: #171c29 !important; + color: #b7c0d3 !important; + border-color: var(--border) !important; +} + +html.midnight-neon table td { + background: #131722 !important; + color: #e2e8f0 !important; + border-color: #252c3a !important; +} + +html.midnight-neon table tbody tr:hover td { + background: #1a2030 !important; +} + +html.midnight-neon .table-striped tbody tr:nth-of-type(odd) td { + background: #161b27 !important; +} + +html.midnight-neon .table-striped tbody tr:hover td { + background: #1e2535 !important; +} + + +/* --------------------------------------------------------- + 7. Формы и поля ввода + --------------------------------------------------------- */ + +html.midnight-neon input:not([type="checkbox"]):not([type="radio"]):not([type="range"]), +html.midnight-neon textarea, +html.midnight-neon select { + background: #0f131d !important; + color: #edf0f7 !important; + border: 1px solid #30384b !important; + border-radius: 9px; +} + +html.midnight-neon input::placeholder, +html.midnight-neon textarea::placeholder { + color: #68738a !important; + opacity: 1; +} + +html.midnight-neon input:focus, +html.midnight-neon textarea:focus, +html.midnight-neon select:focus { + border-color: #8b5cf6 !important; + outline: none !important; + box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.15) !important; +} + +html.midnight-neon input[type="checkbox"], +html.midnight-neon input[type="radio"] { + accent-color: #8b5cf6; +} + +html.midnight-neon option { + background: #131722; + color: #edf0f7; +} + + +/* --------------------------------------------------------- + 8. Кнопки + --------------------------------------------------------- */ + +html.midnight-neon button, +html.midnight-neon .btn { + transition: + background 0.18s ease, + border-color 0.18s ease, + color 0.18s ease, + transform 0.18s ease; +} + +html.midnight-neon .btn-primary { + background: #8b5cf6 !important; + color: #ffffff !important; + border-color: #8b5cf6 !important; +} + +html.midnight-neon .btn-primary:hover { + background: #7c3aed !important; + border-color: #7c3aed !important; + transform: translateY(-1px); +} + +html.midnight-neon .btn-secondary, +html.midnight-neon .btn-light { + background: #202637 !important; + color: #e2e8f0 !important; + border-color: #30384b !important; +} + +html.midnight-neon .btn-secondary:hover, +html.midnight-neon .btn-light:hover { + background: #2b3449 !important; + color: #ffffff !important; +} + +html.midnight-neon .btn-outline-primary { + color: #a78bfa !important; + border-color: #8b5cf6 !important; + background: transparent !important; +} + +html.midnight-neon .btn-outline-primary:hover { + background: rgba(139, 92, 246, 0.15) !important; +} + + +/* --------------------------------------------------------- + 9. Ссылки и текст + --------------------------------------------------------- */ + +html.midnight-neon a { + color: #a78bfa; +} + +html.midnight-neon a:hover { + color: #c4b5fd; +} + +html.midnight-neon h1, +html.midnight-neon h2, +html.midnight-neon h3, +html.midnight-neon h4, +html.midnight-neon h5, +html.midnight-neon h6 { + color: #f1f5f9; +} + +html.midnight-neon p, +html.midnight-neon label, +html.midnight-neon small { + color: inherit; +} + +html.midnight-neon .text-muted, +html.midnight-neon .muted { + color: #929bb0 !important; +} + + +/* --------------------------------------------------------- + 10. Выпадающие меню и модальные окна + --------------------------------------------------------- */ + +html.midnight-neon .dropdown-menu { + background: #151a27 !important; + border: 1px solid #30384b !important; + box-shadow: 0 15px 40px rgba(0, 0, 0, 0.35); +} + +html.midnight-neon .dropdown-item { + color: #dce3f0 !important; +} + +html.midnight-neon .dropdown-item:hover, +html.midnight-neon .dropdown-item:focus { + background: #242b3d !important; + color: #ffffff !important; +} + +html.midnight-neon .modal-content { + background: #151a27 !important; + border: 1px solid #30384b !important; + box-shadow: 0 25px 80px rgba(0, 0, 0, 0.4); +} + +html.midnight-neon .modal-header, +html.midnight-neon .modal-footer { + border-color: #30384b !important; +} + + +/* --------------------------------------------------------- + 11. Бейджи и статусы + --------------------------------------------------------- */ + +html.midnight-neon .badge { + border: 1px solid transparent; +} + +html.midnight-neon .badge-primary { + background: rgba(139, 92, 246, 0.18) !important; + color: #c4b5fd !important; +} + +html.midnight-neon .badge-success { + background: rgba(52, 211, 153, 0.14) !important; + color: #6ee7b7 !important; +} + +html.midnight-neon .badge-danger { + background: rgba(251, 113, 133, 0.14) !important; + color: #fda4af !important; +} + +html.midnight-neon .badge-warning { + background: rgba(251, 146, 60, 0.14) !important; + color: #fdba74 !important; +} + + +/* --------------------------------------------------------- + 12. Уведомления + --------------------------------------------------------- */ + +html.midnight-neon .alert { + background: #171c29 !important; + color: #e2e8f0 !important; + border-color: #30384b !important; +} + +html.midnight-neon .alert-success { + background: rgba(52, 211, 153, 0.1) !important; + color: #6ee7b7 !important; + border-color: rgba(52, 211, 153, 0.25) !important; +} + +html.midnight-neon .alert-danger { + background: rgba(251, 113, 133, 0.1) !important; + color: #fda4af !important; + border-color: rgba(251, 113, 133, 0.25) !important; +} + +html.midnight-neon .alert-warning { + background: rgba(251, 146, 60, 0.1) !important; + color: #fdba74 !important; + border-color: rgba(251, 146, 60, 0.25) !important; +} + + +/* --------------------------------------------------------- + 13. Разделители + --------------------------------------------------------- */ + +html.midnight-neon hr { + border-color: #252c3a !important; + opacity: 1; +} + +html.midnight-neon .border, +html.midnight-neon .border-top, +html.midnight-neon .border-bottom, +html.midnight-neon .border-left, +html.midnight-neon .border-right { + border-color: #252c3a !important; +} + + +/* --------------------------------------------------------- + 14. Отчёты и специфические элементы + --------------------------------------------------------- */ + +html.midnight-neon .report-fields__btn { + background: #171c29 !important; + color: #e2e8f0 !important; + border-color: #30384b !important; +} + +html.midnight-neon .report-fields__btn:hover { + color: #c4b5fd !important; + border-color: #8b5cf6 !important; +} + +html.midnight-neon .report-fields__panel { + background: #151a27 !important; + border-color: #30384b !important; +} + +html.midnight-neon .report-fields__item:hover { + background: #202637 !important; +} + +html.midnight-neon .report-fields__track { + background: #30384b !important; +} + +html.midnight-neon .report-fields__toggle input:checked + .report-fields__track { + background: #8b5cf6 !important; +} + +html.midnight-neon .report-fields__shot { + background: #8b5cf6 !important; + color: #ffffff !important; +} + +html.midnight-neon .student-card__gallery-grid { + color: #e2e8f0; +} + +html.midnight-neon .sc-gal__shot { + background: #171c29 !important; + border-color: #30384b !important; +} + +html.midnight-neon .sc-gal__shot:hover { + border-color: #8b5cf6 !important; + box-shadow: 0 10px 25px rgba(139, 92, 246, 0.16); +} + + +/* --------------------------------------------------------- + 15. Исправление светлых элементов + --------------------------------------------------------- */ + +html.midnight-neon .face-assign-select { + background: #0f131d !important; + color: #edf0f7 !important; + border-color: #30384b !important; +} + +html.midnight-neon [style*="background:#fff"], +html.midnight-neon [style*="background: #fff"], +html.midnight-neon [style*="background-color:#fff"], +html.midnight-neon [style*="background-color: #fff"], +html.midnight-neon [style*="background: white"], +html.midnight-neon [style*="background-color: white"] { + background-color: #131722 !important; + color: #edf0f7 !important; +} + +html.midnight-neon [style*="#fff7ed"], +html.midnight-neon [style*="#fff7ed"] * { + background-color: #241b17 !important; + color: #fdba74 !important; +} + + +/* --------------------------------------------------------- + 16. Плавное переключение + --------------------------------------------------------- */ + +html.midnight-neon body, +html.midnight-neon .sidebar, +html.midnight-neon .card, +html.midnight-neon .panel, +html.midnight-neon input, +html.midnight-neon select, +html.midnight-neon textarea, +html.midnight-neon button { + transition: + background-color 0.2s ease, + color 0.2s ease, + border-color 0.2s ease; +} + + +/* --------------------------------------------------------- + 17. Уважение системной настройки reduced motion + --------------------------------------------------------- */ + +@media (prefers-reduced-motion: reduce) { + html.midnight-neon *, + html.midnight-neon *::before, + html.midnight-neon *::after { + animation-duration: 0.01ms !important; + animation-iteration-count: 1 !important; + transition-duration: 0.01ms !important; + } +} diff --git a/public/admin.js b/public/admin.js index d592c31..1d5176a 100644 --- a/public/admin.js +++ b/public/admin.js @@ -253,6 +253,7 @@ const NOTIFY_ICONS = { 'face.recognized': 'user-round-check', 'face.scan.error': 'scan-search', 'chat.message': 'bell', + 'calendar.reminder': 'bell-ring', }; const NOTIFY_LEVELS = { warning: 'Предупреждение', critical: 'Важно', info: '' }; diff --git a/public/calendar.html b/public/calendar.html index aab0338..74cc697 100644 --- a/public/calendar.html +++ b/public/calendar.html @@ -32,6 +32,8 @@ .cal-head{display:flex;align-items:center;gap:10px;padding:14px 18px;border-bottom:1px solid var(--border);flex-wrap:wrap} .cal-head-left,.cal-head-right{display:flex;align-items:center;gap:8px} .cal-head-left{flex:1;min-width:0} + .cal-user-filter{margin-bottom:0} + .cal-user-filter select{max-width:180px} .cal-head h2{margin:0 0 0 6px;font-size:1.15rem;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .cal-nav-btn{width:32px;height:32px;display:inline-flex;align-items:center;justify-content:center;border:1px solid var(--border);border-radius:8px;background:var(--card);color:var(--text);cursor:pointer;font-size:1rem} .cal-nav-btn:hover{border-color:var(--accent);color:var(--accent)} @@ -151,7 +153,7 @@

Из системы

-
Напоминания сохраняются в событиях; доставка уведомлений будет добавлена отдельно.
+
Напоминания приходят в уведомления в выбранное время до события.
@@ -162,7 +164,7 @@

- +
diff --git a/public/js/calendar.js b/public/js/calendar.js index 0107dcb..80c7762 100644 --- a/public/js/calendar.js +++ b/public/js/calendar.js @@ -91,7 +91,7 @@ function renderUserFilter() { const sel = document.getElementById('calUserFilter'); - sel.classList.toggle('cal-hidden', !isAdmin()); + sel.closest('.cal-user-filter').classList.toggle('cal-hidden', !isAdmin()); if (!isAdmin()) return; sel.innerHTML = '' + state.users.map(userOption).join(''); sel.value = state.ownerFilter; diff --git a/server.js b/server.js index cb4bdf9..162435f 100644 --- a/server.js +++ b/server.js @@ -132,6 +132,7 @@ const { restoreCalendarEvent, deleteCalendarEventPermanent, listWorkspaceSources, + createCalendarReminderWorker, } = require('./lib/calendar'); const { parseTaskKey, getTaskStates, getClosures, saveStepState, closeTask, reopenTask, ensurePostLessonTaskTables } = require('./lib/post-lesson-tasks'); const { normalizeEntryClientId, findEntryByClientId, entryExistsByClientId } = require('./lib/entry-submit'); @@ -395,6 +396,7 @@ const NOTIFY_TYPES = { '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) { @@ -428,6 +430,7 @@ 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; @@ -452,15 +455,15 @@ cache.on(NOTIFY_CHANNEL, message => { } }); -async function pushNotification({ type, title, body, link, target, branchId, level, adminOnly }) { +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) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8) - RETURNING id, type, level, title, body, link, target, admin_only, branch_id, created_at`, + `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', @@ -470,6 +473,7 @@ async function pushNotification({ type, title, body, link, target, branchId, lev 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]; @@ -586,10 +590,13 @@ async function ensureNotificationsTable() { 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, @@ -704,15 +711,15 @@ async function purgeOldChat() { function notificationsScope(user) { const s = branchScope(user); - if (s.admin) return { cond: '', params: [] }; + if (s.admin) return { cond: '(n.user_id IS NULL OR n.user_id = $1)', params: [] }; const params = []; - let cond = 'n.admin_only = false'; + let branch = 'n.admin_only = false'; if (s.ids.length) { - cond += ` AND (n.branch_id IS NULL OR n.branch_id IN (${s.ids.map(id => '$' + (params.push(id) + 1)).join(',')}))`; + branch += ` AND (n.branch_id IS NULL OR n.branch_id IN (${s.ids.map(id => '$' + (params.push(id) + 1)).join(',')}))`; } else { - cond += ' AND n.branch_id IS NULL'; + branch += ' AND n.branch_id IS NULL'; } - return { cond, params }; + return { cond: `(n.user_id = $1 OR (n.user_id IS NULL AND ${branch}))`, params }; } async function notificationsCounts(user) { @@ -3082,7 +3089,7 @@ app.get('/api/notifications', requireAuth, notificationLimiter, async (req, res) 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.created_at, + `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 @@ -3148,9 +3155,10 @@ app.post('/api/notifications/:id/read', requireAuth, notificationLimiter, async 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 = $1${scope.cond ? ' AND (' + scope.cond + ')' : ''}`, - [id, ...scope.params] + `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( @@ -3174,14 +3182,17 @@ app.post('/api/notifications/test', requireAdmin, notificationLimiter, async (re 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', [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'); + 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 }); }); @@ -8083,9 +8094,10 @@ app.post('/api/restore', requireAdmin, backupUploadGuard, uploadBackup.single('b } for (const x of ndata.notifications) { const okBranch = x.branch_id == null || (await client.query('SELECT 1 FROM branches WHERE id = $1', [x.branch_id])).rowCount; + const okUser = x.user_id == null || (await client.query('SELECT 1 FROM users WHERE id = $1', [x.user_id])).rowCount; await client.query( - 'INSERT INTO notifications (id, type, level, title, body, link, target, admin_only, branch_id, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)', - [x.id, x.type, x.level, x.title, x.body, x.link, x.target, x.admin_only, okBranch ? x.branch_id : null, x.created_at] + 'INSERT INTO notifications (id, type, level, title, body, link, target, admin_only, branch_id, user_id, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)', + [x.id, x.type, x.level, x.title, x.body, x.link, x.target, x.admin_only, okBranch ? x.branch_id : null, okUser ? x.user_id : null, x.created_at] ); } for (const x of ndata.notification_reads) { @@ -15909,4 +15921,11 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab digestPublisher = createDigestPublisher({ pool, onDone: onDigestPublished }); digestPublisher.start(); console.log('Digest publisher started'); + const calendarReminderWorker = createCalendarReminderWorker({ + pool, + notify: pushNotification, + timezone: appTimezone, + }); + calendarReminderWorker.start(); + console.log('Calendar reminder worker started'); })();