236 lines
14 KiB
TypeScript
236 lines
14 KiB
TypeScript
// PEP-29 / PEP-35 / PEP-55: notification settings, quiet hours, browser push and the daily
|
||
// digest — the real bot against mock-telegram and mock-push, controlled clock for the digest.
|
||
import assert from "node:assert/strict";
|
||
import { after, before, beforeEach, describe, test } from "node:test";
|
||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||
import { core, db, teardown, waitFor } from "./helpers.ts";
|
||
import { MockTelegram } from "../src/mock-telegram.ts";
|
||
import { MockPushService } from "../src/mock-push.ts";
|
||
import { projects, pushOutbox, pushSubscriptions, questions, sessions, settings, tasks, telegramOutbox, users } from "@peppa/db";
|
||
import { eq, like, sql } from "drizzle-orm";
|
||
import type { Bot } from "@peppa/bot";
|
||
|
||
const { createBot } = await import("@peppa/bot");
|
||
const { TelegramApi } = await import("@peppa/bot/telegram");
|
||
|
||
process.env.PEPPA_SECRET = "mock-secret-for-tests";
|
||
const TZ = "Europe/Moscow"; // UTC+3, no DST
|
||
const tg = await new MockTelegram().start();
|
||
const push = await new MockPushService().start();
|
||
const PM = { id: 601, chatId: 601 };
|
||
const BOB = { id: 602, chatId: 602 };
|
||
let bot: Bot;
|
||
let pm: Awaited<ReturnType<typeof core.upsertUserFromGitea>>;
|
||
let bob: typeof pm;
|
||
let seq = 0;
|
||
|
||
async function newProject(name: string) {
|
||
const key = `N${String.fromCharCode(65 + seq++)}`;
|
||
const p = await core.createProject(db, { slug: key.toLowerCase(), key, name, giteaOwner: "test", workspacePath: "/tmp/none", ownerId: pm.id });
|
||
await core.addMember(db, p, bob.login, pm.id);
|
||
return p;
|
||
}
|
||
async function newTask(p: { id: number; key: string }, title = "Стори") {
|
||
const ref = await core.createTask(db, { projectId: p.id, title });
|
||
return core.resolveTask(db, ref.key);
|
||
}
|
||
const prefs = (u: { id: number }) => core.getNotifyPrefs(db, u.id);
|
||
async function setPrefs(u: { id: number }, patch: Partial<Awaited<ReturnType<typeof prefs>>>) {
|
||
await core.setNotifyPrefs(db, u.id, { ...(await prefs(u)), ...patch });
|
||
}
|
||
const sentTo = (chatId: number, needle: string) => tg.calls.filter((c) => c.method === "sendMessage" && c.params.chat_id === chatId && String(c.params.text).includes(needle));
|
||
|
||
before(async () => {
|
||
pm = await core.upsertUserFromGitea(db, { id: 71, login: "mock-pm" }, { access_token: "x" });
|
||
bob = await core.upsertUserFromGitea(db, { id: 72, login: "mock-bob" }, { access_token: "y" });
|
||
await db.update(users).set({ telegramChatId: PM.chatId, telegramUserId: PM.id }).where(eq(users.id, pm.id));
|
||
await db.update(users).set({ telegramChatId: BOB.chatId, telegramUserId: BOB.id }).where(eq(users.id, bob.id));
|
||
pm = (await core.getUser(db, pm.id))!;
|
||
bob = (await core.getUser(db, bob.id))!;
|
||
bot = createBot({ db, api: new TelegramApi(tg.token, tg.url), secret: tg.token, webUrl: "http://peppa.test", pollTimeoutSec: 1, outboxIntervalMs: 100, reconcileIntervalMs: 300, log: (m) => process.env.MOCK_DEBUG && console.log(m) });
|
||
await bot.start();
|
||
});
|
||
after(async () => {
|
||
await bot.stop();
|
||
await tg.stop();
|
||
await push.stop();
|
||
await teardown();
|
||
});
|
||
beforeEach(async () => {
|
||
// Earlier tests' open questions would pop up on a fresh push subscription.
|
||
await db.delete(questions);
|
||
await db.delete(pushSubscriptions);
|
||
for (const u of [pm, bob]) await core.setNotifyPrefs(db, u.id, { ...core.defaultPrefs(), timezone: TZ });
|
||
});
|
||
|
||
describe("settings", () => {
|
||
test("defaults: everything on except the digest in the browser; garbage is rejected", async () => {
|
||
const p = await prefs(pm);
|
||
assert.deepEqual(p.events.questions, { telegram: true, push: true });
|
||
assert.deepEqual(p.events.digest, { telegram: true, push: false });
|
||
assert.equal(p.digestTime, "09:00");
|
||
await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, quiet: { from: "25:00", to: "08:00" } }), /ЧЧ:ММ/);
|
||
await assert.rejects(core.setNotifyPrefs(db, pm.id, { ...p, timezone: "Mars/Olympus" }), /таймзона/);
|
||
});
|
||
|
||
test("quiet hours cross midnight in the user's timezone", () => {
|
||
const q = { quiet: { from: "23:00", to: "08:00" }, timezone: TZ };
|
||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T23:00:00Z")), true); // 02:00 MSK
|
||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T19:59:00Z")), false); // 22:59 MSK
|
||
assert.equal(core.inQuietHours(q, new Date("2026-03-01T05:00:00Z")), false); // 08:00 MSK
|
||
assert.equal(core.inQuietHours({ quiet: null, timezone: TZ }, new Date()), false);
|
||
});
|
||
|
||
test("question events", () => {
|
||
const base = { taskId: 1, sessionId: 1 };
|
||
assert.equal(core.questionEvent({ ...base, kind: "approval" }, {}), "questions");
|
||
assert.equal(core.questionEvent({ ...base, kind: "attention" }, { taskStatus: "review" }), "review");
|
||
assert.equal(core.questionEvent({ ...base, kind: "attention" }, { sessionStatus: "rate_limited" }), "failures");
|
||
assert.equal(core.questionEvent({ kind: "question", taskId: null, sessionId: null }, {}), "releases");
|
||
});
|
||
});
|
||
|
||
describe("routing in the bot", () => {
|
||
test("Сценарий: выключены вопросы агентов в Telegram — сообщения нет, у участника есть", async () => {
|
||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, questions: { telegram: false, push: true } } });
|
||
const p = await newProject("Routing");
|
||
const ref = await newTask(p);
|
||
const q = await core.askPm(db, ref, { kind: "question", text: "Какую БД взять?" });
|
||
await waitFor("bob got the question", async () => sentTo(BOB.chatId, "Какую БД взять").length > 0);
|
||
await new Promise((r) => setTimeout(r, 800)); // a couple of reconcile rounds
|
||
assert.equal(sentTo(PM.chatId, "Какую БД взять").length, 0);
|
||
assert.equal((await core.pendingQuestions(db, p.id)).some((x) => x.id === q.id), true, "still visible in the web");
|
||
});
|
||
|
||
test("Сценарий: проект выключен — ни Telegram, ни push; участник получает", async () => {
|
||
const p = await newProject("Demo");
|
||
const sub = push.subscribe();
|
||
await core.savePushSubscription(db, pm.id, sub);
|
||
await setPrefs(pm, { mutedProjects: [p.id] });
|
||
const ref = await newTask(p, "Ревью-стори");
|
||
await core.updateTask(db, ref, { status: "review" });
|
||
await core.askPm(db, ref, { kind: "attention", text: "Готово, проверь." });
|
||
await waitFor("bob got review", async () => sentTo(BOB.chatId, "Готово, проверь").length > 0);
|
||
await new Promise((r) => setTimeout(r, 800));
|
||
assert.equal(sentTo(PM.chatId, "Готово, проверь").length, 0);
|
||
assert.equal(push.for(sub.id).length, 0);
|
||
await db.delete(pushSubscriptions);
|
||
});
|
||
|
||
test("Сценарий: тихие часы — Telegram без звука, push не отправляется", async () => {
|
||
const sub = push.subscribe();
|
||
await core.savePushSubscription(db, pm.id, sub);
|
||
// Quiet the whole day around now, whatever the clock says.
|
||
const now = core.localClock(new Date(), TZ).minutes;
|
||
const hh = (m: number) => `${String(Math.floor(((m + 1440) % 1440) / 60)).padStart(2, "0")}:${String(((m + 1440) % 1440) % 60).padStart(2, "0")}`;
|
||
await setPrefs(pm, { quiet: { from: hh(now - 60), to: hh(now + 60) } });
|
||
const p = await newProject("Night");
|
||
const ref = await newTask(p);
|
||
await core.askPm(db, ref, { kind: "permission", text: "Можно rm -rf node_modules?" });
|
||
const [msg] = await waitFor("silent message", async () => { const a = sentTo(PM.chatId, "rm -rf node_modules"); return a.length ? a : null; });
|
||
assert.equal(msg!.params.disable_notification, true);
|
||
assert.equal(sentTo(BOB.chatId, "rm -rf node_modules")[0]?.params.disable_notification, undefined, "bob has no quiet hours");
|
||
await new Promise((r) => setTimeout(r, 600));
|
||
assert.equal(push.for(sub.id).length, 0);
|
||
await db.delete(pushSubscriptions);
|
||
});
|
||
|
||
test("Сценарий: готово к ревью в браузер — уведомление со ссылкой на стори", async () => {
|
||
const sub = push.subscribe();
|
||
await core.savePushSubscription(db, pm.id, { ...sub, userAgent: "Mock Chrome" });
|
||
const p = await newProject("Push");
|
||
const ref = await newTask(p, "Кнопка входа");
|
||
await core.updateTask(db, ref, { status: "review" });
|
||
await core.askPm(db, ref, { kind: "attention", text: "PR готов." });
|
||
const [m] = await waitFor("push delivered", async () => { const a = push.for(sub.id); return a.length ? a : null; });
|
||
assert.equal(m!.payload.url, `/t/${ref.project.key}-${ref.task.number}`);
|
||
assert.match(String(m!.payload.title), /Готово к ревью/);
|
||
assert.equal(m!.payload.body, "PR готов.");
|
||
assert.equal(m!.payload.sound, true);
|
||
assert.ok(Number(m!.payload.count) >= 1);
|
||
assert.equal(push.rejected.length, 0, JSON.stringify(push.rejected));
|
||
// One push per question, not one per reconcile round.
|
||
await new Promise((r) => setTimeout(r, 800));
|
||
assert.equal(push.for(sub.id).filter((x) => x.payload.body === "PR готов.").length, 1);
|
||
await db.delete(pushSubscriptions);
|
||
});
|
||
|
||
test("Сценарий: подписка протухла — 410 удаляет её, повторов нет", async () => {
|
||
const sub = push.subscribe();
|
||
await core.savePushSubscription(db, pm.id, sub);
|
||
push.setStatus(sub.id, 410);
|
||
const p = await newProject("Gone");
|
||
const ref = await newTask(p);
|
||
await core.askPm(db, ref, { kind: "question", text: "Есть кто?" });
|
||
await waitFor("subscription removed", async () => (await core.userPushSubscriptions(db, pm.id)).length === 0);
|
||
const rows = await db.select().from(pushOutbox).where(like(pushOutbox.dedupeKey, "q:%"));
|
||
assert.ok(rows.every((r) => r.status !== "pending"));
|
||
const n = push.rejected.filter((r) => r.subscription === sub.id).length;
|
||
await new Promise((r) => setTimeout(r, 800));
|
||
assert.equal(push.rejected.filter((r) => r.subscription === sub.id).length, n, "no retries");
|
||
});
|
||
|
||
test("a test push straight from the web action path (sendWebPush)", async () => {
|
||
const sub = push.subscribe();
|
||
const r = await core.sendWebPush(db, { endpoint: sub.endpoint, ...sub.keys }, { title: "Пеппа", body: "Проверка", url: "/settings" });
|
||
assert.deepEqual(r, { ok: true });
|
||
assert.equal(push.for(sub.id)[0]?.payload.body, "Проверка");
|
||
});
|
||
});
|
||
|
||
describe("incidents and monitoring follow the settings", () => {
|
||
test("monitoring off in Telegram → admin gets no message", async () => {
|
||
await core.setPlatformAdmins(db, [pm.login, bob.login]);
|
||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, monitoring: { telegram: false, push: false } } });
|
||
const n = await core.alertAdmins(db, "mon:test:1", "Бот молчит 6 мин", () => {});
|
||
assert.equal(n, 1);
|
||
const rows = await db.select().from(telegramOutbox).where(like(telegramOutbox.dedupeKey, "mon:test:1:%"));
|
||
assert.deepEqual(rows.map((r) => r.params.chat_id), [BOB.chatId]);
|
||
});
|
||
});
|
||
|
||
describe("daily digest", () => {
|
||
// 2026-03-10 09:01 MSK = 06:01 UTC
|
||
const at = (hhmm: string, day = 10) => new Date(`2026-03-${String(day).padStart(2, "0")}T${String(Number(hhmm.slice(0, 2)) - 3).padStart(2, "0")}:${hhmm.slice(3)}:00Z`);
|
||
|
||
test("Сценарий: утренний дайджест — одна сводка за день с сделанным, в работе и ждущим", async () => {
|
||
await db.delete(questions);
|
||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||
// Only this project counts for the digest (older ones are muted for the PM).
|
||
await setPrefs(pm, { mutedProjects: (await db.select({ id: projects.id }).from(projects)).map((p) => p.id) });
|
||
const p = await newProject("Digest");
|
||
const done = await newTask(p, "Вход через Gitea");
|
||
const wip = await newTask(p, "Доска");
|
||
await core.updateTask(db, done, { status: "done" });
|
||
await db.update(tasks).set({ updatedAt: at("20:00", 9) }).where(eq(tasks.id, done.task.id));
|
||
await core.updateTask(db, wip, { status: "in_progress" });
|
||
await core.askPm(db, wip, { kind: "question", text: "Цвет кнопки?" });
|
||
|
||
const before = tg.calls.length;
|
||
assert.equal(await core.digestTick(db, { now: at("08:59") }), 0, "too early");
|
||
assert.ok((await core.digestTick(db, { now: at("09:01") })) >= 1);
|
||
assert.equal(await core.digestTick(db, { now: at("09:30") }), 0, "once a day");
|
||
const [m] = await waitFor("digest delivered", async () => { const a = sentTo(PM.chatId, "Сводка за сутки").filter((c) => tg.calls.indexOf(c) >= before); return a.length ? a : null; });
|
||
const text = String(m!.params.text);
|
||
assert.match(text, /Digest/);
|
||
assert.match(text, new RegExp(`Сделано: 1[\\s\\S]*${done.project.key}-${done.task.number}`));
|
||
assert.match(text, new RegExp(`В работе: 1[\\s\\S]*${wip.project.key}-${wip.task.number}`));
|
||
assert.match(text, /Ждёт вас: 1/);
|
||
// The next day it comes again.
|
||
assert.ok((await core.digestTick(db, { now: at("09:05", 11) })) >= 1);
|
||
});
|
||
|
||
test("Сценарий: выкат вечером — до завтрашних 09:00 сводки нет; выключенный дайджест не приходит", async () => {
|
||
await db.delete(settings).where(like(settings.key, "digest.last:%"));
|
||
assert.equal(await core.digestTick(db, { now: at("20:00", 12) }), 0);
|
||
await setPrefs(pm, { events: { ...(await prefs(pm)).events, digest: { telegram: false, push: false } } });
|
||
await setPrefs(bob, { events: { ...(await prefs(bob)).events, digest: { telegram: false, push: false } } });
|
||
assert.equal(await core.digestTick(db, { now: at("09:10", 13) }), 0);
|
||
});
|
||
|
||
test("/digest in the bot answers right away", async () => {
|
||
tg.userSends({ id: PM.id, chatId: PM.chatId, username: "pm" }, "/digest");
|
||
await waitFor("digest reply", async () => tg.botMessages(PM.chatId).some((m) => /Сводка за сутки/.test(m.text)));
|
||
});
|
||
});
|