brendmanager/src/strategy-card.js

230 lines
14 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 function createStrategyCard({ file, telegram, strategy, getOwnerChat, testRun = null, enabled = false, siteUrl = "", questions = [], 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 ??= [];
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 };
};
function record(ok, problems, now) {
st.attempt = { at: iso(now), ok, problems: problems.map((p) => ({ ...p, who: WHO[p.code] ?? "agent" })) };
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);
const r = await toOwner(cardText(v), cardButtons(v));
if (!r?.ok) return record(false, [fail(r)], now);
st.deliveries.push({ n: v.n, hash: versionHash(v), at: iso(now), messageId: r.result.message_id });
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);
}
// Раз в минуту из таймера сервера.
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);
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 === "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),
})));
};
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>`];
if (!version) { out.push(`<p id="svstage">${T("stage.none")}</p></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>`);
out.push(`<p class="hint">${T("stages")}</p>`);
// 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.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.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>`);
}
// Вопросы
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("");
}