brendmanager/src/test-run.js

333 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// BRM-143: проверочный путь до закрытого тестового Telegram-канала.
// Стратегия утверждена → минутный таймер сервера (tick) → проверки доступа → карточка Татьяне в личный чат
// → «Одобрить» для этой версии (текст, материалы, канал, время) → одна отправка через общий публикатор
// только в подтверждённый закрытый канал → ссылка владельцу, номер сообщения и время в журнале.
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { t } from "./i18n.js";
import { almatyTime } from "./deploy-status.js";
import { decide, submit, publish as markPublished } from "./approval.js";
import { publicStatus } from "./facts.js";
import { DECIDER } from "./strategy.js";
export const CHANNEL = "telegram-test"; // отдельный канал публикатора: пишет только в подтверждённый chat id
export const OFFSET_MS = 5 * 3600e3; // Алматы, UTC+5
export const SLOT = "12:00"; // время публикации по Алматы
export const DEADLINE = "21:00"; // срок ответа на карточку по Алматы; позже — считается отказом
export const MIN_LEAD_MS = 10 * 60e3; // публикация не раньше чем через 10 минут после карточки
const LOG_MAX = 200;
// Боты, которые нельзя использовать для согласований (PM, вопрос #1686): бот стажировок.
export const FORBIDDEN_BOTS = ["nternships_bot"];
export const NEED_UPDATES = ["message", "callback_query", "my_chat_member"]; // что должен получать вебхук бота
// Кто снимает причину: pm — PM в настройках проекта, tatiana — владелец в Telegram или на сайте, agent — агент сам.
export const WHO = {
"key.missing": "pm", "key.bad": "pm", "key.wrongBot": "pm", "webhook.none": "pm", "webhook.updates": "pm", "owner.unbound": "tatiana", "channel.none": "tatiana", "channel.gone": "tatiana",
"channel.public": "tatiana", "channel.type": "tatiana", "rights.post": "tatiana", "channel.changed": "tatiana",
"text.empty": "tatiana", "fact": "tatiana", "asset.rights": "tatiana", "asset.kind": "tatiana",
"send.stopped": "tatiana", "send.limit": "agent", "send.rules": "agent", "send.error": "pm",
};
const problem = (code, detail) => ({ code, who: WHO[code] ?? "agent", ...(detail ? { detail: String(detail) } : {}) });
const sha = (s) => crypto.createHash("sha256").update(s).digest("hex");
const local = (ms) => new Date(ms + OFFSET_MS).toISOString(); // «местное» ISO: дата и время по Алматы
const atLocal = (date, hm) => Date.parse(`${date}T${hm}:00Z`) - OFFSET_MS;
// Ссылка на сообщение закрытого канала: t.me/c/<id без -100>/<номер>.
export const messageLink = (chatId, messageId) => `https://t.me/c/${String(chatId).replace(/^-100/, "").replace(/^-/, "")}/${messageId}`;
// pub — функция, возвращающая публикатор (он создаётся после проверочного пути, потому что принимает его adapter).
export function createTestRun({ file, telegram, getOwnerChat, getPlan, savePlan = () => {}, facts, assets, strategy, pub, lang = "ru" }) {
let st;
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = {}; }
st.armedAt ??= null; st.channel ??= null; st.offered ??= null; st.cards ??= []; st.log ??= []; st.nextId ??= 1;
st.blocks ??= {}; st.lastCheck ??= null;
const save = () => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file + ".tmp", JSON.stringify(st, null, 2)); fs.renameSync(file + ".tmp", file); };
const L = (k, v) => t(lang, "tr." + k, v);
const scrub = (s) => telegram.secrets().reduce((a, x) => a.split(x).join("***"), String(s ?? ""));
const iso = (ms) => new Date(ms).toISOString();
function log(kind, at, extra = {}) {
const e = JSON.parse(scrub(JSON.stringify({ at: iso(at), kind, test: true, ...extra })));
st.log.push(e); if (st.log.length > LOG_MAX) st.log.splice(0, st.log.length - LOG_MAX);
save(); return e;
}
const api = (m, p, f) => telegram.api(m, p, f);
const toOwner = async (text, buttons) => {
const chat = getOwnerChat();
if (chat == null || !telegram.secrets().length) return null;
return api("sendMessage", { chat_id: chat, text, ...(buttons ? { reply_markup: { inline_keyboard: buttons } } : {}) });
};
// Причина простыми словами: что мешает. Кто снимает. Что сделать.
const why = (p) => `${L("why." + p.code, { detail: p.detail ?? "" }).replace(" ()", "")}. ${L("who." + p.who)}. ${L("do." + p.code)}`;
// Проверки доступа: ключ бота, привязка владельца, тестовый канал (закрыт, это канал), права бота.
async function diagnose(now = Date.now()) {
const problems = [];
let me = null, chat = null;
if (!telegram.secrets().length) problems.push(problem("key.missing"));
else {
const r = await api("getMe", {});
if (!r?.ok) problems.push(problem("key.bad", r?.description));
else if (FORBIDDEN_BOTS.includes(String(r.result.username ?? "").toLowerCase())) problems.push(problem("key.wrongBot", "@" + r.result.username));
else {
me = r.result;
// Без вебхука с callback_query и my_chat_member кнопки карточки и добавление в канал до сервера не дойдут.
const w = await api("getWebhookInfo", {});
if (w?.ok && !w.result.url) problems.push(problem("webhook.none"));
else if (w?.ok) { const need = NEED_UPDATES.filter((u) => (w.result.allowed_updates ?? []).length && !w.result.allowed_updates.includes(u)); if (need.length) problems.push(problem("webhook.updates", need.join(", "))); }
}
}
if (getOwnerChat() == null) problems.push(problem("owner.unbound"));
if (me) {
if (!st.channel) problems.push(problem("channel.none"));
else {
const c = await api("getChat", { chat_id: st.channel.chatId });
if (!c?.ok) problems.push(problem("channel.gone", c?.description));
else {
chat = c.result;
if (chat.username) problems.push(problem("channel.public", "@" + chat.username));
else if (chat.type !== "channel") problems.push(problem("channel.type", chat.type));
const m = await api("getChatMember", { chat_id: st.channel.chatId, user_id: me.id });
const can = m?.ok && (m.result.status === "creator" || (m.result.status === "administrator" && m.result.can_post_messages === true));
if (!can) problems.push(problem("rights.post", m?.ok ? m.result.status : m?.description));
}
}
}
st.lastCheck = { at: iso(now), ok: problems.length === 0, problems };
save();
return { ok: problems.length === 0, problems, me, chat };
}
// Блокировка: в журнал и владельцу один раз, пока набор причин не поменялся.
async function block(problems, now, extra = {}) {
const k = String(extra.ideaId ?? (extra.card != null ? "card" + extra.card : "access"));
const sig = JSON.stringify(problems.map((p) => p.code + ":" + (p.detail ?? "")));
if (st.blocks[k] === sig) return null;
st.blocks[k] = sig;
const e = log("blocked", now, { problems, ...extra });
if (!problems.some((p) => p.code.startsWith("key.") || p.code === "owner.unbound"))
await toOwner(L("msg.blocked") + "\n" + problems.map((p) => "• " + why(p)).join("\n")).catch(() => null);
return e;
}
// Материал записи: текст публикации, материалы, что мешает.
function material(idea) {
const problems = [];
const att = assets ? assets.forIdea(idea.id) : [];
const body = [String(idea.title ?? "").trim(), String(idea.description ?? "").trim()].filter(Boolean).join("\n\n");
if (!body) problems.push(problem("text.empty"));
for (const key of idea.facts ?? []) {
const f = facts?.get(key);
if (!f) problems.push(problem("fact", key));
else { const s = publicStatus(f); if (!s.ok) problems.push(problem("fact", `${f.title}: ${s.why.join(", ")}`)); }
}
for (const a of att) {
if (a.rights !== "yes") problems.push(problem("asset.rights", a.title));
if (a.kind === "text") problems.push(problem("asset.kind", a.title));
}
const links = att.filter((a) => a.kind === "link" || a.kind === "video").map((a) => a.url);
const photos = att.filter((a) => a.kind === "image").map((a) => ({ id: a.id, title: a.title, url: a.url ?? null }));
const post = [L("post.mark") + " " + body, ...links].join("\n");
return { post, attachments: att.map((a) => ({ id: a.id, title: a.title, kind: a.kind, url: a.url ?? null })), photos, problems };
}
const contentKey = (m, chatId) => sha(JSON.stringify([m.post, m.attachments, String(chatId)]));
const cardHash = (ck, publishAt) => sha(ck + "\n" + publishAt);
function cardText(c) {
const mats = c.attachments.length ? c.attachments.map((a) => `«${a.title}»`).join(", ") : L("card.noAssets");
return [L("card.head"), "", L("card.text") + ":", c.post, "", L("card.assets") + ": " + mats,
L("card.channel", { title: c.chat.title }), L("card.time", { time: almatyTime(c.publishAt) }),
L("card.deadline", { time: almatyTime(c.expiresAt) }), "", L("card.bound")].join("\n");
}
const buttons = (c) => [["approve", "rework", "reject"].map((a) => ({ text: L("btn." + a), callback_data: `tr:${a}:${c.id}:${c.hash.slice(0, 8)}` }))];
const ideaOf = (c) => getPlan().ideas.find((i) => i.id === c.ideaId);
const returnIdea = (idea, comment, at) => {
if (idea?.status === "review") { idea.approver = DECIDER; decide(idea, { action: "return", comment, by: DECIDER }, at); savePlan(); }
};
async function prepare(now) {
const today = local(now).slice(0, 10);
const ideas = getPlan().ideas.filter((i) => i.date && i.date <= today && ["draft", "review"].includes(i.status))
.sort((a, b) => a.date.localeCompare(b.date) || a.id - b.id);
let d = null;
for (const idea of ideas) {
const m = material(idea);
const ck = st.channel ? contentKey(m, st.channel.chatId) : null;
if (ck && st.cards.some((c) => c.ideaId === idea.id && c.contentKey === ck)) continue; // на эту версию карточка уже была
d ??= await diagnose(now);
if (!d.ok) return block(d.problems, now);
delete st.blocks.access;
if (m.problems.length) { await block(m.problems, now, { ideaId: idea.id }); continue; }
const publishAt = Math.max(atLocal(idea.date, SLOT), now + MIN_LEAD_MS);
const expiresAt = Math.max(atLocal(local(publishAt).slice(0, 10), DEADLINE), publishAt + 2 * 3600e3);
const c = {
id: st.nextId++, ideaId: idea.id, test: true, status: "waiting", createdAt: iso(now), trigger: "schedule",
post: m.post, attachments: m.attachments, photos: m.photos, chat: { chatId: st.channel.chatId, title: d.chat.title ?? st.channel.title },
publishAt: iso(publishAt), expiresAt: iso(expiresAt), contentKey: ck, hash: cardHash(ck, iso(publishAt)),
};
const r = await toOwner(cardText(c), buttons(c));
if (!r?.ok) return block([problem("owner.unbound", r?.description)], now);
c.ownerMessageId = r.result.message_id;
st.cards.push(c); delete st.blocks[String(idea.id)];
if (idea.status === "draft") submit(idea, { approver: DECIDER, by: "agent" }, iso(now)); else idea.approver = DECIDER;
savePlan();
log("card", now, { card: c.id, ideaId: idea.id, trigger: "schedule", publishAt: c.publishAt, expiresAt: c.expiresAt });
return c;
}
return null;
}
// Канал публикатора: отправляет только в подтверждённый закрытый канал.
let lastSent = null;
const adapter = {
channel: CHANNEL,
secrets: () => telegram.secrets(),
connected: () => Boolean(st.channel) && telegram.secrets().length > 0,
missing: () => (!telegram.secrets().length ? "key" : !st.channel ? "chat" : null),
defaultLimits: () => [{ limit: 3, periodMs: 24 * 3600e3 }],
async send(text) {
if (!st.channel) throw new Error("нет тестового канала");
const r = await api("sendMessage", { chat_id: st.channel.chatId, text });
if (!r?.ok) throw new Error(r?.description ?? "ошибка Telegram");
lastSent = r.result;
return { message_id: r.result.message_id, url: messageLink(st.channel.chatId, r.result.message_id) };
},
};
async function sendCard(c, now) {
const idea = ideaOf(c);
const d = await diagnose(now);
if (!d.ok) { await block(d.problems, now, { card: c.id }); return null; }
if (String(st.channel.chatId) !== String(c.chat.chatId)) { await block([problem("channel.changed")], now, { card: c.id }); return null; }
const m = idea ? material(idea) : null;
if (!m || cardHash(contentKey(m, c.chat.chatId), c.publishAt) !== c.hash) return stale(c, now);
if (pub().status().channels[CHANNEL]?.stopped) { await block([problem("send.stopped")], now, { card: c.id }); return null; }
lastSent = null;
const e = await pub().publish({ channel: CHANNEL, text: c.post, approvedBy: "tatiana", key: `test-card:${c.id}:${c.hash}` });
if (e.result !== "published") {
const code = e.reason === "stopped" ? "send.stopped" : e.reason === "limit" ? "send.limit" : e.result === "error" ? "send.error" : "send.rules";
c.status = e.reason === "stopped" || e.reason === "limit" ? "approved" : "failed"; c.reason = e.reason;
if (e.retryAt) c.retryAt = e.retryAt;
save();
await block([problem(code, e.retryAt ? almatyTime(e.retryAt) : e.reason)], now, { card: c.id });
return null;
}
const messageId = lastSent?.message_id ?? Number(String(e.ref ?? "").replace(/\D/g, ""));
const link = messageLink(c.chat.chatId, messageId);
const photoIds = [];
for (const ph of c.photos ?? []) {
const f = ph.url ? null : assets?.readFile(ph.id);
const r = await api("sendPhoto", { chat_id: c.chat.chatId, caption: L("post.mark") + " " + ph.title, reply_to_message_id: messageId, ...(ph.url ? { photo: ph.url } : {}) },
f ? { field: "photo", buf: f.buf, mime: f.mime, name: `asset-${ph.id}` } : undefined);
if (r?.ok) photoIds.push(r.result.message_id); else log("failed", now, { card: c.id, what: "photo", reason: scrub(r?.description) });
}
Object.assign(c, { status: "sent", messageId, photoIds, sentAt: e.time, link }); delete st.blocks["card" + c.id]; save();
if (idea && (idea.status === "approved")) {
const r = markPublished(idea, getPlan().publications, { channel: "telegram", date: local(Date.parse(e.time)).slice(0, 10), by: DECIDER }, e.time);
if (r.publication) Object.assign(r.publication, { test: true, link, messageId });
savePlan();
}
log("sent", now, { card: c.id, ideaId: c.ideaId, messageId, sentAt: e.time, link, channel: c.chat.title });
await toOwner(L("msg.sent", { title: c.chat.title, link, time: almatyTime(e.time) })).catch(() => null);
return c;
}
function stale(c, now) {
c.status = "stale"; save();
log("stale", now, { card: c.id, ideaId: c.ideaId });
return null;
}
// Кнопка карточки: ответ владельцу (текст). Без «Одобрить» ничего не отправляется.
async function onButton(action, cardId, h8, now = Date.now()) {
const c = st.cards.find((x) => x.id === Number(cardId));
if (!c) return L("btn.notFound");
if (c.status !== "waiting") return L("btn.closed", { state: L("state." + c.status) });
if (now > Date.parse(c.expiresAt)) { expire(c, now); return L("btn.expired"); }
const idea = ideaOf(c);
if (action === "rework" || action === "reject") {
c.status = action === "rework" ? "rework" : "rejected"; c.decidedAt = iso(now); save();
returnIdea(idea, L(action === "rework" ? "comment.rework" : "comment.reject"), iso(now));
log(c.status, now, { card: c.id, ideaId: c.ideaId });
return L("btn.done." + action);
}
if (action !== "approve") return L("btn.notFound");
const m = idea ? material(idea) : null;
if (h8 !== c.hash.slice(0, 8) || !m || !st.channel || cardHash(contentKey(m, st.channel.chatId), c.publishAt) !== c.hash) { stale(c, now); return L("btn.stale"); }
c.status = "approved"; c.approvedAt = iso(now); save();
strategy.grant({ text: c.post, by: DECIDER }, iso(now)); // согласие Татьяны ровно на этот текст
if (idea?.status === "review") { idea.approver = DECIDER; decide(idea, { action: "approve", by: DECIDER }, iso(now)); savePlan(); }
log("approved", now, { card: c.id, ideaId: c.ideaId, publishAt: c.publishAt });
if (now >= Date.parse(c.publishAt)) { const r = await sendCard(c, now); return r ? L("btn.done.sentNow") : L("btn.done.held"); }
return L("btn.done.approve", { time: almatyTime(c.publishAt) });
}
function expire(c, now) {
c.status = "expired"; save();
returnIdea(ideaOf(c), L("comment.expired"), iso(now));
log("expired", now, { card: c.id, ideaId: c.ideaId });
}
// Бота добавили в канал: предложить владельцу подтвердить его как закрытый тестовый.
async function offerChannel(chat, now = Date.now()) {
if (st.channel && String(st.channel.chatId) === String(chat.id)) return null;
if (chat.username || chat.type !== "channel") {
log("channel-refused", now, { title: chat.title ?? "", reason: chat.username ? "public" : chat.type });
return toOwner(L(chat.username ? "ch.public" : "ch.type", { title: chat.title ?? "" }));
}
st.offered = { chatId: chat.id, title: chat.title ?? "", at: iso(now) }; save();
log("channel-offered", now, { title: st.offered.title });
return toOwner(L("ch.offer", { title: st.offered.title }), [[{ text: L("ch.yes"), callback_data: `tc:yes:${chat.id}` }]]);
}
async function confirmChannel(chatId, now = Date.now()) {
if (!st.offered || String(st.offered.chatId) !== String(chatId)) return L("btn.notFound");
const c = await api("getChat", { chat_id: chatId });
if (!c?.ok) return L("why.channel.gone", { detail: scrub(c?.description) });
if (c.result.username || c.result.type !== "channel") return L(c.result.username ? "ch.public" : "ch.type", { title: c.result.title ?? "" });
st.channel = { chatId: c.result.id, title: c.result.title ?? st.offered.title, confirmedAt: iso(now), by: DECIDER };
st.offered = null; st.blocks = {}; save();
strategy.setRule({ kind: "channel", key: CHANNEL, mode: "each" }); // каждая публикация — только с одобрением
log("channel-confirmed", now, { title: st.channel.title });
return L("ch.done", { title: st.channel.title });
}
function arm(now = Date.now()) {
if (st.armedAt) return false;
st.armedAt = iso(now); log("armed", now, { trigger: "strategy-approved" });
return true;
}
// Раз в минуту из таймера сервера.
async function tick(now = Date.now()) {
if (!strategy.isApproved()) return { skipped: "strategy" };
arm(now);
for (const c of st.cards.filter((x) => x.status === "waiting" && now > Date.parse(x.expiresAt))) expire(c, now);
for (const c of st.cards.filter((x) => x.status === "approved" && now >= Date.parse(x.publishAt) && !(x.retryAt && now < Date.parse(x.retryAt)))) await sendCard(c, now);
const card = await prepare(now);
return { card };
}
// BRM-147: когда по расписанию следующая проверочная публикация: карточка ждёт/одобрена — её время,
// иначе ближайшая запись плана (черновик или на согласовании) в SLOT по Алматы.
// BRM-157: ближайший запуск считаем только при утверждённой стратегии (иначе tick ничего не делает).
function next(now = Date.now()) {
if (!strategy.isApproved()) return null;
const open = st.cards.filter((c) => ["waiting", "approved"].includes(c.status)).sort((a, b) => a.publishAt.localeCompare(b.publishAt))[0];
if (open) return { at: open.publishAt, card: open.id };
const today = local(now).slice(0, 10);
const idea = (getPlan().ideas ?? []).filter((i) => i.date && ["draft", "review"].includes(i.status) && !st.cards.some((c) => c.ideaId === i.id && (c.date == null || c.date === i.date)))
.sort((a, b) => a.date.localeCompare(b.date) || a.id - b.id)[0];
if (!idea) return null;
return { at: iso(Math.max(atLocal(idea.date < today ? today : idea.date, SLOT), now + MIN_LEAD_MS)), ideaId: idea.id };
}
const view = (now = Date.now()) => JSON.parse(scrub(JSON.stringify({
armedAt: st.armedAt, approved: strategy.isApproved(), channel: st.channel, lastCheck: st.lastCheck, next: next(now), sentCount: st.cards.filter((c) => c.status === "sent").length,
cards: st.cards.slice(-10).reverse().map(({ contentKey, ...c }) => ({ ...c, hash: c.hash.slice(0, 8) })),
log: st.log.slice(-50).reverse(),
})));
return { tick, arm, diagnose, onButton, offerChannel, confirmChannel, adapter, view, cardText, why, channel: () => st.channel, offered: () => st.offered };
}