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 { createStrategy, SECTIONS } from "../src/strategy.js"; import { createPublisher } from "../src/publisher.js"; import { createApp } from "../src/server.js"; const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "brm53-")); const full = (over = {}) => ({ ...Object.fromEntries(SECTIONS.map((s) => [s, "текст"])), plan90: "Пост 1\nПост 2", ...over }); const mk = () => createStrategy(path.join(tmp(), "s.json")); const NOW = "2026-11-17T10:00:00Z"; test("Сценарий: возврат с замечанием — версия на доработке, замечание видно агенту", () => { const s = mk(); s.edit(full(), "agent", NOW); assert.equal(s.decide({ action: "return", by: "Татьяна" }, NOW).err, "err.strategy.commentRequired"); assert.equal(s.current().status, "draft"); assert.ok(s.decide({ action: "return", comment: "Тон слишком строгий", by: "Татьяна" }, NOW).ok); assert.equal(s.current().status, "revision"); assert.equal(s.current().comments[0].text, "Тон слишком строгий"); }); test("Сценарий: утверждает только Татьяна и только полную версию", () => { const s = mk(); s.edit(full({ budget: "" }), "agent", NOW); assert.equal(s.decide({ action: "approve", by: "Команда" }, NOW).err, "err.strategy.notDecider"); const r = s.decide({ action: "approve", by: "Татьяна" }, NOW); assert.deepEqual(r.missing, ["budget"]); assert.equal(s.current().status, "draft"); }); test("Сценарий: утверждение создаёт задачи; правка утверждённой версии даёт новую версию-черновик", () => { const s = mk(); s.edit(full(), "agent", NOW); assert.ok(s.decide({ action: "approve", by: "Татьяна" }, NOW).ok); assert.deepEqual(s.tasks().map((t) => t.title), ["Пост 1", "Пост 2"]); assert.equal(s.isApproved(), true); s.edit({ tone: "новый" }, "agent", NOW); assert.equal(s.current().n, 2); assert.equal(s.current().status, "draft"); assert.equal(s.isApproved(), false); }); test("Сценарий: режимы — по умолчанию только черновик, действует самый строгий", () => { const s = mk(); s.edit(full(), "a", NOW); s.decide({ action: "approve", by: "Татьяна" }, NOW); assert.equal(s.gate({ channel: "telegram", text: "x" }), "mode-draft"); s.setRule({ kind: "channel", key: "telegram", mode: "auto" }); assert.equal(s.gate({ channel: "telegram", text: "x" }), null); s.setRule({ kind: "rubric", key: "1", mode: "each" }); assert.equal(s.gate({ channel: "telegram", rubric: 1, text: "x" }), "no-consent"); assert.equal(s.setRule({ kind: "action", key: "letter_as_owner", mode: "auto" }).err, "err.strategy.mustConsent"); assert.equal(s.setRule({ kind: "channel", key: "x", mode: "bad" }).err, "err.strategy.mode"); }); test("Сценарий: согласие привязано к тексту, правка сбрасывает; обязательные действия требуют согласия", () => { const s = mk(); s.edit(full(), "a", NOW); s.decide({ action: "approve", by: "Татьяна" }, NOW); s.setRule({ kind: "channel", key: "telegram", mode: "each" }); assert.equal(s.grant({ text: "Привет", by: "Команда" }, NOW).err, "err.strategy.notDecider"); assert.equal(s.gate({ channel: "telegram", text: "Привет" }), "no-consent"); s.grant({ text: "Привет", by: "Татьяна" }, NOW); assert.equal(s.gate({ channel: "telegram", text: "Привет" }), null); assert.equal(s.gate({ channel: "telegram", text: "Привет!" }), "no-consent"); s.setRule({ kind: "channel", key: "linkedin", mode: "auto" }); assert.equal(s.gate({ channel: "linkedin", action: "spend", text: "Реклама" }), "no-consent"); }); test("Сценарий: публикация до утверждения отклонена, внутренняя сводка проходит", async () => { const s = mk(); const ch = { secrets: () => [], connected: () => true, send: async () => ({}) }; const pub = createPublisher({ file: path.join(tmp(), "p.json"), channels: { telegram: ch }, gate: (r) => s.gate(r) }); const e = await pub.publish({ channel: "telegram", text: "Пост", approvedBy: "tatiana" }); assert.equal(e.reason, "strategy-not-approved"); assert.equal((await pub.publish({ channel: "telegram", text: "Сводка", approvedBy: "pm", internal: true })).result, "published"); }); test("API стратегии: правка, возврат, утверждение, режимы", async () => { const file = path.join(tmp(), "plan.json"); const srv = createApp({ file }).listen(0); await new Promise((r) => srv.once("listening", r)); const call = async (m, u, b) => { const r = await fetch(`http://127.0.0.1:${srv.address().port}${u}`, { method: m, headers: { "content-type": "application/json" }, body: b && JSON.stringify(b) }); return [r.status, await r.json()]; }; try { assert.equal((await call("POST", "/api/strategy/edit", { sections: { nope: "x" } }))[0], 400); assert.equal((await call("POST", "/api/strategy/edit", { sections: full() }))[0], 200); assert.equal((await call("POST", "/api/strategy/decision", { action: "approve", by: "Команда" }))[0], 403); assert.equal((await call("PUT", "/api/strategy/rules", { kind: "action", key: "price", mode: "auto" }))[0], 400); assert.equal((await call("POST", "/api/strategy/decision", { action: "approve", by: "Татьяна" }))[0], 200); const [, d] = await call("GET", "/api/strategy"); assert.equal(d.approved, true); assert.equal(d.tasks.length, 2); } finally { srv.close(); } });