142 lines
8.4 KiB
JavaScript
142 lines
8.4 KiB
JavaScript
// BRM-190: первый рабочий запуск — журнал доставки карточки и идея первой публикации (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 } from "../src/strategy.js";
|
||
import { createStrategyCard, strategyBox, LOG_MAX } from "../src/strategy-card.js";
|
||
import { SEED_KEY, SEED_SECTIONS, SEED_QUESTIONS, FIRST_TOPICS } from "../src/strategy-seed.js";
|
||
import { createBot, createBotStore, mockTranscriber } from "../src/bot.js";
|
||
import { createOwner } from "../src/owner.js";
|
||
import { TEXTS } from "../src/i18n.js";
|
||
import { waitList } from "../src/bot-page.js";
|
||
|
||
const TATIANA = 555;
|
||
const T0 = Date.parse("2026-11-27T09:09:00Z"); // 14:09 по Алматы
|
||
const iso = (ms) => new Date(ms).toISOString();
|
||
const plain = (html) => html.replace(/<[^>]+>/g, "");
|
||
|
||
function setup({ bound = true } = {}) {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm190-"));
|
||
const telegram = mockTelegramApi({});
|
||
const store = createBotStore(path.join(dir, "bot.json"));
|
||
if (bound) store.bind(TATIANA);
|
||
const strategy = createStrategy(path.join(dir, "strategy.json"));
|
||
const testRun = { channel: () => null, offered: () => null, arm() {}, view: () => ({ sentCount: 0 }) };
|
||
const card = createStrategyCard({ file: path.join(dir, "sc.json"), telegram, strategy, getOwnerChat: () => store.chatId(), testRun, enabled: true, siteUrl: "https://brm-prod.example", questions: SEED_QUESTIONS, topics: FIRST_TOPICS });
|
||
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 msgs = () => telegram.posts[String(TATIANA)] ?? [];
|
||
const withButton = (prefix) => msgs().filter((m) => m.reply_markup?.inline_keyboard?.[0]?.[0]?.callback_data?.startsWith(prefix));
|
||
const press = (data) => bot.handleUpdate({ callback_query: { from: { id: TATIANA }, message: { chat: { id: TATIANA } }, data } });
|
||
const box = () => plain(strategyBox("ru", card.view(), strategy.current()));
|
||
strategy.propose(SEED_SECTIONS, { key: SEED_KEY }, iso(T0 - 3600e3));
|
||
const approve = async () => { await card.tick(clock.now); await press(withButton("sv:approve").at(-1).reply_markup.inline_keyboard[0][0].callback_data); };
|
||
return { telegram, store, strategy, card, clock, msgs, withButton, press, box, approve };
|
||
}
|
||
|
||
test("Сценарий: Сначала не привязана, потом доставлена — две строки журнала", async () => {
|
||
const s = setup({ bound: false });
|
||
await s.card.tick(T0);
|
||
await s.card.tick(T0 + 60e3);
|
||
s.store.bind(TATIANA);
|
||
await s.card.tick(T0 + 11 * 60e3);
|
||
const v = s.card.view();
|
||
assert.equal(v.log.length, 2);
|
||
const b = s.box();
|
||
assert.match(b, /27\.11\.2026 14:09 по Алматы — Версия 1: не доставлена — Владелица не подключена к боту \(последняя проверка 27\.11\.2026 14:10 по Алматы\)/);
|
||
assert.match(b, /27\.11\.2026 14:20 по Алматы — Версия 1: доставлена в личный чат Татьяны/);
|
||
assert.ok(b.indexOf("14:20 по Алматы — Версия 1: доставлена") < b.indexOf("14:09 по Алматы — Версия 1: не доставлена"), "новые сверху");
|
||
});
|
||
|
||
test("Граница: попыток ещё не было — так и написано; журнал не растёт без предела", async () => {
|
||
const s = setup({ bound: false });
|
||
assert.match(s.box(), /Попыток доставки ещё не было/);
|
||
for (let i = 0; i < 100; i++) await s.card.tick(T0 + i * 60e3);
|
||
assert.equal(s.card.view().log.length, 1);
|
||
assert.ok(LOG_MAX >= 10);
|
||
});
|
||
|
||
test("Сценарий: До утверждения идеи нет", async () => {
|
||
const s = setup();
|
||
await s.card.tick(T0);
|
||
await s.card.tick(T0 + 60e3);
|
||
assert.equal(s.withButton("st:").length, 0);
|
||
assert.match(s.box(), /после того, как она утвердит стратегию/);
|
||
assert.equal(s.card.view().topic.state, "afterApprove");
|
||
});
|
||
|
||
test("Сценарий: Идея пришла после «Утвердить» — только сообщение Татьяне", async () => {
|
||
const s = setup();
|
||
await s.approve();
|
||
s.clock.now = T0 + 60e3;
|
||
await s.card.tick(s.clock.now);
|
||
const topic = s.withButton("st:");
|
||
assert.equal(topic.length, 1);
|
||
assert.match(topic[0].text, /Идея первой публикации/);
|
||
assert.deepEqual(topic[0].reply_markup.inline_keyboard[0].map((b) => b.text), ["Подходит", "Другую идею"]);
|
||
assert.match(topic[0].text, /только в подтверждённый закрытый канал/);
|
||
const b = s.box();
|
||
assert.match(b, new RegExp(FIRST_TOPICS[0].text));
|
||
assert.match(b, /Отправлена Татьяне в Telegram: 27\.11\.2026 14:10 по Алматы\. ждём решения владельца/);
|
||
// в каналы ничего: все сообщения — только в личный чат Татьяны
|
||
assert.deepEqual(Object.keys(s.telegram.posts), [String(TATIANA)]);
|
||
await s.card.tick(T0 + 2 * 60e3);
|
||
assert.equal(s.withButton("st:").length, 1, "второй раз не шлём");
|
||
});
|
||
|
||
test("Сценарий: Подходит — идея выбрана, публикаций нет", async () => {
|
||
const s = setup();
|
||
await s.approve();
|
||
await s.card.tick(T0 + 60e3);
|
||
s.clock.now = T0 + 5 * 60e3;
|
||
await s.press(s.withButton("st:").at(-1).reply_markup.inline_keyboard[0][0].callback_data);
|
||
assert.match(s.msgs().at(-1).text, /Записал идею/);
|
||
assert.match(s.box(), /Татьяна выбрала эту идею \(27\.11\.2026 14:14 по Алматы\)/);
|
||
assert.deepEqual(Object.keys(s.telegram.posts), [String(TATIANA)]);
|
||
await s.press(s.withButton("st:").at(-1).reply_markup.inline_keyboard[0][1].callback_data);
|
||
assert.equal(s.card.view().topic.state, "ok", "повторное нажатие не меняет выбор");
|
||
});
|
||
|
||
test("Сценарий: Другую идею — следующая; Идеи кончились — «нужна другая идея»", async () => {
|
||
const s = setup();
|
||
await s.approve();
|
||
await s.card.tick(T0 + 60e3);
|
||
for (let i = 1; i < FIRST_TOPICS.length; i++) {
|
||
await s.press(s.withButton("st:").at(-1).reply_markup.inline_keyboard[0][1].callback_data);
|
||
assert.equal(s.withButton("st:").length, i + 1);
|
||
assert.match(s.withButton("st:").at(-1).text, new RegExp(`\\(${i + 1} из ${FIRST_TOPICS.length}\\)`));
|
||
}
|
||
await s.press(s.withButton("st:").at(-1).reply_markup.inline_keyboard[0][1].callback_data);
|
||
assert.match(s.msgs().at(-1).text, /агент подготовит новые идеи/);
|
||
assert.match(s.box(), /нужна другая идея/);
|
||
});
|
||
|
||
test("Граница: старая кнопка идеи не срабатывает", async () => {
|
||
const s = setup();
|
||
await s.approve();
|
||
await s.card.tick(T0 + 60e3);
|
||
const old = s.withButton("st:")[0].reply_markup.inline_keyboard[0][0].callback_data;
|
||
await s.press(s.withButton("st:").at(-1).reply_markup.inline_keyboard[0][1].callback_data);
|
||
await s.press(old);
|
||
assert.match(s.msgs().at(-1).text, /изменилась/);
|
||
assert.equal(s.card.view().topic.state, "waiting");
|
||
});
|
||
|
||
test("Идея ждёт ответа — видна в «Ждут вашего решения» со ссылкой", () => {
|
||
const html = waitList("ru", { total: 1, parts: { topic: 1 } });
|
||
assert.match(html, /id="nowdec-topic"/);
|
||
assert.match(html, /href="\/strategy\.html#svtopic"/);
|
||
});
|
||
|
||
test("Тексты журнала и идеи есть на трёх языках и без служебных слов", () => {
|
||
const keys = Object.keys(TEXTS.ru).filter((k) => /^sv\.(log|topic)\.|^now\.(dec|go)\.topic$|^deploy\.note\.brm190$/.test(k));
|
||
assert.ok(keys.length >= 20);
|
||
for (const lang of ["ru", "kk", "en"]) for (const k of keys) {
|
||
assert.ok(TEXTS[lang][k], `${lang}:${k}`);
|
||
assert.ok(!/TOKEN|секрет|Secret|вебхук|webhook|настройк|staging/i.test(TEXTS[lang][k]), `${lang}:${k}`);
|
||
}
|
||
});
|