223 lines
13 KiB
JavaScript
223 lines
13 KiB
JavaScript
// BRM-165: карточка стратегии в личном Telegram Татьяны (сценарии specs/strategy-card).
|
||
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 { mockTelegramApi } from "../src/telegram.js";
|
||
import { createStrategy, SECTIONS } from "../src/strategy.js";
|
||
import { createStrategyCard, strategyBox } from "../src/strategy-card.js";
|
||
import { SEED_KEY, SEED_SECTIONS, SEED_QUESTIONS } from "../src/strategy-seed.js";
|
||
import { createBot, createBotStore, mockTranscriber } from "../src/bot.js";
|
||
import { createOwner } from "../src/owner.js";
|
||
import { createApp } from "../src/server.js";
|
||
import { webhookSecret, WEBHOOK_PATH } from "../src/bot-identity.js";
|
||
import { TEXTS } from "../src/i18n.js";
|
||
|
||
const TATIANA = 555;
|
||
const T0 = Date.parse("2026-11-23T10:00:00Z"); // 15:00 по Алматы
|
||
const iso = (ms) => new Date(ms).toISOString();
|
||
const plain = (html) => html.replace(/<[^>]+>/g, "");
|
||
|
||
function setup({ enabled = true, bound = true, failSend, sent = 0, token } = {}) {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm165-"));
|
||
const telegram = mockTelegramApi({ ...(failSend ? { failSend } : {}), ...(token !== undefined ? { token } : {}) });
|
||
const store = createBotStore(path.join(dir, "bot.json"));
|
||
if (bound) store.bind(TATIANA);
|
||
const strategy = createStrategy(path.join(dir, "strategy.json"));
|
||
const armed = [];
|
||
let ch = null;
|
||
const testRun = { channel: () => ch, offered: () => null, arm: (now) => armed.push(now), view: () => ({ sentCount: sent }), setChannel: (c) => { ch = c; } };
|
||
const card = createStrategyCard({ file: path.join(dir, "sc.json"), telegram, strategy, getOwnerChat: () => store.chatId(), testRun, enabled, siteUrl: "https://brm-staging.example", questions: SEED_QUESTIONS });
|
||
const clock = { now: T0 };
|
||
const bot = createBot({ store, telegram, pub: { status: () => ({ channels: {} }) }, owner: createOwner(path.join(dir, "o.json"), "слово"), getPlan: () => ({ ideas: [] }), savePlan() {}, transcriber: mockTranscriber(), strategyCard: card, now: () => new Date(clock.now) });
|
||
const toTatiana = () => telegram.posts[String(TATIANA)] ?? [];
|
||
const cardMsg = () => toTatiana().find((m) => m.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data?.startsWith("sv:approve"));
|
||
const press = (data) => bot.handleUpdate({ callback_query: { from: { id: TATIANA }, message: { chat: { id: TATIANA } }, data } });
|
||
const say = (text) => bot.handleUpdate({ message: { from: { id: TATIANA }, chat: { id: TATIANA }, text } });
|
||
const last = () => toTatiana().at(-1).text;
|
||
const box = () => plain(strategyBox("ru", card.view(), strategy.current()));
|
||
strategy.propose(SEED_SECTIONS, { key: SEED_KEY }, iso(T0 - 3600e3));
|
||
return { dir, telegram, store, strategy, card, testRun, armed, clock, bot, toTatiana, cardMsg, press, say, last, box };
|
||
}
|
||
|
||
test("Сценарий: Версия видна на странице — все разделы, дни 1–60 подробнее 61–90", () => {
|
||
const s = setup();
|
||
const v = s.strategy.current();
|
||
assert.equal(v.n, 1);
|
||
for (const sec of SECTIONS) assert.ok(v.sections[sec].trim(), sec);
|
||
const html = s.box();
|
||
assert.match(html, /Версия 1/);
|
||
for (const h of ["Основной вариант", "Альтернативы", "Источники", "Бюджет", "Показатели успеха"]) assert.ok(html.includes(h), h);
|
||
const lines = v.sections.plan90.split("\n");
|
||
const early = lines.filter((l) => /^Дни (\d+)/.test(l) && Number(l.match(/^Дни (\d+)/)[1]) <= 60).length;
|
||
assert.ok(early > (lines.length - early) * 2, "первые 60 дней расписаны подробнее");
|
||
assert.match(v.sections.budget, /не утверждена/);
|
||
});
|
||
|
||
test("Сценарий: Повторный запуск не создаёт дубль", () => {
|
||
const s = setup();
|
||
assert.equal(s.strategy.propose(SEED_SECTIONS, { key: SEED_KEY }, iso(T0)).skipped, "exists");
|
||
assert.equal(s.strategy.versions().length, 1);
|
||
});
|
||
|
||
test("Сценарий: Утверждённую не перетираем", () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm165-"));
|
||
const st = createStrategy(path.join(dir, "s.json"));
|
||
st.edit(Object.fromEntries(SECTIONS.map((x) => [x, "текст"])), "агент", iso(T0));
|
||
st.decide({ action: "approve", by: "Татьяна" }, iso(T0));
|
||
assert.equal(st.propose(SEED_SECTIONS, { key: SEED_KEY }, iso(T0)).skipped, "approved");
|
||
assert.equal(st.versions().length, 1);
|
||
assert.ok(st.isApproved());
|
||
});
|
||
|
||
test("Сценарий: Карточка доставлена — кнопки, время по Алматы, «ждём согласования»", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
const m = s.cardMsg();
|
||
assert.match(m.text, /Стратегия бренда, версия 1/);
|
||
assert.deepEqual(m.reply_markup.inline_keyboard[0].map((b) => b.text), ["Утвердить", "На доработку"]);
|
||
assert.match(s.box(), /Карточка доставлена в Telegram: 23\.11\.2026 15:00 по Алматы/);
|
||
assert.match(s.box(), /Версия 1: ждём согласования/);
|
||
assert.ok(!m.text.includes("MOCK_TELEGRAM_TOKEN"));
|
||
await s.card.tick(T0 + 60e3);
|
||
assert.equal(s.toTatiana().filter((x) => x.text.startsWith("Стратегия бренда")).length, 1, "карточка одна");
|
||
});
|
||
|
||
test("Сценарий: Утвердить — «утверждена» с датой и временем по Алматы", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
s.clock.now = T0 + 30 * 60e3;
|
||
await s.press(s.cardMsg().reply_markup.inline_keyboard[0][0].callback_data);
|
||
assert.equal(s.strategy.current().status, "approved");
|
||
assert.match(s.last(), /утверждена 23\.11\.2026 15:30 по Алматы/);
|
||
assert.match(s.box(), /Версия 1: утверждена 23\.11\.2026 15:30 по Алматы/);
|
||
assert.equal(s.armed.length, 1);
|
||
});
|
||
|
||
test("Сценарий: На доработку — замечание сохранено, стратегия не утверждена", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
await s.press(s.cardMsg().reply_markup.inline_keyboard[0][1].callback_data);
|
||
await s.say("Добавить выступления");
|
||
const v = s.strategy.current();
|
||
assert.equal(v.status, "revision");
|
||
assert.ok(v.comments.some((c) => c.text === "Добавить выступления"));
|
||
assert.equal(s.strategy.isApproved(), false);
|
||
assert.match(s.box(), /на доработке/);
|
||
assert.match(s.last(), /Замечание сохранено/);
|
||
});
|
||
|
||
test("Сценарий: Версия поменялась после карточки — старая кнопка не утверждает", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
const old = s.cardMsg().reply_markup.inline_keyboard[0][0].callback_data;
|
||
s.strategy.edit({ budget: "Другая вилка" }, "агент", iso(T0 + 1));
|
||
await s.press(old);
|
||
assert.match(s.last(), /версия стратегии изменилась/);
|
||
assert.equal(s.strategy.isApproved(), false);
|
||
});
|
||
|
||
test("Сценарий: Не версия для проверки — карточка не отправляется, сказано, кто отправляет", async () => {
|
||
const s = setup({ enabled: false });
|
||
await s.card.tick(T0);
|
||
assert.equal(s.toTatiana().length, 0);
|
||
const html = strategyBox("ru", s.card.view(), s.strategy.current(), "https://brm-staging.example/strategy.html");
|
||
assert.match(plain(html), /Карточку Татьяне отправляет версия для проверки/);
|
||
assert.match(html, /href="https:\/\/brm-staging\.example\/strategy\.html"/);
|
||
});
|
||
|
||
test("Сценарий: Владелица не привязана — что мешает и что сделать", async () => {
|
||
const s = setup({ bound: false });
|
||
await s.card.tick(T0);
|
||
const html = s.box();
|
||
assert.match(html, /Что мешает: Владелица не подключена к боту\. Кто снимает: вы\. Что сделать: напишите боту \/start и слово для одобрения/);
|
||
assert.match(html, /черновик, карточка ещё не доставлена/);
|
||
});
|
||
|
||
test("Сценарий: Telegram не принял сообщение — причина без ключа бота", async () => {
|
||
const s = setup({ failSend: "Forbidden: bot was blocked by the user MOCK_TELEGRAM_TOKEN" });
|
||
await s.card.tick(T0);
|
||
const html = s.box();
|
||
assert.match(html, /Telegram не доставил сообщение в ваш чат с ботом \(Forbidden: bot was blocked by the user \*\*\*\)/);
|
||
assert.match(html, /Что сделать: откройте бота в Telegram/);
|
||
assert.ok(!html.includes("MOCK_TELEGRAM_TOKEN"));
|
||
assert.ok(!JSON.stringify(s.card.view()).includes("MOCK_TELEGRAM_TOKEN"));
|
||
});
|
||
|
||
test("Сценарий: Вопросы заданы — не больше трёх, с «Зачем спрашиваем» и вариантами", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
const qs = s.toTatiana().filter((m) => m.text.startsWith("Вопрос по стратегии"));
|
||
assert.equal(qs.length, 3);
|
||
for (const q of qs) {
|
||
assert.match(q.text, /\nЗачем спрашиваем: [^\n]+$/);
|
||
assert.ok(q.reply_markup.inline_keyboard.length >= 2);
|
||
}
|
||
assert.equal((s.box().match(/ждём решения владельца/g) ?? []).length, 5, "3 вопроса + канал + чат");
|
||
await s.card.tick(T0 + 60e3);
|
||
assert.equal(s.toTatiana().filter((m) => m.text.startsWith("Вопрос по стратегии")).length, 3, "повторно не задаются");
|
||
});
|
||
|
||
test("Сценарий: Ответ на вопрос — виден на странице и записан замечанием", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
await s.press("sq:goal:0");
|
||
assert.match(s.box(), /Ответ: Клиенты на консультации/);
|
||
assert.ok(s.strategy.current().comments.some((c) => c.text.includes("Клиенты на консультации")));
|
||
assert.equal(s.strategy.current().status, "draft", "ответ не меняет стадию");
|
||
});
|
||
|
||
test("Сценарий: Чат для сводок — «Да, сюда»", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
assert.ok(s.toTatiana().some((m) => m.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data === "ss:here"));
|
||
await s.press("ss:here");
|
||
assert.match(s.box(), /Чат для сводок: ваш личный чат с ботом/);
|
||
assert.equal(s.card.summaryChat(), TATIANA);
|
||
});
|
||
|
||
test("Сценарий: Ответа ещё нет — канал и чат «ждём решения владельца», за неё ничего не ставится", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
const html = s.box();
|
||
assert.match(html, /Закрытый канал для проверки: ждём решения владельца/);
|
||
assert.match(html, /Чат для сводок: ждём решения владельца/);
|
||
assert.equal(s.card.summaryChat(), null);
|
||
});
|
||
|
||
test("Сценарий: Чужой аккаунт не может утвердить", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
await s.bot.handleUpdate({ callback_query: { from: { id: 777 }, message: { chat: { id: 777 } }, data: s.cardMsg().reply_markup.inline_keyboard[0][0].callback_data } });
|
||
assert.equal(s.strategy.isApproved(), false);
|
||
});
|
||
|
||
test("Сценарий: Запущено — утверждена и вышла проверочная публикация", async () => {
|
||
const s = setup({ sent: 1 });
|
||
await s.card.tick(T0);
|
||
await s.press(s.cardMsg().reply_markup.inline_keyboard[0][0].callback_data);
|
||
assert.match(s.box(), /запущено — утверждена/);
|
||
});
|
||
|
||
test("Страница «Стратегия и правила»: блок виден до скриптов, без ключа; карточка уходит через вебхук версии для проверки", async () => {
|
||
const TOKEN = "MOCK_TELEGRAM_TOKEN";
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm165-"));
|
||
const telegram = mockTelegramApi({ token: TOKEN });
|
||
const app = createApp({ file: path.join(dir, "plan.json"), telegram, webhookSecret: webhookSecret(TOKEN, {}), webhook: "https://brm-staging.example" + WEBHOOK_PATH, siteUrl: "https://brm-staging.example" });
|
||
app.seedStrategy();
|
||
const srv = app.listen(0);
|
||
await new Promise((r) => srv.once("listening", r));
|
||
const base = `http://127.0.0.1:${srv.address().port}`;
|
||
try {
|
||
let page = await (await fetch(base + "/strategy.html")).text();
|
||
assert.match(page, /id="svcard"/);
|
||
assert.match(plain(page), /Владелица не подключена к боту|черновик, карточка ещё не доставлена/);
|
||
await app.runDue(T0);
|
||
page = plain(await (await fetch(base + "/strategy.html")).text());
|
||
assert.match(page, /Что мешает: Владелица не подключена к боту/);
|
||
assert.ok(!page.includes(TOKEN));
|
||
for (const k of ["sv.h", "sv.stage.waiting", "sv.waitOwner", "ui.str.sec.main"]) assert.ok(TEXTS.kk[k] && TEXTS.en[k], k);
|
||
} finally { srv.close(); }
|
||
});
|