328 lines
15 KiB
TypeScript
328 lines
15 KiB
TypeScript
import assert from "node:assert/strict";
|
||
import { describe, it } from "node:test";
|
||
import { Assistant, CODE_TTL_MS } from "../src/assistant.ts";
|
||
import { loadConfig } from "../src/config.ts";
|
||
import { Store } from "../src/store.ts";
|
||
import type { TgMessage } from "../src/telegram.ts";
|
||
import { zonedParts, zonedToUtc } from "../src/time.ts";
|
||
import { combine, type MockEvent, type MockMail, mockGoogle, mockTelegram } from "./mocks.ts";
|
||
|
||
const tz = "Asia/Almaty";
|
||
const OWNER = 555;
|
||
|
||
function setup(
|
||
o: { mails?: MockMail[]; events?: MockEvent[]; webhook?: string; conflict?: boolean; now?: Date } = {},
|
||
) {
|
||
const g = mockGoogle({ mails: o.mails, events: o.events });
|
||
const tg = mockTelegram({ webhook: o.webhook, conflict: o.conflict });
|
||
const clock = { now: o.now ?? zonedToUtc(2026, 12, 1, 8, 0, tz) };
|
||
const config = loadConfig({
|
||
ASSISTANT_PASSWORD: "tanya-2026",
|
||
GOOGLE_CLIENT_ID: "mock-client",
|
||
GOOGLE_CLIENT_SECRET: "mock-secret",
|
||
TELEGRAM_BOT_TOKEN: "mock-token",
|
||
TELEGRAM_CHAT_ID: "777",
|
||
});
|
||
const store = new Store();
|
||
const a = new Assistant(config, store, {
|
||
fetch: combine(g.fetchFn, tg.fetchFn),
|
||
now: () => clock.now,
|
||
log: () => {},
|
||
});
|
||
return { a, g, tg, clock, store };
|
||
}
|
||
|
||
const pm = (text: string, id = 1, chat = OWNER, extra: Partial<TgMessage> = {}): TgMessage => ({
|
||
message_id: id,
|
||
date: 0,
|
||
chat: { id: chat, type: "private" },
|
||
from: { id: chat, first_name: "Татьяна" },
|
||
text,
|
||
...extra,
|
||
});
|
||
|
||
async function confirm(s: ReturnType<typeof setup>) {
|
||
await s.a.telegramInit();
|
||
const code = s.a.telegramCode();
|
||
await s.a.handleUpdate({ update_id: 1, message: pm(`/start ${code}`) });
|
||
return code;
|
||
}
|
||
|
||
const mailReport: MockMail = {
|
||
id: "m1",
|
||
subject: "Отчёт",
|
||
from: "Иван <ivan@example.com>",
|
||
body: "Добрый день!\nПрошу прислать отчёт до 03.12\n\nOn Mon, Ivan wrote:\n> старое",
|
||
};
|
||
|
||
describe("Требование: Подключение Google штатным входом", () => {
|
||
it("Scenario: Успешное подключение — адрес почты сохраняется", async () => {
|
||
const s = setup();
|
||
await s.a.connectGoogle("good-code", "https://x/oauth/google/callback");
|
||
assert.equal(s.store.state.google?.email, "tanya@example.com");
|
||
assert.equal(s.store.state.google?.refreshToken, "mock-refresh");
|
||
});
|
||
it("ссылка входа Google запрашивает только чтение почты и события календаря", () => {
|
||
const s = setup();
|
||
const url = new URL(s.a.google?.authUrl("https://x/cb", "st") ?? "");
|
||
assert.equal(
|
||
url.searchParams.get("scope"),
|
||
"openid email https://www.googleapis.com/auth/gmail.readonly https://www.googleapis.com/auth/calendar.events",
|
||
);
|
||
assert.equal(url.searchParams.get("access_type"), "offline");
|
||
});
|
||
it("неверный код — ошибка, Google не подключён", async () => {
|
||
const s = setup();
|
||
await assert.rejects(s.a.connectGoogle("bad", "https://x/cb"));
|
||
assert.equal(s.store.state.google, undefined);
|
||
});
|
||
});
|
||
|
||
describe("Требование: Автоматическое выделение (почта)", () => {
|
||
it("Scenario: Ссылка на письмо", async () => {
|
||
const s = setup({ mails: [mailReport] });
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
const [task] = s.store.state.tasks;
|
||
assert.equal(task?.title, "прислать отчёт");
|
||
assert.equal(task?.sourceTitle, "Отчёт");
|
||
assert.equal(task?.link, "https://mail.google.com/mail/u/?authuser=tanya%40example.com#all/m1");
|
||
assert.equal(s.store.state.tasks.length, 1, "цитата не даёт второй задачи");
|
||
});
|
||
it("Scenario: Повторная проверка — дубликата нет", async () => {
|
||
const s = setup({ mails: [mailReport] });
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
await s.a.syncGoogle();
|
||
assert.equal(s.store.state.tasks.length, 1);
|
||
const fullGets = s.g.calls.filter((c) => c.url.includes("/messages/m1?"));
|
||
assert.equal(fullGets.length, 1, "письмо второй раз не читается");
|
||
});
|
||
it("Scenario: Письмо без поручений", async () => {
|
||
const s = setup({
|
||
mails: [
|
||
{ id: "n1", subject: "Новости недели", from: "news@example.com", body: "Спасибо, что были с нами" },
|
||
],
|
||
});
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
assert.equal(s.store.state.tasks.length, 0);
|
||
});
|
||
it("письмо в HTML и поручение в описании встречи", async () => {
|
||
const day = (h: number) => zonedToUtc(2026, 12, 1, h, 0, tz).toISOString();
|
||
const s = setup({
|
||
mails: [
|
||
{
|
||
id: "h1",
|
||
subject: "Договор",
|
||
from: "a@b",
|
||
body: "<p>Коллеги,</p><p>Нужно подписать договор завтра в 12:00</p>",
|
||
html: true,
|
||
},
|
||
],
|
||
events: [
|
||
{
|
||
id: "e1",
|
||
summary: "Планёрка",
|
||
description: "Договорились обновить план продаж к пятнице",
|
||
start: day(9),
|
||
end: day(11),
|
||
},
|
||
],
|
||
});
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
assert.deepEqual(
|
||
s.store.state.tasks.map((t) => [t.source, t.kind, t.title]),
|
||
[
|
||
["gmail", "task", "подписать договор"],
|
||
["calendar", "agreement", "обновить план продаж"],
|
||
],
|
||
);
|
||
assert.equal(s.store.state.events.length, 1);
|
||
});
|
||
it("доступ отозван — понятная пометка, без падения", async () => {
|
||
const s = setup({ mails: [mailReport] });
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
s.g.state.refreshValid = false;
|
||
s.a.google?.forget();
|
||
await s.a.syncGoogle();
|
||
assert.equal(s.store.state.google?.lastError, "revoked");
|
||
});
|
||
});
|
||
|
||
describe("Требование: Подтверждённый чат Telegram без помехи другим проектам", () => {
|
||
it("Scenario: Подтверждение чата", async () => {
|
||
const s = setup();
|
||
await confirm(s);
|
||
assert.equal(s.store.state.telegram.chatId, OWNER);
|
||
assert.equal(
|
||
s.tg.sent.at(-1)?.text.split("\n")[0],
|
||
"Чат подтверждён. Сюда будут приходить сводки и напоминания.",
|
||
);
|
||
});
|
||
it("Scenario: Чужой или устаревший код", async () => {
|
||
const s = setup();
|
||
await s.a.telegramInit();
|
||
const code = s.a.telegramCode();
|
||
s.clock.now = new Date(s.clock.now.getTime() + CODE_TTL_MS + 60000);
|
||
await s.a.handleUpdate({ update_id: 1, message: pm(`/start ${code}`) });
|
||
assert.equal(s.store.state.telegram.chatId, undefined);
|
||
assert.equal(
|
||
s.tg.sent.at(-1)?.text,
|
||
"Ссылка устарела. Откройте страницу «Подключения» и возьмите новую.",
|
||
);
|
||
});
|
||
it("Scenario: Бот занят другим проектом — ничего не меняем, только отправка", async () => {
|
||
const s = setup({ webhook: "https://other-project.example/hook" });
|
||
await s.a.telegramInit();
|
||
assert.equal(s.store.state.telegram.mode, "send-only");
|
||
assert.equal(await s.a.telegramPollOnce(), 0);
|
||
assert.ok(!s.tg.calls.includes("getUpdates"));
|
||
assert.ok(!s.tg.calls.includes("deleteWebhook") && !s.tg.calls.includes("setWebhook"));
|
||
assert.equal(s.a.chatId, "777", "чат берётся из настроек продукта");
|
||
});
|
||
it("другой проект опрашивает бота (409) — переходим в режим отправки", async () => {
|
||
const s = setup({ conflict: true });
|
||
await s.a.telegramInit();
|
||
await assert.rejects(s.a.telegramPollOnce());
|
||
assert.equal(s.store.state.telegram.mode, "send-only");
|
||
});
|
||
});
|
||
|
||
describe("Требование: Границы чтения мессенджеров", () => {
|
||
it("Scenario: Пересланное боту сообщение становится задачей", async () => {
|
||
const s = setup({ now: zonedToUtc(2026, 12, 1, 10, 0, tz) });
|
||
await confirm(s);
|
||
s.tg.queue.push({
|
||
update_id: 2,
|
||
message: pm("Прошу подготовить смету до 05.12", 2, OWNER, {
|
||
forward_origin: { type: "user", sender_user: { id: 9, first_name: "Олег" } },
|
||
}),
|
||
});
|
||
await s.a.telegramPollOnce();
|
||
const [task] = s.store.state.tasks;
|
||
assert.equal(task?.title, "подготовить смету");
|
||
assert.equal(task?.source, "telegram");
|
||
assert.equal(task?.sourceTitle, "Пересланное сообщение от Олег");
|
||
assert.equal(zonedParts(new Date(task?.due ?? ""), tz).day, 5);
|
||
assert.match(s.tg.sent.at(-1)?.text ?? "", /^Новое поручение: подготовить смету/);
|
||
});
|
||
it("Scenario: Сообщение из неподтверждённого чата", async () => {
|
||
const s = setup();
|
||
await confirm(s);
|
||
await s.a.handleUpdate({ update_id: 3, message: pm("Нужно срочно перевести деньги", 3, 999) });
|
||
assert.equal(s.store.state.tasks.length, 0);
|
||
});
|
||
it("группа читается только после /watch от владельца", async () => {
|
||
const s = setup();
|
||
await confirm(s);
|
||
const g = (text: string, id: number, from: number): TgMessage => ({
|
||
message_id: id,
|
||
date: 0,
|
||
chat: { id: -1001234, type: "supergroup", title: "Команда" },
|
||
from: { id: from, first_name: "Олег" },
|
||
text,
|
||
});
|
||
await s.a.handleUpdate({ update_id: 4, message: g("Нужно обновить сайт", 10, 9) });
|
||
assert.equal(s.store.state.tasks.length, 0);
|
||
await s.a.handleUpdate({ update_id: 5, message: g("/watch", 11, 9) });
|
||
assert.equal(s.store.state.telegram.groups.length, 0, "посторонний не включает группу");
|
||
await s.a.handleUpdate({ update_id: 6, message: g("/watch", 12, OWNER) });
|
||
await s.a.handleUpdate({ update_id: 7, message: g("Нужно обновить сайт", 13, 9) });
|
||
assert.equal(s.store.state.tasks[0]?.link, "https://t.me/c/1234/13");
|
||
});
|
||
});
|
||
|
||
describe("Требование: Напоминание в подтверждённый чат", () => {
|
||
it("Scenario: Напоминание приходит один раз", async () => {
|
||
const day = (h: number) => zonedToUtc(2026, 12, 1, h, 0, tz).toISOString();
|
||
const s = setup({
|
||
mails: [{ ...mailReport, body: "Прошу подготовить отчёт сегодня" }],
|
||
events: [{ id: "e", summary: "Встреча", start: day(9), end: day(11) }],
|
||
});
|
||
await confirm(s);
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
const task = s.store.state.tasks[0];
|
||
assert.ok(task);
|
||
const r = s.a.accept(task.id);
|
||
assert.deepEqual(r, { ok: true, chatConfirmed: true });
|
||
assert.equal(zonedParts(new Date(task.accepted?.start ?? ""), tz).hour, 11);
|
||
s.clock.now = zonedToUtc(2026, 12, 1, 10, 59, tz);
|
||
assert.equal(await s.a.sendReminders(), 0);
|
||
s.clock.now = zonedToUtc(2026, 12, 1, 11, 0, tz);
|
||
assert.equal(await s.a.sendReminders(), 1);
|
||
const msg = s.tg.sent.at(-1);
|
||
assert.equal(msg?.chat_id, OWNER);
|
||
assert.match(msg?.text ?? "", /^Напоминание: подготовить отчёт/);
|
||
assert.match(
|
||
msg?.text ?? "",
|
||
/https:\/\/mail\.google\.com\/mail\/u\/\?authuser=tanya%40example\.com#all\/m1/,
|
||
);
|
||
s.clock.now = zonedToUtc(2026, 12, 1, 11, 5, tz);
|
||
assert.equal(await s.a.sendReminders(), 0);
|
||
});
|
||
it("Scenario: Чат не подтверждён", async () => {
|
||
const s = setup();
|
||
await s.a.telegramInit();
|
||
s.a.ingest({ source: "telegram", sourceId: "x", sourceTitle: "x", text: "Нужно позвонить врачу" });
|
||
const id = s.store.state.tasks[0]?.id ?? "";
|
||
assert.deepEqual(s.a.accept(id), { ok: true, chatConfirmed: false });
|
||
});
|
||
it("кнопка «Принять время» в Telegram работает только у владельца", async () => {
|
||
const s = setup();
|
||
await confirm(s);
|
||
s.a.ingest({ source: "telegram", sourceId: "x", sourceTitle: "x", text: "Нужно позвонить врачу" });
|
||
const id = s.store.state.tasks[0]?.id ?? "";
|
||
await s.a.handleUpdate({
|
||
update_id: 8,
|
||
callback_query: { id: "q1", from: { id: 999 }, data: `accept:${id}` },
|
||
});
|
||
assert.equal(s.store.state.tasks[0]?.accepted, undefined);
|
||
await s.a.handleUpdate({
|
||
update_id: 9,
|
||
callback_query: { id: "q2", from: { id: OWNER }, data: `accept:${id}` },
|
||
});
|
||
assert.ok(s.store.state.tasks[0]?.accepted);
|
||
assert.match(s.tg.answers.at(-1)?.text ?? "", /^Напомню/);
|
||
});
|
||
it("утренняя сводка приходит в 08:30 один раз", async () => {
|
||
const s = setup({ now: zonedToUtc(2026, 12, 1, 8, 0, tz) });
|
||
await confirm(s);
|
||
assert.equal(await s.a.sendDailySummary(), false);
|
||
s.clock.now = zonedToUtc(2026, 12, 1, 8, 30, tz);
|
||
assert.equal(await s.a.sendDailySummary(), true);
|
||
assert.equal(await s.a.sendDailySummary(), false);
|
||
assert.match(s.tg.sent.at(-1)?.text ?? "", /^План на/);
|
||
});
|
||
});
|
||
|
||
describe("Требование: Запись наружу только по подтверждению", () => {
|
||
it("Scenario: Добавление в календарь по кнопке", async () => {
|
||
const s = setup();
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
s.a.ingest({
|
||
source: "gmail",
|
||
sourceId: "gmail:z",
|
||
sourceTitle: "Отчёт",
|
||
text: "Прошу подготовить отчёт",
|
||
});
|
||
const id = s.store.state.tasks[0]?.id ?? "";
|
||
s.a.accept(id);
|
||
await s.a.addToCalendar(id);
|
||
assert.equal(s.g.created.length, 1);
|
||
assert.equal((s.g.created[0] as { summary: string }).summary, "подготовить отчёт");
|
||
assert.equal(s.store.state.tasks[0]?.calendarEventId, "created1");
|
||
});
|
||
it("Scenario: Без подтверждения ничего не пишется", async () => {
|
||
const s = setup({ mails: [mailReport] });
|
||
await s.a.connectGoogle("good-code", "https://x/cb");
|
||
await s.a.syncGoogle();
|
||
s.a.accept(s.store.state.tasks[0]?.id ?? "");
|
||
await s.a.tick();
|
||
assert.equal(s.g.created.length, 0);
|
||
assert.ok(!s.g.calls.some((c) => c.method === "POST" && c.url.includes("calendar")));
|
||
});
|
||
});
|