Календарь: напоминания личными уведомлениями и тёмная тема

This commit is contained in:
dev
2026-11-27 09:56:11 +03:00
parent 9960e2e8bd
commit cde281fd89
15 changed files with 1349 additions and 45 deletions
+35 -16
View File
@@ -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');
})();