peppa/packages/testkit/test/stale-waits.test.ts
peppa-bot 9e97fd531d
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 51с
peppa/build build: success за 35с
peppa/test test: success за 1644с
peppa-ci / ci (pull_request) Successful in 29m38s
PEP-279: старые вопросы закрываются вариантом по умолчанию, «Принять» — одна сводка в день
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-26 19:06:46 +00:00

130 lines
7.6 KiB
TypeScript
Raw 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.

// PEP-279, spec stale-waits: old questions close with their default option (one summary per
// person); «Принять» is never pressed for a person — one reminder a day in working time.
import assert from "node:assert/strict";
import { after, before, describe, test } from "node:test";
import { events, questions, tasks, telegramOutbox, users } from "@peppa/db";
import { stripAsIs } from "@peppa/shared/i18n";
import { and, eq, like, sql } from "drizzle-orm";
import { core, db, runner, teardown } from "./helpers.ts";
process.env.PEPPA_TZ = "UTC";
process.env.PEPPA_SECRET = "mock-secret-for-tests";
const DAY = 86_400_000;
// Wednesday 10:00 UTC — working time by the default watchdog hours (Mon–Fri 9–19).
const NOW = new Date("2026-11-25T10:00:00Z");
const ago = (days: number) => new Date(NOW.getTime() - days * DAY);
let n = 0;
async function owner() {
n++;
const chat = 79_000 + n;
const u = await core.upsertUserFromGitea(db, { id: 97_000 + n, login: `mock-stale-${n}` }, { access_token: "x" });
await db.update(users).set({ telegramChatId: chat, telegramUserId: chat }).where(eq(users.id, u.id));
return { user: u, chat };
}
async function proj(ownerId: number) {
n++;
return core.createProject(db, { slug: `mock-stale-p${n}`, key: `ST${String.fromCharCode(64 + n)}`, name: `Старое ${n}`, giteaOwner: "peppa-bot", giteaRepo: `mock-stale-p${n}`, workspacePath: `/tmp/mock-stale-p${n}`, ownerId });
}
async function question(projectId: number, taskId: number | null, o: { text: string; options?: string[]; def?: string; msgType?: "question" | "done" | null; kind?: "question" | "attention"; days: number }) {
const [row] = await db
.insert(questions)
.values({ projectId, taskId, kind: o.kind ?? "question", text: o.text, options: o.options, defaultOption: o.def, msgType: o.msgType === undefined ? "question" : o.msgType, createdAt: ago(o.days) })
.returning();
return row!;
}
const sentTo = async (chat: number, prefix: string) =>
(await db.select().from(telegramOutbox).where(and(eq(sql`json_extract(${telegramOutbox.params}, '$.chat_id')`, chat), like(telegramOutbox.dedupeKey, `${prefix}%`)))).map((r) => stripAsIs(String((r.params as { text?: string }).text ?? "")));
before(() => {
delete process.env.PEPPA_ACCEPT_REMIND;
});
after(async () => {
process.env.PEPPA_ACCEPT_REMIND = "off";
await teardown();
});
describe("PEP-279: старые вопросы закрываются вариантом по умолчанию", () => {
test("Вопрос с вариантом по умолчанию; свежий вопрос и карточка «готово» не трогаются; без варианта — без выбора; одно итоговое сообщение", async () => {
const o = await owner();
const p = await proj(o.user.id);
const t = await core.createTask(db, { projectId: p.id, title: "Кнопка" });
const old = await question(p.id, t.task.id, { text: "Какой цвет кнопки?", options: ["Синий", "Зелёный"], def: "Синий", days: 8 });
const budget = await question(p.id, t.task.id, { text: "Продлить бюджет?", options: ["Продлить ×2", "Остановить"], kind: "attention", msgType: null, days: 9 });
const fresh = await question(p.id, t.task.id, { text: "Какой шрифт?", options: ["Обычный", "Крупный"], def: "Обычный", days: 2 });
const done = await question(p.id, t.task.id, { text: "Готово к приёмке", kind: "attention", msgType: "done", days: 10 });
const note = await question(p.id, null, { text: "Сбой выкладки", kind: "attention", msgType: null, days: 10 });
// Предпросмотр ничего не меняет.
const preview = await runner.closeStaleQuestions(db, { now: NOW, dryRun: true });
const mine = preview.closed.filter((x) => x.projectId === p.id);
assert.deepEqual(mine.map((x) => [x.id, x.answer]), [[old.id, "Синий"], [budget.id, null]]);
assert.equal((await core.getQuestion(db, old.id)).answeredAt, null);
const r = await runner.closeStaleQuestions(db, { now: NOW });
assert.equal(r.failed, 0);
const q1 = await core.getQuestion(db, old.id);
assert.equal(q1.answer, "Синий");
assert.equal(q1.answeredVia, "system");
const q2 = await core.getQuestion(db, budget.id);
assert.equal(q2.answer, runner.STALE_NO_DEFAULT);
for (const id of [fresh.id, done.id, note.id]) assert.equal((await core.getQuestion(db, id)).answeredAt, null, `#${id} stays open`);
const ev = await db.select().from(events).where(and(eq(events.projectId, p.id), eq(events.type, "stale_questions_closed")));
assert.equal(ev.length, 1);
assert.deepEqual((ev[0]!.payload as { questionIds: number[] }).questionIds, [old.id, budget.id]);
const msgs = await sentTo(o.chat, "stale:");
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /Закрыли вопросов без ответа старше 7 дней: 2/);
assert.match(msgs[0]!, /Какой цвет кнопки\?» → Синий/);
});
test("Нечего закрывать — никому ничего не отправлено", async () => {
const o = await owner();
const p = await proj(o.user.id);
await question(p.id, null, { text: "Свежий?", options: ["Да", "Нет"], def: "Да", days: 1 });
const r = await runner.closeStaleQuestions(db, { now: NOW });
assert.equal(r.closed.filter((x) => x.projectId === p.id).length, 0);
assert.equal((await sentTo(o.chat, "stale:")).length, 0);
});
});
describe("PEP-279: «Принять» — одно напоминание в день", () => {
async function inReview(projectId: number, title: string, days: number) {
const t = await core.createTask(db, { projectId, title });
await db.update(tasks).set({ status: "review" }).where(eq(tasks.id, t.task.id));
await question(projectId, t.task.id, { text: `Готово: ${title}`, kind: "attention", msgType: "done", days });
return t;
}
test("Три задачи ждут приёмки — одно сообщение за день, задачи остаются на приёмке", async () => {
const o = await owner();
const p = await proj(o.user.id);
const ts = [await inReview(p.id, "А", 2), await inReview(p.id, "Б", 2), await inReview(p.id, "В", 3)];
await runner.acceptReminderTick(db, { now: NOW });
await runner.acceptReminderTick(db, { now: new Date(NOW.getTime() + 3600_000) });
const msgs = await sentTo(o.chat, "accrem:");
assert.equal(msgs.length, 1);
assert.match(msgs[0]!, /Ждут «Принять» — задач: 3, самая давняя ждёт дней: 3/);
for (const t of ts) assert.equal((await runner.resolveTaskById(db, t.task.id)).task.status, "review");
// Next working day — again one.
await runner.acceptReminderTick(db, { now: new Date(NOW.getTime() + DAY) });
assert.equal((await sentTo(o.chat, "accrem:")).length, 2);
});
test("Ночью и для свежих задач — тишина", async () => {
const a = await owner();
const b = await owner();
const pa = await proj(a.user.id);
const pb = await proj(b.user.id);
await inReview(pa.id, "Свежая", 2 / 24);
await inReview(pb.id, "Давняя", 2);
await runner.acceptReminderTick(db, { now: new Date("2026-11-25T22:00:00Z") });
assert.equal((await sentTo(b.chat, "accrem:")).length, 0);
await runner.acceptReminderTick(db, { now: NOW });
assert.equal((await sentTo(a.chat, "accrem:")).length, 0);
assert.equal((await sentTo(b.chat, "accrem:")).length, 1);
});
});