174 lines
8.7 KiB
TypeScript
174 lines
8.7 KiB
TypeScript
// 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 { 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";
|
||
|
||
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));
|
||
const list = (await listUserProjects(db, user.id)).filter((p) => !prefs.mutedProjects.includes(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, "&").replace(/</g, "<").replace(/>/g, ">");
|
||
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> ${esc(clip(t.title, 60))}`);
|
||
if (items.length > max) shown.push(`…и ещё ${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 ?? "☀️ Сводка за сутки")}</b>`];
|
||
if (!d.projects.length) {
|
||
lines.push("", "Всё тихо: за сутки ничего не сделано, ничего не в работе и ничего не ждёт вас.");
|
||
return lines.join("\n");
|
||
}
|
||
for (const p of d.projects) {
|
||
lines.push("", `<b>${esc(p.name)}</b> (${esc(p.key)}) — <a href="${esc(`${o.webUrl}/p/${p.key}`)}">доска</a>`);
|
||
if (p.done.length) lines.push(`✅ Сделано: ${p.done.length}`, taskList(o.webUrl, p.done));
|
||
if (p.inProgress.length) lines.push(`🔨 В работе: ${p.inProgress.length}`, taskList(o.webUrl, p.inProgress, 5));
|
||
if (p.review.length) lines.push(`👀 На ревью: ${p.review.length}`, taskList(o.webUrl, p.review));
|
||
if (p.waiting) lines.push(`⏳ Ждёт вас: ${p.waiting}`);
|
||
if (p.blocked.length) lines.push(`⛔ Заблокировано: ${p.blocked.length}`, taskList(o.webUrl, p.blocked));
|
||
if (p.stalled) lines.push(`🧊 Зависло агентов: ${p.stalled}`);
|
||
if (p.rateLimited || p.limitResumes) {
|
||
lines.push(`⌛ Лимит: ${[p.rateLimited ? `ждут сброса ${p.rateLimited}` : null, p.limitResumes ? `авто-продолжений за сутки ${p.limitResumes}` : null].filter(Boolean).join(", ")}`);
|
||
}
|
||
}
|
||
if (d.totals.waiting) lines.push("", `<a href="${esc(o.webUrl)}">Открыть Peppa FACTORY</a> — ответить на ${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 && `сделано ${t.done}`, t.inProgress && `в работе ${t.inProgress}`, t.review && `на ревью ${t.review}`, t.waiting && `ждёт вас ${t.waiting}`, t.stuck && `зависло ${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: "Сводка за сутки", 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;
|
||
}
|