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

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
+146
View File
@@ -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,