import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { createApp } from "../src/server.js"; import { mockTelegram } from "../src/telegram.js"; import { buildSummary } from "../src/metrics.js"; async function withServer(telegram, fn, dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm16-"))) { const srv = createApp({ file: path.join(dir, "plan.json"), telegram }).listen(0); await new Promise((r) => srv.once("listening", r)); const base = `http://127.0.0.1:${srv.address().port}`; const call = async (m, u, b) => { const r = await fetch(base + u, { method: m, headers: { "content-type": "application/json" }, body: b && JSON.stringify(b) }); return [r.status, await r.json()]; }; try { await fn(call); } finally { srv.close(); } } const HEADS = ["Сделано", "Результат", "Возможность", "Риск", "Нужно решение", "Следующий шаг"]; test("Сценарий: сохранение значения и видно после перезапуска", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm16-")); await withServer(mockTelegram(), async (call) => { assert.equal((await call("POST", "/api/metrics", { name: "Подписчики основного канала", unit: "чел.", value: "120", date: "2026-11-15" }))[0], 200); }, dir); await withServer(mockTelegram(), async (call) => { const [, d] = await call("GET", "/api/metrics"); assert.equal(d.metrics.find((m) => m.name === "Подписчики основного канала").entries[0].value, 120); }, dir); }); test("Сценарий: шестой показатель и неверные данные отклоняются", () => withServer(mockTelegram(), async (call) => { assert.equal((await call("GET", "/api/metrics"))[1].metrics.length, 5); assert.equal((await call("POST", "/api/metrics", { name: "M6", value: 1, date: "2026-11-15" }))[0], 400); assert.equal((await call("POST", "/api/metrics", { name: "Отклики", value: "abc", date: "2026-11-15" }))[0], 400); assert.equal((await call("POST", "/api/metrics", { name: "Отклики", value: 2, date: "2026-13-01" }))[0], 400); })); test("Сценарий: недельная сводка с изменением, шесть разделов по порядку", () => { const metrics = [{ name: "Подписчики", entries: [{ date: "2026-11-08", value: 100 }, { date: "2026-11-15", value: 120 }] }]; const t = buildSummary({ metrics, period: "week", asOf: "2026-11-15", sections: { done: "Пост" } }); assert.match(t.split("\n")[0], /неделя: 2026-11-08 → 2026-11-15/); assert.match(t, /Подписчики: 120 — было 100 \(2026-11-08\), \+20/); const pos = HEADS.map((h) => t.indexOf(h + ":")); assert.deepEqual([...pos].sort((a, b) => a - b), pos); assert.ok(pos.every((p) => p >= 0)); }); test("Сценарий: одна запись и пустые разделы", () => { const t = buildSummary({ metrics: [{ name: "Обращения", entries: [{ date: "2026-11-15", value: 3 }] }], period: "day", asOf: "2026-11-15" }); assert.match(t, /первое значение/); assert.equal(t.match(/\nнет$/gm).length, 5); }); test("Сценарий: показатель без записей — «нет данных»", () => { const t = buildSummary({ metrics: [{ name: "Охват", entries: [] }], period: "day", asOf: "2026-11-15" }); assert.match(t, /Охват: нет данных за период/); }); test("Сценарий: отправка одним сообщением", () => withServer(mockTelegram(), async () => {}).then(async () => { const tg = mockTelegram(); await withServer(tg, async (call) => { const [c, d] = await call("POST", "/api/summary/send", { period: "day", date: "2026-11-15" }); assert.equal(c, 200); assert.equal(tg.sent.length, 1); assert.equal(tg.sent[0].text, d.text); }); })); test("Сценарий: Telegram недоступен или не подключён — текст не теряется", async () => { await withServer(mockTelegram({ fail: "boom" }), async (call) => { const [c, d] = await call("POST", "/api/summary/send", { period: "week", date: "2026-11-15" }); assert.equal(c, 502); assert.match(d.error, /Не удалось отправить/); assert.match(d.text, /Сводка по бренду/); }); await withServer({ connected: () => false, secrets: () => [], send: async () => {} }, async (call) => { const [c, d] = await call("POST", "/api/summary/send", { period: "day" }); assert.equal(c, 409); assert.ok(d.text); }); await withServer(mockTelegram(), async (call) => { assert.equal((await call("POST", "/api/summary/preview", { period: "year" }))[0], 400); }); }); test("Сценарий: пять стартовых цифр с единицами", () => withServer(mockTelegram(), async (call) => { const [, d] = await call("GET", "/api/metrics"); assert.equal(d.metrics.length, 5); assert.ok(d.metrics.every((m) => m.name && m.unit)); })); test("Сценарий: значение с единицей и датой; устаревшее — «нет данных за период»", () => { const metrics = [ { name: "Отклики", unit: "шт.", entries: [{ date: "2026-11-14", value: 4 }] }, { name: "Встречи", unit: "шт.", entries: [{ date: "2026-10-01", value: 9 }] }, ]; const t = buildSummary({ metrics, period: "week", asOf: "2026-11-15" }); assert.match(t, /Отклики: 4 шт\. \(на 2026-11-14\)/); assert.match(t, /Встречи: нет данных за период \(последнее: 9 шт\. на 2026-10-01\)/); assert.doesNotMatch(t, /Встречи: 9/); }); test("Сценарий: сводка не длиннее 1000 знаков", () => { const long = "очень длинный текст ".repeat(100); const t = buildSummary({ metrics: [], period: "week", asOf: "2026-11-15", sections: { done: long, risk: long, next: long, decision: long, opportunity: long } }); assert.ok(t.length <= 1000, String(t.length)); assert.match(t, /Следующий шаг:/); }); test("Сценарий: расписание — недельная в понедельник 09:00 по Алматы, повтора нет", async () => { const tg = mockTelegram(); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm25-")); const srv = createApp({ file: path.join(dir, "plan.json"), telegram: tg }); const at = (iso) => Date.parse(iso); assert.equal((await srv.runDue(at("2026-11-15T23:00:00Z"))).length, 0); // пн 04:00 по Алматы — ещё рано assert.equal((await srv.runDue(at("2026-11-16T04:00:00Z"))).length, 1); // пн 09:00 Алматы assert.equal((await srv.runDue(at("2026-11-16T05:00:00Z"))).length, 0); assert.equal(tg.sent.length, 1); }); test("Сценарий: ежедневная выключена по умолчанию, включается переключателем", async () => { const tg = mockTelegram(); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm25-")); const srv = createApp({ file: path.join(dir, "plan.json"), telegram: tg }).listen(0); await new Promise((r) => srv.once("listening", r)); const base = `http://127.0.0.1:${srv.address().port}`; try { assert.equal((await srv.runDue(Date.parse("2026-11-17T04:00:00Z"))).length, 0); // вторник const r = await fetch(base + "/api/summary/settings", { method: "PUT", body: JSON.stringify({ daily: { enabled: true } }) }); assert.equal(r.status, 200); const out = await srv.runDue(Date.parse("2026-11-17T04:00:00Z")); assert.equal(out.length, 1); assert.equal(out[0].kind, "day"); const bad = await fetch(base + "/api/summary/settings", { method: "PUT", body: JSON.stringify({ weekly: { time: "25:00" } }) }); assert.equal(bad.status, 400); } finally { srv.close(); } }); test("Сценарий: после остановки сводки не уходят, текст в журнале; сбой Telegram виден в журнале", async () => { const tg = mockTelegram(); await withServer(tg, async (call) => { await call("POST", "/api/summary/stop", {}); const [c, d] = await call("POST", "/api/summary/send", { period: "week", date: "2026-11-15" }); assert.equal(c, 502); assert.match(d.error, /остановлена/); assert.ok(d.text); assert.equal(tg.sent.length, 0); const [, log] = await call("GET", "/api/summary/log"); assert.equal(log[0].reason, "stopped"); assert.equal(log[0].text, d.text); }); await withServer(mockTelegram({ fail: "boom" }), async (call) => { await call("POST", "/api/summary/send", { period: "day", date: "2026-11-15" }); const [, log] = await call("GET", "/api/summary/log"); assert.equal(log[0].result, "error"); }); }); // BRM-61: кнопка на версии без Telegram отвечает словами и оставляет след в журнале. test("Сценарий: Отправка выключена на этой версии — сообщение и запись в журнале", async () => { const off = { connected: () => false, secrets: () => [], send: async () => { throw new Error("не должно вызываться"); } }; await withServer(off, async (call) => { const [c, d] = await call("POST", "/api/summary/send", { period: "week", date: "2026-11-16" }); assert.equal(c, 409); assert.equal(d.off, true); assert.match(d.error, /^На этой версии отправка выключена, сводка в Telegram не ушла\./); assert.match(d.text, /Сводка по бренду/); const [, log] = await call("GET", "/api/summary/log"); assert.equal(log.length, 1); assert.equal(log[0].result, "error"); assert.equal(log[0].off, true); assert.equal(log[0].text, d.text); }); }); test("Сценарий: сообщение о выключенной отправке на языке страницы", async () => { const off = { connected: () => false, secrets: () => [], send: async () => {} }; await withServer(off, async (call) => { const r = await call("POST", "/api/summary/send", { period: "day", date: "2026-11-16" }); assert.equal(r[0], 409); }); const { TEXTS } = await import("../src/i18n.js"); for (const l of ["ru", "kk", "en"]) for (const k of ["err.sum.off", "err.sum.stopped", "err.sum.limit", "err.sum.failed", "ui.sum.log.off", "ui.sum.sendOffTip"]) assert.ok(TEXTS[l][k], `${l} ${k}`); }); // BRM-78: почему отправка выключена import { createTelegram } from "../src/telegram.js"; import { createLinkedIn } from "../src/linkedin.js"; import { homePage } from "../src/site.js"; import { botPage } from "../src/bot-page.js"; test("Сценарий: ключ бота есть, чата нет — причина названа прямо", () => { const tg = createTelegram({ token: "x", chatId: "" }); assert.equal(tg.connected(), false); assert.equal(tg.missing(), "chat"); assert.equal(createTelegram({ token: "", chatId: "1" }).missing(), "key"); assert.equal(createLinkedIn({ token: "t", author: "" }).missing(), "author"); const home = homePage("ru", undefined, null, [], { telegram: "chat", linkedin: "key" }); assert.match(home, /Telegram:<\/b> Отправка в Telegram выключена: ключ бота уже есть/); assert.match(home, /LinkedIn:<\/b> Отправка в LinkedIn выключена/); assert.match(home, /версия для проверки|версии для проверки/); const bot = botPage("ru", { sending: false, paused: false, connected: false, missing: "chat", reports: Object.fromEntries(["day","week"].map((k) => [k, { last: null, next: null }])), errors: [] }); assert.match(bot, /ключ бота уже есть/); }); test("Сценарий: всё подключено — объяснения нет", () => { assert.doesNotMatch(homePage("ru", undefined, null, [], {}), /id="sendwhy"/); });