139 lines
8.7 KiB
JavaScript
139 lines
8.7 KiB
JavaScript
// BRM-163: карточка согласования и журнал отправки у записи «Плана и банка идей» (specs/plan-approval-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 { createTestRun, CHANNEL } from "../src/test-run.js";
|
||
import { mockTelegramApi } from "../src/telegram.js";
|
||
import { createPublisher } from "../src/publisher.js";
|
||
import { createStrategy, SECTIONS } from "../src/strategy.js";
|
||
import { withApproval } from "../src/approval.js";
|
||
import { createAssetStore } from "../src/assets.js";
|
||
import { createFactsStore } from "../src/facts.js";
|
||
import { createBot, createBotStore, mockTranscriber } from "../src/bot.js";
|
||
import { createOwner } from "../src/owner.js";
|
||
import { planCard, pickIdea } from "../src/plan-card.js";
|
||
import { createApp } from "../src/server.js";
|
||
|
||
const TATIANA = 555;
|
||
const CH = -1001234567890;
|
||
const T0 = Date.parse("2026-11-22T05:00:00Z"); // 10:00 по Алматы
|
||
const NOON = Date.parse("2026-11-22T07:00:00Z"); // 12:00 по Алматы
|
||
|
||
function setup() {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm163-"));
|
||
const telegram = mockTelegramApi({});
|
||
const chat = { id: CH, type: "channel", title: "Тест BRM" };
|
||
telegram.chats[String(CH)] = chat;
|
||
telegram.members[String(CH)] = { status: "administrator", can_post_messages: true, user: { id: 900 } };
|
||
const store = createBotStore(path.join(dir, "bot.json"));
|
||
store.bind(TATIANA);
|
||
const strategy = createStrategy(path.join(dir, "strategy.json"));
|
||
const plan = { ideas: [withApproval({ id: 1, title: "Первый пост", description: "", rubric: 1, date: "2026-11-22" }), withApproval({ id: 2, title: "Второй пост", description: "", rubric: 2, date: "2026-11-30" })], publications: [] };
|
||
const clock = { now: T0 };
|
||
let pub;
|
||
const tr = createTestRun({ file: path.join(dir, "tr.json"), telegram, getOwnerChat: () => store.chatId(), getPlan: () => plan, facts: createFactsStore(path.join(dir, "facts.json")), assets: createAssetStore(path.join(dir, "assets.json")), strategy, pub: () => pub });
|
||
pub = createPublisher({ file: path.join(dir, "p.json"), channels: { [CHANNEL]: tr.adapter }, gate: (r) => strategy.gate(r), now: () => clock.now });
|
||
const bot = createBot({ store, telegram, pub, owner: createOwner(path.join(dir, "o.json"), "слово"), getPlan: () => plan, savePlan() {}, transcriber: mockTranscriber(), testRun: tr, now: () => new Date(clock.now) });
|
||
const press = (data) => bot.handleUpdate({ callback_query: { from: { id: TATIANA }, message: { chat: { id: TATIANA } }, data } });
|
||
const ready = async () => {
|
||
await bot.handleUpdate({ my_chat_member: { chat, from: { id: TATIANA }, new_chat_member: { status: "administrator" } } });
|
||
await press(`tc:yes:${CH}`);
|
||
strategy.edit(Object.fromEntries(SECTIONS.map((s) => [s, "текст"])), "агент", new Date(T0).toISOString());
|
||
strategy.decide({ action: "approve", by: "Татьяна" }, new Date(T0).toISOString());
|
||
tr.arm(T0);
|
||
};
|
||
const html = (id, extra = {}) => planCard("ru", { ideas: plan.ideas, idea: pickIdea(plan.ideas, id, "2026-11-22"), tr: tr.view(clock.now), publications: plan.publications, why: tr.why, wordSet: true, ...extra });
|
||
return { plan, tr, clock, ready, html };
|
||
}
|
||
const text = (h) => h.replace(/<[^>]+>/g, " ").replace(/"/g, '"').replace(/&/g, "&").replace(/\s+/g, " ");
|
||
|
||
test("Запись выбрана, карточка ждёт решения: текст, материалы, канал, время и три кнопки", async () => {
|
||
const s = setup();
|
||
await s.ready();
|
||
await s.tr.tick(T0);
|
||
const h = s.html("1");
|
||
const v = text(h);
|
||
for (const want of ["Текст", "[Тест] Первый пост", "Материалы: нет", "«Тест BRM»", "22.11.2026 12:00", "Слово для одобрения", "Сейчас: ждёт решения"]) assert.ok(v.includes(want), want);
|
||
for (const b of ["approve", "rework", "reject"]) assert.match(h, new RegExp(`<button type="submit" name="action" value="${b}">`));
|
||
assert.match(h, /action="\/bot\/test-card" id="apform"><input type="hidden" name="back" value="plan">/);
|
||
});
|
||
|
||
test("Карточки ещё нет: кнопки серые, причина рядом, время по дате записи", async () => {
|
||
const s = setup();
|
||
await s.ready();
|
||
await s.tr.tick(T0);
|
||
const h = s.html("2");
|
||
const v = text(h);
|
||
for (const want of ["Второй пост", "Материалы: нет", "30.11.2026 12:00", "Одобрить", "Доработать", "Отклонить"]) assert.ok(v.includes(want), want);
|
||
assert.equal((h.match(/class="off" aria-disabled="true"/g) ?? []).length, 3);
|
||
assert.match(h, /<small id="apwhy">Карточки этой записи пока нет/);
|
||
});
|
||
|
||
test("Записей нет: пустая карточка с подсказкой и три серые кнопки", () => {
|
||
const h = planCard("ru", { ideas: [], idea: null, tr: null });
|
||
assert.match(text(h), /Записей пока нет/);
|
||
assert.equal((h.match(/aria-disabled="true"/g) ?? []).length, 3);
|
||
assert.match(text(h), /Ничего не отправлено/);
|
||
});
|
||
|
||
test("Запись не одобрена: в журнале «Ничего не отправлено», тестовых и настоящих 0", async () => {
|
||
const s = setup();
|
||
await s.ready();
|
||
await s.tr.tick(T0);
|
||
const v = text(s.html("1"));
|
||
assert.match(v, /Журнал отправки этой записи/);
|
||
assert.match(v, /Ничего не отправлено/);
|
||
assert.match(v, /Тестовых: 0, настоящих: 0/);
|
||
});
|
||
|
||
test("Публикация ушла: ссылка, номер сообщения и время, метка «тест»", async () => {
|
||
const s = setup();
|
||
await s.ready();
|
||
await s.tr.tick(T0);
|
||
const c = s.tr.view().cards[0];
|
||
await s.tr.onButton("approve", c.id, c.hash, T0 + 60e3);
|
||
assert.match(text(s.html("1")), /Сейчас: одобрено/);
|
||
s.clock.now = NOON;
|
||
await s.tr.tick(NOON);
|
||
const sent = s.tr.view().cards[0];
|
||
assert.equal(sent.status, "sent");
|
||
const h = s.html("1");
|
||
const v = text(h);
|
||
assert.ok(v.includes(`тест Отправлено: сообщение №${sent.messageId}, 22.11.2026 12:00 по Алматы.`), v);
|
||
assert.ok(h.includes(`href="https://t.me/c/1234567890/${sent.messageId}"`));
|
||
assert.match(v, /Тестовых: 1, настоящих: 0/);
|
||
});
|
||
|
||
test("Отмеченная вручную настоящая публикация: «настоящая», без метки «тест»", () => {
|
||
const idea = withApproval({ id: 5, title: "Пост", rubric: 1, date: "2026-12-01", status: "published" });
|
||
const h = planCard("ru", { ideas: [idea], idea, tr: null, publications: [{ id: 1, ideaId: 5, channel: "linkedin", date: "2026-12-02", createdAt: "2026-12-02T08:00:00Z" }] });
|
||
const li = h.match(/<ul id="appubs">(.*?)<\/ul>/)[1];
|
||
assert.match(text(li), /настоящая LinkedIn, 2026-12-02, отмечено вручную/);
|
||
assert.doesNotMatch(li, /class="smp"/);
|
||
assert.match(text(h), /Тестовых: 0, настоящих: 1/);
|
||
});
|
||
|
||
test("Страница плана: карточка в ответе сервера до скриптов, выбор по ?id, возврат к записи после решения", async () => {
|
||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm163s-"));
|
||
const srv = createApp({ file: path.join(dir, "plan.json") }).listen(0);
|
||
const base = `http://127.0.0.1:${srv.address().port}`;
|
||
try {
|
||
let page = await (await fetch(base + "/plan.html")).text();
|
||
assert.match(page, /id="apcard"/);
|
||
assert.match(page, /Записей пока нет/);
|
||
const st = await (await fetch(base + "/api/state")).json();
|
||
const r = await fetch(base + "/api/ideas", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ title: "Пост из плана", rubric: 1, date: st.start }) });
|
||
assert.equal(r.status, 201);
|
||
const id = (await r.json()).ideas[0].id;
|
||
page = await (await fetch(base + "/plan.html?id=" + id)).text();
|
||
assert.match(page, /<b id="aptitle">Пост из плана<\/b>/);
|
||
assert.match(page, /<p id="aptime">Время публикации: .* 12:00 по Алматы<\/p>/);
|
||
assert.equal((page.match(/class="off" aria-disabled="true" aria-describedby="apwhy"/g) ?? []).length, 3);
|
||
const post = await fetch(base + "/bot/test-card", { method: "POST", redirect: "manual", headers: { "content-type": "application/x-www-form-urlencoded" }, body: "back=plan&id=99&action=approve&word=x" });
|
||
assert.equal(post.status, 303);
|
||
assert.match(post.headers.get("location"), /^\/plan\.html\?id=&card=(noWord|wrong|closed)#apcard$/);
|
||
} finally { srv.close(); }
|
||
});
|