// Notification preferences and routing (PEP-35): every notification belongs to an event, // the user picks channels per event (Telegram, browser push), quiet hours and projects. import { projectMembers, projects, users, type Db } from "@peppa/db"; import { eq, inArray } from "drizzle-orm"; import { getSetting, setSetting } from "./settings.ts"; import { enqueueTelegram, type OutboxRow } from "./telegram.ts"; import type { Question } from "./tasks.ts"; import type { User } from "./users.ts"; import { enqueuePush, type PushPayload } from "./webpush.ts"; import { addMasterMessage } from "./chats.ts"; import { getUserLocale } from "./locale.ts"; import { localizeText, m as tr, type Locale } from "@peppa/shared/i18n"; /** PEP-98: a rendered message (Telegram text, push body) in `locale` — see localizeText. */ export function localizeMessage(locale: Locale, text: string): string { return localizeText(locale, text); } /** Telegram HTML → plain text for the web chat. */ export function htmlToText(html: string): string { return html .replace(//gi, "\n") .replace(/]*>([^<]*)<\/a>/gi, (_m, href: string, t: string) => (t && t !== href ? `${t} (${href})` : href)) .replace(/<[^>]+>/g, "") .replace(/</g, "<") .replace(/>/g, ">") .replace(/"/g, '"') .replace(/'/g, "'") .replace(/&/g, "&"); } export const NOTIFY_EVENTS = ["questions", "review", "failures", "releases", "incidents", "chat", "monitoring", "users", "digest", "platform"] as const; export type NotifyEvent = (typeof NOTIFY_EVENTS)[number]; export const NOTIFY_EVENT_NAMES: Record = { questions: tr("Вопросы агентов"), review: tr("Готово к ревью"), failures: tr("Сбои, зависания и лимиты агентов"), releases: tr("Обновления продукта"), incidents: tr("Ошибки в продукте"), chat: tr("Сообщения в обсуждении проекта"), monitoring: tr("Мониторинг Peppa FACTORY (админам)"), users: tr("Новые пользователи (админам)"), digest: tr("Ежедневный дайджест"), platform: tr("Дайджест обновлений Peppa FACTORY"), }; export interface Channels { telegram: boolean; push: boolean; } export interface NotifyPrefs { events: Record; /** "HH:MM"–"HH:MM" in `timezone`; may cross midnight. null = off. */ quiet: { from: string; to: string } | null; /** IANA zone for quiet hours and the digest. */ timezone: string; /** "HH:MM" local time of the daily digest. */ digestTime: string; /** Sound for browser notifications and the open tab. */ sound: boolean; /** Projects the user doesn't want notifications from. */ mutedProjects: number[]; } const prefsKey = (userId: number) => `notify.prefs:${userId}`; export const serverTimezone = () => process.env.PEPPA_TZ || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; export function defaultPrefs(): NotifyPrefs { const on = { telegram: true, push: true }; return { events: { questions: on, review: on, failures: on, releases: on, incidents: on, chat: on, monitoring: on, users: on, digest: { telegram: true, push: false }, platform: { telegram: true, push: false } }, quiet: null, timezone: serverTimezone(), digestTime: "09:00", sound: true, mutedProjects: [], }; } const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/; export function isValidTimezone(tz: string): boolean { try { new Intl.DateTimeFormat("en-US", { timeZone: tz }); return true; } catch { return false; } } /** Saved preferences merged over the defaults (new events get their default). */ export async function getNotifyPrefs(db: Db, userId: number): Promise { const d = defaultPrefs(); const s = (await getSetting>(db, prefsKey(userId))) ?? {}; const events = { ...d.events }; for (const e of NOTIFY_EVENTS) if (s.events?.[e]) events[e] = { ...d.events[e], ...s.events[e] }; return { events, quiet: s.quiet && HHMM.test(s.quiet.from) && HHMM.test(s.quiet.to) ? s.quiet : null, timezone: s.timezone && isValidTimezone(s.timezone) ? s.timezone : d.timezone, digestTime: s.digestTime && HHMM.test(s.digestTime) ? s.digestTime : d.digestTime, sound: s.sound ?? d.sound, mutedProjects: Array.isArray(s.mutedProjects) ? s.mutedProjects.filter((n) => Number.isInteger(n)) : [], }; } export async function setNotifyPrefs(db: Db, userId: number, p: NotifyPrefs): Promise { if (p.quiet && (!HHMM.test(p.quiet.from) || !HHMM.test(p.quiet.to))) throw new Error(tr("Тихие часы: время в формате ЧЧ:ММ")); if (p.quiet && p.quiet.from === p.quiet.to) throw new Error(tr("Тихие часы: начало и конец совпадают")); if (!HHMM.test(p.digestTime)) throw new Error(tr("Время дайджеста: формат ЧЧ:ММ")); if (!isValidTimezone(p.timezone)) throw new Error(tr("Неизвестная таймзона: {tz}", { tz: p.timezone })); await setSetting(db, prefsKey(userId), p); return getNotifyPrefs(db, userId); } /** Local wall clock of `now` in `tz`: date "YYYY-MM-DD" and minutes since midnight. */ export function localClock(now: Date, tz: string): { date: string; minutes: number; hhmm: string } { const parts = Object.fromEntries( new Intl.DateTimeFormat("en-CA", { timeZone: tz, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }) .formatToParts(now) .map((p) => [p.type, p.value]), ); const minutes = Number(parts.hour) * 60 + Number(parts.minute); return { date: `${parts.year}-${parts.month}-${parts.day}`, minutes, hhmm: `${parts.hour}:${parts.minute}` }; } export const hhmmToMinutes = (s: string) => Number(s.slice(0, 2)) * 60 + Number(s.slice(3, 5)); export function inQuietHours(prefs: Pick, now = new Date()): boolean { if (!prefs.quiet) return false; const m = localClock(now, prefs.timezone).minutes; const from = hhmmToMinutes(prefs.quiet.from); const to = hhmmToMinutes(prefs.quiet.to); return from < to ? m >= from && m < to : m >= from || m < to; } /** Which event a PM question stands for. */ export function questionEvent(q: Pick, ctx: { taskStatus?: string | null; sessionStatus?: string | null }): NotifyEvent { if (q.kind !== "attention") return q.taskId == null && q.sessionId == null ? "releases" : "questions"; if (ctx.taskStatus === "review") return "review"; if (ctx.sessionStatus && ["failed", "rate_limited", "stalled"].includes(ctx.sessionStatus)) return "failures"; if (q.taskId == null && q.sessionId == null) return "releases"; return "questions"; } /** Owner and members of a project (whether or not they paired Telegram). */ export async function projectAudience(db: Db, projectId: number): Promise { const [p] = await db.select({ ownerId: projects.ownerId }).from(projects).where(eq(projects.id, projectId)); const members = await db.select({ id: projectMembers.userId }).from(projectMembers).where(eq(projectMembers.projectId, projectId)); const ids = [...new Set([p?.ownerId, ...members.map((m) => m.id)].filter((x): x is number => x != null))]; if (!ids.length) return []; return (await db.select().from(users).where(inArray(users.id, ids))).filter((u) => !u.disabledAt); } export interface Delivery { event: NotifyEvent; /** Muting a project silences it; null = not about a project (monitoring, digest). */ projectId?: number | null; /** Telegram outbox key for this user's message (push keys derive from it). */ dedupeKey: string; /** Push outbox key prefix if it must not depend on the Telegram key (default: dedupeKey). */ pushKey?: string; telegram?: { method?: OutboxRow["method"]; params: Record; questionId?: number }; push?: PushPayload; urgency?: "normal" | "high"; now?: Date; } export interface Delivered { telegram: boolean; push: number; /** Skipped by preferences (muted project / event off). */ muted: boolean; } /** Routes one notification to one user by their preferences. */ export async function deliverToUser(db: Db, user: User, d: Delivery, prefs?: NotifyPrefs): Promise { // PEP-62: monitoring and the digest also land in the user's master chat (a feed, not a channel). if (d.projectId == null && (d.event === "monitoring" || d.event === "digest") && typeof d.telegram?.params.text === "string") { const text = htmlToText(d.telegram.params.text); await addMasterMessage(db, user.id, { kind: "event", important: true, text, dedupeKey: `master:u${user.id}:${d.dedupeKey}`, url: d.push?.url ?? null }).catch(() => null); } const p = prefs ?? (await getNotifyPrefs(db, user.id)); const out: Delivered = { telegram: false, push: 0, muted: false }; if (d.projectId != null && p.mutedProjects.includes(d.projectId)) return { ...out, muted: true }; const ch = p.events[d.event]; if (!ch.telegram && !ch.push) return { ...out, muted: true }; // The digest comes at a time the user picked, so quiet hours don't apply to it. const quiet = d.event !== "digest" && inQuietHours(p, d.now); if (ch.telegram && d.telegram && user.telegramChatId) { out.telegram = await enqueueTelegram(db, { dedupeKey: d.dedupeKey, method: d.telegram.method ?? "sendMessage", questionId: d.telegram.questionId, params: { ...d.telegram.params, chat_id: user.telegramChatId, ...(quiet ? { disable_notification: true } : {}) }, }); } if (ch.push && d.push && !quiet) { // PEP-98: push text in the user's language (Telegram is translated by the bot when sent). const locale = await getUserLocale(db, user.id); const push = locale === "ru" ? d.push : { ...d.push, title: localizeMessage(locale, d.push.title), body: localizeMessage(locale, d.push.body) }; out.push = await enqueuePush(db, user.id, { dedupeKey: d.pushKey ?? d.dedupeKey, payload: { ...push, sound: d.push.sound ?? p.sound }, urgency: d.urgency }); } return out; } /** * An informational message about a project's runner (no buttons, nothing to answer), e.g. * «переключил на подписку X» (PEP-39): to the project's owner and members by their * preferences, as a «failures» event (limits belong there). `dedupeKey` makes it once per * event. Returns how many users got it. */ export async function sendProjectMessage(db: Db, projectId: number, text: string, dedupeKey: string, push: { title: string; url: string }): Promise { let sent = 0; for (const u of await projectAudience(db, projectId)) { const r = await deliverToUser(db, u, { event: "failures", projectId, dedupeKey: `${dedupeKey}:${u.telegramChatId}`, pushKey: `${dedupeKey}:u${u.id}`, telegram: { params: { text } }, push: { title: push.title, body: text.slice(0, 200), url: push.url, tag: dedupeKey }, }); if (r.telegram || r.push) sent++; } return sent; }