peppa/packages/core/src/digest.ts
2026-11-16 21:25:21 +05:00

191 lines
9.4 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Daily digest (PEP-29): per user, per project — done in the last day, in progress, in
// review, waiting for the user, stuck, limits. Sent from the watchdog tick at the user's
// time; /digest in the bot renders it on demand.
import { asIs, m as tr } from "@peppa/shared/i18n";
import { projects, pushSubscriptions, questions, sessions, tasks, users, type Db } from "@peppa/db";
import { formatTaskKey, loadEnv } from "@peppa/shared";
import { and, asc, gte, inArray, isNull, notInArray } from "drizzle-orm";
import { deliverToUser, getNotifyPrefs, hhmmToMinutes, localClock, type NotifyPrefs } from "./notifications.ts";
import { FINISHED_SESSION_STATUSES } from "./sessions.ts";
import { getSetting, setSetting } from "./settings.ts";
import { listUserProjects, type User } from "./users.ts";
import { pausedProjectIds } from "./project-pause.ts";
const DAY = 24 * 3600_000;
/** After the chosen time the digest may still go out for this long (a watchdog restart). */
const WINDOW_MIN = 180;
type TaskLine = { key: string; title: string };
export interface ProjectDigest {
key: string;
name: string;
done: TaskLine[];
inProgress: TaskLine[];
review: TaskLine[];
blocked: TaskLine[];
waiting: number;
stalled: number;
rateLimited: number;
limitResumes: number;
}
export interface Digest {
projects: ProjectDigest[];
totals: { done: number; inProgress: number; review: number; waiting: number; stuck: number };
}
/** What happened in the user's projects (muted ones left out) since `now - 24h`. */
export async function buildDigest(db: Db, user: Pick<User, "id">, o: { now?: Date; prefs?: NotifyPrefs } = {}): Promise<Digest> {
const now = o.now ?? new Date();
const since = new Date(now.getTime() - DAY);
const prefs = o.prefs ?? (await getNotifyPrefs(db, user.id));
// PEP-174: a project on pause is not in the digest.
const paused = await pausedProjectIds(db);
const list = (await listUserProjects(db, user.id)).filter((p) => !prefs.mutedProjects.includes(p.id) && !paused.has(p.id));
const out: Digest = { projects: [], totals: { done: 0, inProgress: 0, review: 0, waiting: 0, stuck: 0 } };
if (!list.length) return out;
const ids = list.map((p) => p.id);
const taskRows = await db
.select({ projectId: tasks.projectId, number: tasks.number, title: tasks.title, status: tasks.status, updatedAt: tasks.updatedAt })
.from(tasks)
.where(and(inArray(tasks.projectId, ids), inArray(tasks.status, ["done", "proposing", "in_progress", "review", "blocked"])))
.orderBy(asc(tasks.number));
const open = await db
.select({ projectId: questions.projectId })
.from(questions)
.where(and(inArray(questions.projectId, ids), isNull(questions.answeredAt)));
const runners = await db
.select({ projectId: sessions.projectId, status: sessions.status, limitResumes: sessions.limitResumes, limitResumedAt: sessions.limitResumedAt })
.from(sessions)
.where(and(inArray(sessions.projectId, ids), notInArray(sessions.status, FINISHED_SESSION_STATUSES)));
const resumed = await db
.select({ projectId: sessions.projectId })
.from(sessions)
.where(and(inArray(sessions.projectId, ids), gte(sessions.limitResumedAt, since)));
for (const p of list) {
const line = (t: { number: number; title: string }) => ({ key: formatTaskKey(p.key, t.number), title: t.title });
const mine = taskRows.filter((t) => t.projectId === p.id);
const d: ProjectDigest = {
key: p.key,
name: p.name,
done: mine.filter((t) => t.status === "done" && t.updatedAt >= since).map(line),
inProgress: mine.filter((t) => t.status === "in_progress" || t.status === "proposing").map(line),
review: mine.filter((t) => t.status === "review").map(line),
blocked: mine.filter((t) => t.status === "blocked").map(line),
waiting: open.filter((q) => q.projectId === p.id).length,
stalled: runners.filter((s) => s.projectId === p.id && s.status === "stalled").length,
rateLimited: runners.filter((s) => s.projectId === p.id && s.status === "rate_limited").length,
limitResumes: resumed.filter((s) => s.projectId === p.id).length,
};
const any = d.done.length + d.inProgress.length + d.review.length + d.blocked.length + d.waiting + d.stalled + d.rateLimited + d.limitResumes;
if (!any) continue;
out.projects.push(d);
out.totals.done += d.done.length;
out.totals.inProgress += d.inProgress.length;
out.totals.review += d.review.length;
out.totals.waiting += d.waiting;
out.totals.stuck += d.blocked.length + d.stalled + d.rateLimited;
}
return out;
}
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n)}…` : s);
function taskList(webUrl: string, items: TaskLine[], max = 8): string {
const shown = items.slice(0, max).map((t) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a> ${asIs(esc(clip(t.title, 60)))}`);
if (items.length > max) shown.push(`…${tr("и ещё {n}", { n: items.length - max })}`);
return shown.map((s) => ` • ${s}`).join("\n");
}
/** Telegram HTML text of the digest. */
export function renderDigest(d: Digest, o: { webUrl: string; title?: string }): string {
const lines = [`<b>${esc(o.title ?? tr("☀️ Сводка за сутки"))}</b>`];
if (!d.projects.length) {
lines.push("", tr("Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт вас."));
return lines.join("\n");
}
for (const p of d.projects) {
lines.push("", `<b>${asIs(esc(p.name))}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">${tr("доска")}</a>`);
if (p.done.length) lines.push(tr("✅ Сделано: {n}", { n: p.done.length }), taskList(o.webUrl, p.done));
if (p.inProgress.length) lines.push(tr("🔨 В работе: {n}", { n: p.inProgress.length }), taskList(o.webUrl, p.inProgress, 5));
if (p.review.length) lines.push(tr("👀 На ревью: {n}", { n: p.review.length }), taskList(o.webUrl, p.review));
if (p.waiting) lines.push(tr("⏳ Ждёт вас: {n}", { n: p.waiting }));
if (p.blocked.length) lines.push(tr("⛔ Заблокировано: {n}", { n: p.blocked.length }), taskList(o.webUrl, p.blocked));
if (p.stalled) lines.push(tr("🧊 Зависло агентов: {n}", { n: p.stalled }));
if (p.rateLimited || p.limitResumes) {
const v = { waiting: p.rateLimited, resumes: p.limitResumes };
lines.push(
p.rateLimited && p.limitResumes
? tr("⌛ Лимит: ждут сброса {waiting}, авто-продолжений за сутки {resumes}", v)
: p.rateLimited
? tr("⌛ Лимит: ждут сброса {waiting}", v)
: tr("⌛ Лимит: авто-продолжений за сутки {resumes}", v),
);
}
}
if (d.totals.waiting) lines.push("", `<a href="${esc(o.webUrl)}">${tr("Открыть Peppa FACTORY")}</a> — ${tr("ответить на {n}", { n: d.totals.waiting })}.`);
return lines.join("\n");
}
/** One-line summary for a push notification. */
export function digestSummary(d: Digest): string {
const t = d.totals;
return [
t.done && tr("сделано {n}", { n: t.done }),
t.inProgress && tr("в работе {n}", { n: t.inProgress }),
t.review && tr("на ревью {n}", { n: t.review }),
t.waiting && tr("ждёт вас {n}", { n: t.waiting }),
t.stuck && tr("зависло {n}", { n: t.stuck }),
]
.filter(Boolean)
.join(" · ");
}
const lastKey = (userId: number) => `digest.last:${userId}`;
/**
* Sends today's digest to every user whose time has come (watchdog tick). At most one per
* local day; an empty digest isn't sent. Returns the number of users it went to.
*/
export async function digestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise<number> {
const now = o.now ?? new Date();
const webUrl = loadEnv().PEPPA_WEB_URL;
const withPush = new Set((await db.selectDistinct({ id: pushSubscriptions.userId }).from(pushSubscriptions)).map((r) => r.id));
const all = (await db.select().from(users)).filter((u) => !u.disabledAt && (u.telegramChatId || withPush.has(u.id)));
let sent = 0;
for (const u of all) {
try {
const prefs = await getNotifyPrefs(db, u.id);
const ch = prefs.events.digest;
if (!ch.telegram && !ch.push) continue;
const clock = localClock(now, prefs.timezone);
const target = hhmmToMinutes(prefs.digestTime);
if (clock.minutes < target || clock.minutes >= target + WINDOW_MIN) continue;
if ((await getSetting<string>(db, lastKey(u.id))) === clock.date) continue;
await setSetting(db, lastKey(u.id), clock.date);
const d = await buildDigest(db, u, { now, prefs });
if (!d.projects.length) continue;
const r = await deliverToUser(
db,
u,
{
event: "digest",
dedupeKey: `digest:u${u.id}:${clock.date}`,
telegram: { params: { text: renderDigest(d, { webUrl }), parse_mode: "HTML", link_preview_options: { is_disabled: true } } },
push: { title: tr("Сводка за сутки"), body: digestSummary(d), url: "/", tag: "digest" },
now,
},
prefs,
);
if (r.telegram || r.push) sent++;
} catch (e) {
o.log?.(`digest u${u.id}: ${(e as Error).message}`);
}
}
if (sent) o.log?.(`digest: sent to ${sent}`);
return sent;
}