// PEP-209: fewer «готово» messages in Telegram. When more than two stories of a project become // ready within an hour, their cards are not sent one by one: one summary «Готово к приёмке» with // a button that opens the acceptance page comes instead (the cards stay on the site). // // The bot's decision on a «готово» card (`acceptDigestHold`) waits `PEPPA_ACCEPT_DIGEST_SETTLE_SEC` // (300 s) after the card was made — so that with five ready at once the first two don't go alone — // and is then final: it depends only on the cards made in [card − 1 h; card + pause], which no // longer change. `acceptDigestTick` (watchdog, once a minute) sends the summary of held cards. // `PEPPA_ACCEPT_DIGEST=off` turns both off. import { questions, tasks, type Db } from "@peppa/db"; import { asIs, m as tr } from "@peppa/shared/i18n"; import { and, eq, gte, isNull, lte } from "drizzle-orm"; import { pausedProjectIds } from "./project-pause.ts"; import { deliverToUser, projectAudience } from "./notifications.ts"; import { listProjects } from "./projects.ts"; import { getSetting, setSetting } from "./settings.ts"; const WINDOW_MS = 3600_000; /** More «готово» than this within an hour → one summary. */ export const ACCEPT_DIGEST_MAX_SINGLE = 2; const settleMs = () => { const n = Number(process.env.PEPPA_ACCEPT_DIGEST_SETTLE_SEC ?? 300); return Number.isFinite(n) && n >= 0 ? n * 1000 : 300_000; }; const off = () => process.env.PEPPA_ACCEPT_DIGEST === "off"; export type DigestHold = "send" | "wait" | "held"; /** The bot's question about one card: send it now, wait a little, or leave it to the summary. */ export async function acceptDigestHold(db: Db, q: { projectId: number; taskId: number | null; msgType?: string | null; createdAt: Date }, now = new Date()): Promise { if (off() || q.msgType !== "done" || q.taskId == null) return "send"; const settle = settleMs(); const at = q.createdAt.getTime(); if (now.getTime() < at + settle) return "wait"; const rows = await db .select({ taskId: questions.taskId }) .from(questions) .where(and(eq(questions.projectId, q.projectId), eq(questions.msgType, "done"), gte(questions.createdAt, new Date(at - WINDOW_MS)), lte(questions.createdAt, new Date(at + settle)))); return new Set(rows.map((r) => r.taskId)).size > ACCEPT_DIGEST_MAX_SINGLE ? "held" : "send"; } interface DigestState { /** Stories already in a summary. */ ids: number[]; at: number; } const stateKey = (projectId: number) => `accept.digest:${projectId}`; export function acceptDigestText(projectName: string, n: number, url: string): string { return [tr("✅ {project}: готово к приёмке — задач: {n}", { project: asIs(projectName), n }), tr("Откройте «Приёмка» — там всё на одном экране: посмотреть, принять или поправить."), url].join("\n"); } /** One summary per project when cards are held; a new one only when new stories joined. */ export async function acceptDigestTick(db: Db, o: { now?: Date; log?: (m: string) => void } = {}): Promise { if (off()) return 0; const now = o.now ?? new Date(); const paused = await pausedProjectIds(db); let sent = 0; for (const project of await listProjects(db)) { if (paused.has(project.id)) continue; const open = await db .select({ q: questions, status: tasks.status }) .from(questions) .innerJoin(tasks, eq(questions.taskId, tasks.id)) .where(and(eq(questions.projectId, project.id), eq(questions.msgType, "done"), isNull(questions.answeredAt), eq(tasks.status, "review"), isNull(tasks.archivedAt))); if (!open.length) continue; const held = new Set(); let waiting = false; for (const { q } of open) { const h = await acceptDigestHold(db, q, now); if (h === "wait") waiting = true; if (h === "held") held.add(q.taskId!); } if (!held.size || waiting) continue; const st = (await getSetting(db, stateKey(project.id))) ?? { ids: [], at: 0 }; if ([...held].every((id) => st.ids.includes(id))) continue; const total = new Set(open.map((r) => r.q.taskId)).size; const url = `${(process.env.PEPPA_WEB_URL ?? "").replace(/\/$/, "")}/p/${project.key}/accept`; const text = acceptDigestText(project.name, total, url); for (const u of await projectAudience(db, project.id)) { await deliverToUser(db, u, { event: "review", projectId: project.id, dedupeKey: `acc:${project.id}:${now.getTime()}:${u.telegramChatId}`, pushKey: `acc:${project.id}:${now.getTime()}:u${u.id}`, telegram: { params: { text, link_preview_options: { is_disabled: true }, reply_markup: { inline_keyboard: [[{ text: tr("Открыть «Приёмка»"), url }]] } } }, push: { title: tr("Готово к приёмке"), body: tr("{project}: задач: {n}", { project: asIs(project.name), n: total }), url: `/p/${project.key}/accept`, tag: `acc:${project.id}` }, now, }).catch(() => null); } // A week-old list is forgotten: only stories still waiting stay counted. await setSetting(db, stateKey(project.id), { ids: [...new Set([...st.ids.filter((id) => open.some((r) => r.q.taskId === id)), ...held])], at: now.getTime() } satisfies DigestState); o.log?.(`accept digest ${project.key}: ${total} ready (${held.size} held)`); sent++; } return sent; }