brendmanager/src/strategy-card.js

311 lines
20 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-165: карточка стратегии в личном Telegram Татьяны, до трёх вопросов и запросы её решений.
// Отправляет только версия, которая получает сообщения бота (enabled = задан адрес для входящих сообщений):
// кнопки приходят только туда, и Татьяна не получает дублей от других версий.
// За Татьяну ничего не решаем: стадия меняется только по её кнопкам из её чата. В публичные каналы ничего не уходит.
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 { DECIDER, SECTIONS } from "./strategy.js";
export const MAX_QUESTIONS = 3;
export const RETRY_MS = 10 * 60e3; // после неудачной доставки — повтор не чаще раза в 10 минут
const MAX_TEXT = 3900; // предел сообщения Telegram — 4096 знаков
// Кто снимает причину: pm — команда, tatiana — владелица, agent — агент сам.
export const WHO = { "key.missing": "pm", "owner.unbound": "tatiana", "send.error": "pm", "send.blocked": "tatiana" };
const esc = (s) => String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export const versionHash = (v) => crypto.createHash("sha256").update(JSON.stringify(SECTIONS.map((s) => v.sections[s] ?? ""))).digest("hex");
export const LOG_MAX = 30;
export function createStrategyCard({ file, telegram, strategy, getOwnerChat, testRun = null, enabled = false, siteUrl = "", questions = [], topics = [], lang = "ru" }) {
let st;
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = {}; }
st.deliveries ??= []; st.attempt ??= null; st.questions ??= []; st.requests ??= {}; st.awaitingComment ??= null; st.decisions ??= []; st.log ??= []; st.topic ??= null;
for (const q of questions.slice(0, MAX_QUESTIONS)) if (!st.questions.some((x) => x.id === q.id)) st.questions.push({ ...q, askedAt: null, answer: null, answeredAt: 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, "sv." + k, v);
const iso = (ms) => new Date(ms).toISOString();
const scrub = (s) => telegram.secrets().reduce((a, x) => a.split(x).join("***"), String(s ?? ""));
const site = String(siteUrl ?? "").replace(/\/$/, "");
const delivery = (v) => v && st.deliveries.find((d) => d.n === v.n && d.hash === versionHash(v));
const complete = (v) => SECTIONS.every((s) => String(v.sections[s] ?? "").trim());
function problemsNow() {
const p = [];
if (!telegram.secrets().length) p.push({ code: "key.missing" });
if (getOwnerChat() == null) p.push({ code: "owner.unbound" });
return p;
}
const fail = (r) => {
const detail = scrub(r?.description ?? "");
return { code: /blocked|deactivated|chat not found/i.test(detail) ? "send.blocked" : "send.error", detail };
};
// BRM-190: журнал доставки карточки — строка на каждую смену результата, у повторов обновляется lastAt.
function journal(n, ok, problems, now, extra = {}) {
const codes = problems.map((p) => p.code);
const last = st.log.at(-1);
if (last && last.n === n && last.ok === ok && !extra.delivered && !last.delivered && JSON.stringify(last.codes) === JSON.stringify(codes)) { last.lastAt = iso(now); return; }
st.log.push({ at: iso(now), lastAt: iso(now), n, ok, codes, ...extra });
if (st.log.length > LOG_MAX) st.log.splice(0, st.log.length - LOG_MAX);
}
function record(ok, problems, now, n = null) {
st.attempt = { at: iso(now), ok, problems: problems.map((p) => ({ ...p, who: WHO[p.code] ?? "agent" })) };
if (n != null && !ok) journal(n, ok, problems, now);
save();
}
const toOwner = (text, buttons) => telegram.api("sendMessage", { chat_id: getOwnerChat(), text: scrub(text), ...(buttons ? { reply_markup: { inline_keyboard: buttons } } : {}) });
function cardText(v) {
const first = (s) => String(v.sections[s] ?? "").split("\n")[0];
const alts = String(v.sections.alternatives ?? "").split("\n").filter(Boolean).map((l) => "• " + l.split(":")[0]);
const lines = [
L("card.head", { n: v.n }), "",
L("card.main") + ": " + v.sections.main, "",
L("card.alts") + ":", ...alts, "",
L("card.kpi") + ":", v.sections.kpi, "",
L("card.budget") + ": " + first("budget"), "",
L("card.plan"), ...(site ? ["", L("card.link", { link: site + "/strategy.html" })] : []), "",
L("card.ask"),
];
const text = lines.join("\n").replaceAll("уточнить у Татьяны", L("card.askYou")); // карточку читает сама Татьяна
return text.length > MAX_TEXT ? text.slice(0, MAX_TEXT - 1) + "…" : text;
}
const cardButtons = (v) => [["approve", "rework"].map((a) => ({ text: L("btn." + a), callback_data: `sv:${a}:${v.n}:${versionHash(v).slice(0, 8)}` }))];
async function deliver(v, now) {
const problems = problemsNow();
if (problems.length) return record(false, problems, now, v.n);
const r = await toOwner(cardText(v), cardButtons(v));
if (!r?.ok) return record(false, [fail(r)], now, v.n);
st.deliveries.push({ n: v.n, hash: versionHash(v), at: iso(now), messageId: r.result.message_id });
journal(v.n, true, [], now, { delivered: true });
record(true, [], now);
}
// Вопросы и запросы — после карточки, по одному сообщению; каждый задаётся один раз.
async function ask(now) {
for (const q of st.questions.filter((x) => !x.askedAt)) {
const r = await toOwner(L("q.text", { text: q.text, why: q.why }), q.options.map((o, i) => [{ text: o, callback_data: `sq:${q.id}:${i}` }]));
if (!r?.ok) return record(false, [fail(r)], now);
q.askedAt = iso(now); save();
}
if (!testRun?.channel() && !st.requests.channel) {
const off = testRun?.offered?.();
const r = await toOwner(off ? L("req.channelOffered", { title: off.title }) : L("req.channel"), off ? [[{ text: L("req.channelYes"), callback_data: `tc:yes:${off.chatId}` }]] : undefined);
if (!r?.ok) return record(false, [fail(r)], now);
st.requests.channel = { askedAt: iso(now) }; save();
}
if (!st.requests.summary) {
const r = await toOwner(L("req.summary"), [[{ text: L("req.summaryHere"), callback_data: "ss:here" }, { text: L("req.summaryOther"), callback_data: "ss:other" }]]);
if (!r?.ok) return record(false, [fail(r)], now);
st.requests.summary = { askedAt: iso(now), answer: null, at: null }; save();
}
const v = strategy.current(); // всё дошло: прошлая причина больше не мешает
if (st.attempt && !st.attempt.ok && (!v || v.status !== "draft" || delivery(v))) record(true, [], now);
}
// BRM-190: тема первого поста — после утверждения, один раз; «Другую тему» — следующая из списка.
// Только сообщение Татьяне: публикация не создаётся и в каналы ничего не уходит.
const topicButtons = (i) => [[{ text: L("topic.ok"), callback_data: `st:ok:${i}` }, { text: L("topic.other"), callback_data: `st:other:${i}` }]];
async function sendTopic(i, now) {
const x = topics[i];
const r = await toOwner(L("topic.msg", { n: i + 1, of: topics.length, text: x.text, why: x.why }), topicButtons(i));
if (!r?.ok) { record(false, [fail(r)], now); return false; }
st.topic = { n: strategy.current()?.n ?? null, i, sentAt: iso(now), answer: null, answeredAt: null, tried: [...(st.topic?.tried ?? []), i] };
save(); return true;
}
// Раз в минуту из таймера сервера.
async function tick(now = Date.now()) {
if (!enabled) return { skipped: "elsewhere" };
const v = strategy.current();
if (!v) return { skipped: "none" };
if (st.attempt && !st.attempt.ok && now - Date.parse(st.attempt.at) < RETRY_MS && getOwnerChat() != null && telegram.secrets().length) return { skipped: "retry" };
if (v.status === "draft" && complete(v) && !delivery(v)) await deliver(v, now);
if (st.deliveries.length && getOwnerChat() != null && telegram.secrets().length) await ask(now);
if (v.status === "approved" && topics.length && !st.topic && getOwnerChat() != null && telegram.secrets().length) await sendTopic(0, now);
return { ok: true };
}
// Кнопки из чата владелицы (бот пропускает только её). Возвращает ответ бота.
async function onButton(kind, parts, now = Date.now()) {
if (kind === "sv") {
const [action, n, h8] = parts;
const v = strategy.current();
if (!v || String(v.n) !== String(n) || versionHash(v).slice(0, 8) !== h8) return L("reply.stale");
if (v.status === "approved") return L("reply.already", { time: almatyTime(v.approvedAt) });
if (action === "approve") {
const r = strategy.decide({ action: "approve", by: DECIDER }, iso(now));
if (r.err) return L("reply.incomplete");
testRun?.arm(now);
st.decisions.push({ n: v.n, action, at: iso(now) }); st.awaitingComment = null; save();
return L("reply.approved", { n: v.n, time: almatyTime(iso(now)) });
}
if (action === "rework") {
if (v.status !== "revision") strategy.decide({ action: "return", comment: L("comment.button"), by: DECIDER }, iso(now));
st.decisions.push({ n: v.n, action, at: iso(now) }); st.awaitingComment = v.n; save();
return L("reply.rework");
}
return L("reply.stale");
}
if (kind === "sq") {
const [id, i] = parts;
const q = st.questions.find((x) => x.id === id);
const answer = q?.options[Number(i)];
if (!q || answer == null) return L("reply.stale");
Object.assign(q, { answer, answeredAt: iso(now) }); save();
if (strategy.current()) strategy.comment({ text: L("q.comment", { text: q.text, answer }), by: DECIDER }, iso(now));
return L("q.thanks", { answer });
}
if (kind === "st") {
const [answer, i] = parts;
if (!st.topic || st.topic.answer || String(st.topic.i) !== String(i) || !["ok", "other"].includes(answer)) return L("reply.stale");
if (answer === "ok") { Object.assign(st.topic, { answer: "ok", answeredAt: iso(now) }); save(); return L("topic.done.ok", { text: topics[st.topic.i].text }); }
const next = st.topic.i + 1;
if (next < topics.length && getOwnerChat() != null) { if (await sendTopic(next, now)) return L("topic.done.next"); return L("reply.stale"); }
Object.assign(st.topic, { answer: "other", answeredAt: iso(now) }); save();
return L("topic.done.none");
}
if (kind === "ss") {
const answer = parts[0] === "here" ? "here" : "other";
st.requests.summary = { ...(st.requests.summary ?? { askedAt: iso(now) }), answer, at: iso(now) }; save();
return L("req.summaryDone." + answer);
}
return L("reply.stale");
}
// Текст после «На доработку» — замечание к версии. null — текст не для стратегии.
function takeText(text, now = Date.now()) {
if (st.awaitingComment == null || !String(text ?? "").trim()) return null;
const n = st.awaitingComment;
st.awaitingComment = null; save();
const r = strategy.comment({ text, by: DECIDER }, iso(now));
// BRM-170: замечание — к последнему «На доработку» этой версии, отдельно от служебной пометки и ответов.
const d = st.decisions.findLast((x) => x.n === n && x.action === "rework");
if (!r.err && d) { d.remark = { text: String(text).trim(), at: iso(now) }; save(); }
return r.err ? null : L("comment.saved");
}
function stage(v) {
if (!v) return "none";
if (v.status === "approved") return (testRun?.view().sentCount ?? 0) > 0 ? "launched" : "approved";
if (v.status === "revision") return "revision";
return delivery(v) ? "waiting" : "draft";
}
// BRM-170: последнее решение Татьяны по текущей версии (кнопка, время, замечание).
const lastDecision = (v) => {
const d = v && st.decisions.findLast((x) => x.n === v.n);
return d ? { n: d.n, action: d.action, at: d.at, remark: d.remark ?? null } : null;
};
const view = () => {
const v = strategy.current();
const d = delivery(v);
const ch = testRun?.channel() ?? null;
return JSON.parse(scrub(JSON.stringify({
enabled, stage: stage(v), n: v?.n ?? null, approvedAt: v?.approvedAt ?? null,
delivered: d ? { at: d.at } : null, attempt: st.attempt,
questions: st.questions.map(({ id, text, why, options, askedAt, answer, answeredAt }) => ({ id, text, why, options, askedAt, answer, answeredAt })),
channel: ch ? { state: "confirmed", title: ch.title, at: ch.confirmedAt } : { state: st.requests.channel ? "waiting" : "notAsked" },
summary: st.requests.summary?.answer ? { state: st.requests.summary.answer, at: st.requests.summary.at } : { state: st.requests.summary ? "waiting" : "notAsked" },
awaitingComment: st.awaitingComment,
decision: lastDecision(v),
// BRM-190: журнал доставки (новые сверху) и тема первого поста.
log: st.log.slice().reverse(),
topic: st.topic ? { ...st.topic, text: topics[st.topic.i]?.text ?? "", why: topics[st.topic.i]?.why ?? "", state: st.topic.answer ?? "waiting" } : { state: v?.status === "approved" ? "soon" : "afterApprove" },
// BRM-189: были ли карточки вообще и что нужно для отправки (те же условия, что у tick).
sentEver: st.deliveries.length > 0,
needs: [
{ code: "version", ok: Boolean(v && complete(v)) },
{ code: "key", ok: telegram.secrets().length > 0 },
{ code: "owner", ok: getOwnerChat() != null },
{ code: "receiver", ok: enabled },
],
})));
};
return { tick, onButton, takeText, view, cardText, summaryChat: () => (st.requests.summary?.answer === "here" ? getOwnerChat() : null) };
}
// Блок #svcard на «Стратегия и правила»: собирает сервер, видно до скриптов.
export function strategyBox(lang, sv, version, elsewhereUrl = null) {
const T = (k, v) => esc(t(lang, "sv." + k, v));
const at = (iso) => esc(almatyTime(iso)) + " " + T("almaty");
const out = [`<section id="svcard">`, `<h2>${T("h")}</h2>`];
// BRM-189: пока карточку не доставили — что нужно для отправки.
const needBox = () => {
const needs = sv.needs ?? [];
const lines = [];
if (!sv.sentEver) lines.push(`<p id="svnever"><b>${T("never")}</b></p>`);
lines.push(`<h3>${T("need.h")}</h3><ul id="svneed">`);
for (const x of needs) lines.push(`<li id="svneed-${esc(x.code)}" class="${x.ok ? "ok" : "need"}">${T("need." + x.code)}: <b>${T(x.ok ? "need.yes" : "need.no")}</b></li>`);
lines.push(`</ul>`);
if (needs.every((x) => x.ok)) lines.push(`<p class="hint">${T("need.allOk")}</p>`);
return lines.join("");
};
if (!version) { out.push(`<p id="svstage">${T("stage.none")}</p>`, needBox(), `</section>`); return out.join(""); }
const stageText = T("stage." + sv.stage) + (sv.stage === "approved" || sv.stage === "launched" ? " " + at(sv.approvedAt) : "");
out.push(`<p id="svstage" class="st-${esc(sv.stage)}">${T("version", { n: version.n })}: <b>${stageText}</b></p>`);
// BRM-189: шкала стадий, текущая отмечена; «на доработке» — только когда версия на доработке.
const track = ["draft", "waiting", ...(sv.stage === "revision" ? ["revision"] : []), "approved", "launched"];
out.push(`<ol id="svtrack" class="track">${track.map((x) => (x === sv.stage ? `<li class="cur" aria-current="step"><b>${T("track." + x)}</b> ${T("track.here")}</li>` : `<li>${T("track." + x)}</li>`)).join("")}</ol>`);
out.push(`<p class="hint">${T("stages")}</p>`);
if (sv.stage === "revision") out.push(`<p id="svnotapproved"><b>${T("notApproved")}</b></p>`);
// Доставка карточки — раньше решения: сначала дошла, потом нажата.
if (sv.delivered) out.push(`<p id="svdelivery">${T("delivered")}: ${at(sv.delivered.at)}</p>`);
else if (!sv.enabled) out.push(`<p id="svdelivery">${T("elsewhere")}${elsewhereUrl ? ` <a href="${esc(elsewhereUrl)}">${T("elsewhereLink")}</a>` : ""}</p>`);
else if (version.status === "draft") out.push(`<p id="svdelivery">${T("notYet")}</p>`);
if (!sv.delivered && version.status === "draft") out.push(needBox());
// BRM-170: что Татьяна нажала в карточке и её замечание.
const d = sv.decision;
if (d) {
out.push(`<p id="svdecision">${T("dec.pressed", { btn: T("btn." + d.action) })}: ${at(d.at)}</p>`);
if (d.action === "rework") out.push(d.remark ? `<p id="svremark">${T("dec.remark")}: «${esc(d.remark.text)}» (${at(d.remark.at)})</p>` : `<p id="svremark"><b>${T("dec.waitRemark")}</b></p>`);
} else if (sv.stage === "waiting") out.push(`<p id="svdecision">${T("dec.none")}</p>`);
if (sv.attempt && !sv.attempt.ok) {
out.push(`<p class="hint">${T("blockedAt")}: ${at(sv.attempt.at)}</p><ul id="svblock">`);
for (const p of sv.attempt.problems) out.push(`<li>${T("whatBlocks")}: ${T("why." + p.code, { detail: p.detail ?? "" }).replace(" ()", "")}. ${T("who." + p.who)}. ${T("do." + p.code)}</li>`);
out.push(`</ul>`);
}
// BRM-190: журнал доставки карточки.
out.push(`<h3>${T("log.h")}</h3>`);
const log = sv.log ?? [];
if (!log.length) out.push(`<p id="svlog">${T("log.none")}</p>`);
else {
out.push(`<ul id="svlog">`);
for (const e of log) {
const res = e.ok ? T("log.ok") : `${T("log.fail")} — ${e.codes.map((c) => T("why." + c, { detail: "" }).replace(" ()", "")).join("; ")}`;
const again = !e.ok && e.lastAt && e.lastAt !== e.at ? ` <span class="hint">(${T("log.lastAt")} ${at(e.lastAt)})</span>` : "";
out.push(`<li>${at(e.at)} — ${T("version", { n: e.n })}: ${res}${again}</li>`);
}
out.push(`</ul>`);
}
// BRM-190: идея первой публикации — после утверждения.
const tp = sv.topic ?? { state: "afterApprove" };
out.push(`<h3>${T("topic.h")}</h3><div id="svtopic">`);
if (tp.text) {
const state = tp.state === "ok" ? `<b>${T("topic.chosen")}</b> (${at(tp.answeredAt)})` : tp.state === "other" ? `<b>${T("topic.needOther")}</b> (${at(tp.answeredAt)})` : `<b>${T("waitOwner")}</b>`;
out.push(`<p>«${esc(tp.text)}» <span class="hint">${T("topic.why")}: ${esc(tp.why)}</span></p><p>${T("topic.sent")}: ${at(tp.sentAt)}. ${state}</p>`);
} else out.push(`<p>${T("topic." + tp.state)}</p>`);
out.push(`<p class="hint">${T("topic.only")}</p></div>`);
// Вопросы
out.push(`<h3>${T("qH")}</h3><ul id="svq">`);
for (const q of sv.questions) {
const state = q.answer ? `${T("q.answer")}: <b>${esc(q.answer)}</b> (${at(q.answeredAt)})` : q.askedAt ? `<b>${T("waitOwner")}</b>` : T("q.notAsked");
out.push(`<li>${esc(q.text)} <span class="hint">${T("q.why")}: ${esc(q.why)}</span><br>${state}</li>`);
}
out.push(`</ul>`);
// Решения владельца
const ch = sv.channel.state === "confirmed" ? `${T("req.chConfirmed", { title: sv.channel.title })} (${at(sv.channel.at)})` : sv.channel.state === "waiting" ? `<b>${T("waitOwner")}</b>` : T("req.notAsked");
const sm = sv.summary.state === "here" || sv.summary.state === "other" ? `${T("req.sm." + sv.summary.state)} (${at(sv.summary.at)})` : sv.summary.state === "waiting" ? `<b>${T("waitOwner")}</b>` : T("req.notAsked");
out.push(`<h3>${T("reqH")}</h3><ul id="svreq"><li id="svch">${T("req.ch")}: ${ch}</li><li id="svsum">${T("req.sm")}: ${sm}</li></ul>`);
out.push(`<p class="hint">${T("noPublic")}</p>`);
// Содержание версии — блок #strat (strategy-view.js, BRM-169).
out.push(`</section>`);
return out.join("");
}