// BRM-74: раздел «Бот и отчёты» — статус отправки, пауза, последние и следующие отчёты агента, ошибки отправки. // Страница целиком собирается сервером и работает без скриптов (кнопки — формы). import { t } from "./i18n.js"; import { almatyTime } from "./deploy-status.js"; import { localParts } from "./summary-schedule.js"; import { deployBox } from "./site.js"; import { sendLine, nowLines, whoOf } from "./bot.js"; const KINDS = ["day", "week"]; const MAX_ERRORS = 20; const esc = (s) => String(s).replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); // Когда по расписанию уйдёт следующий отчёт вида kind (ISO) или null, если вид выключен. export function nextRun(kind, settings, lastRun = {}, now = Date.now()) { const off = settings.tzOffsetHours * 3600e3; if (kind === "day" && !settings.daily.enabled) return null; const time = kind === "week" ? settings.weekly.time : settings.daily.time; for (let d = 0; d <= 14; d++) { const l = localParts(now + d * 864e5, settings.tzOffsetHours); const fits = kind === "week" ? l.dow === settings.weekly.day : l.dow !== settings.weekly.day; if (!fits || lastRun[kind] === l.date) continue; const at = Date.parse(`${l.date}T${time}:00Z`) - off; return new Date(Math.max(at, d === 0 ? now : at)).toISOString(); // сегодняшнее время прошло — уйдёт при ближайшей проверке } return null; } // Что отправлялось: по началу текста (тексты отчётов и сводок задаёт сам сервер). export function sentWhat(text = "") { if (text.startsWith("Отчёт агента за день")) return "day"; if (text.startsWith("Отчёт агента за неделю")) return "week"; if (text.startsWith("Сводка по бренду")) return "summary"; return "post"; } const whatOfJob = (j) => (j.key?.startsWith("report:") ? j.key.split(":")[1] : j.kind === "publish" ? sentWhat(j.payload?.text) : "post"); // Причина простыми словами по тексту ошибки задачи (тексты задаёт обработчик в agent.js и публикатор). export function causeOf(msg = "") { if (/нет доступ/.test(msg)) return "off"; if (/\(stopped\)/.test(msg)) return "paused"; if (/лимит/.test(msg)) return "limit"; if (/\(public-off\)/.test(msg)) return "publicOff"; // BRM-146 if (/\((strategy-not-approved|mode-draft|no-consent)\)/.test(msg)) return "rules"; return "failed"; } export function botView({ pub, jobs, metrics, telegram, testRun = null, now = Date.now() }) { const st = pub.status(); const paused = Object.values(st.channels).some((c) => c.stopped); const connected = telegram.connected(); const all = jobs.list(); const reports = Object.fromEntries(KINDS.map((kind) => { const job = all.filter((j) => j.key?.startsWith(`report:${kind}:`)).sort((a, b) => b.id - a.id)[0]; let last = null; if (job) { const state = job.status === "done" ? "published" : job.status === "failed" ? "failed" : "planned"; const at = state === "published" ? job.doneAt : state === "planned" ? job.nextAt ?? job.dueAt : job.doneAt ?? job.nextAt ?? job.dueAt; last = { state, at, atText: almatyTime(at), date: job.key.split(":")[2] }; } const n = nextRun(kind, metrics.settings(), metrics.lastRun(), now); return [kind, { last, next: n && { at: n, atText: almatyTime(n), state: "planned" } }]; })); // Ошибки: задачи очереди (отчёты и публикации по расписанию), которые не удались или ждут повтора, // и неудачные ручные отправки сводки из журнала публикатора. const jobErrors = all.filter((j) => j.lastError && (j.status === "failed" || j.status === "pending")) .map((j) => ({ at: j.doneAt ?? j.nextAt ?? j.dueAt, what: whatOfJob(j), cause: causeOf(j.lastError), reason: j.lastError, retryAt: j.status === "pending" ? j.nextAt : null })); const sendErrors = pub.log().filter((e) => e.result === "error" && sentWhat(e.text) === "summary") .map((e) => ({ at: e.time, what: "summary", cause: e.off ? "off" : "failed", reason: `${e.channel}: ${e.reason}`, retryAt: null })); const errors = [...jobErrors, ...sendErrors].sort((a, b) => (a.at < b.at ? 1 : -1)).slice(0, MAX_ERRORS) .map((e) => ({ ...e, atText: almatyTime(e.at), retryText: e.retryAt ? almatyTime(e.retryAt) : null })); // BRM-171: «включена» — только после подтверждённой доставки в чат сводок. const d = telegram.state?.() ?? null; return { sending: connected && !paused && (d ? d.confirmed : true), paused, connected, missing: telegram.missing?.() ?? null, reports, errors, testRun: testRun ? { ...testRun.view(now), why: testRun.why } : null }; } const p = (s) => `
${s}
`; const TEST_LOG = 15; const OLD_CARDS = 2; const CARD_ACTIONS = ["approve", "rework", "reject"]; const multiline = (s) => esc(s).replace(/\n/g, "${L("card.sent", { messageId: c.messageId, time: almatyTime(c.sentAt) })} ${L("card.open")}
` : `${L("card.nothing." + (c.status === "approved" ? (c.retryAt ? "retry" : "approved") : c.status === "waiting" ? "waiting" : "closed"), { time: almatyTime(c.retryAt ?? c.publishAt) })}
`; let form = ""; if (full && c.status === "waiting") { const off = wordSet ? "" : ' class="off" aria-disabled="true"'; const btns = CARD_ACTIONS.map((a) => ``).join(" "); form = ``; } const body = `${L("mark")} ${L("card.state")}: ${B("state." + c.status)}
${B("card.text")}:
${multiline(c.post)}
${B("card.assets")}: ${mats}
${B("card.channel", { title: c.chat?.title ?? "" })}
${B("card.time", { time: almatyTime(c.publishAt) })}
${c.status === "waiting" ? `${B("card.deadline", { time: almatyTime(c.expiresAt) })}
` : ""}${result}${form}`; return full ? `${L("mark")} ${approved ? L("card.none") : L("card.notApproved")}
${B("card.text")}: ${L("card.later")}
${B("card.assets")}: ${L("card.later")}
${channel}
${time}
${L("card.nothing.closed")}
${btns}
${L("card.offWhy")}
${L("notArmed")}
` : `${tr.armedAt ? `${L("armed", { time: almatyTime(tr.armedAt) })}
` : ""}${tr.next ? L("next", { time: almatyTime(tr.next.at) }) : L("noNext")}
`; const channel = tr.channel ? p(L("channel", { title: tr.channel.title, time: almatyTime(tr.channel.confirmedAt) })) : ""; const chk = tr.lastCheck; const check = !chk ? p(L("never")) : chk.ok ? `${L("ok", { time: almatyTime(chk.at) })}
` : `${L("blocked", { time: almatyTime(chk.at) })}
${L("mark")} ${L("logSent", { messageId: lastSent.messageId, time: almatyTime(lastSent.sentAt ?? lastSent.at), n: tr.sentCount ?? 1 })}${lastSent.link ? ` ${L("card.open")}` : ""}
` : `${L("mark")} ${L("logNone")}
`; const log = tr.log.length ? `${L("empty")}
`; const [last, ...older] = tr.cards ?? []; const msg = view.cardMsg ? `${L("card.msg." + view.cardMsg)}
` : ""; const cards = `${esc(t(lang, "botp.test.lead"))}
${L("mark")} ${L("count", { n: tr.sentCount ?? 0 })}
${cards}${N("openBot")} ${N(view.bound ? "openBotBound" : "openBotHint")}
`; } const why = where === "here" || where === "noBot" ? "noBot" : where === "none" ? "none" : "elsewhere"; return `${N("openBot")} ${N("openBotOff." + why)}
`; } // BRM-188: «Присылать сводки в мой личный чат с ботом» видна всегда, где принимаются команды; рядом — какой чат выбран. // home: форма с главной возвращает на главную. function pickBox(lang, view, q, home = false) { if (cmdWhere(view) !== "here") return ""; const N = (k, v) => esc(t(lang, "now." + k, v)); const d = view.delivery ?? { problem: null }; const code = d.problem?.code; const sm = view.card?.summary?.state; const chat = sm === "here" && !["chat", "other", "unbound", "key"].includes(code) ? "here" : code === "other" || sm === "other" ? "other" : ["chat", "unbound"].includes(code) ? "none" : code === "key" ? "none" : "set"; const line = `${N("chat." + chat)}
`; const off = !view.bound ? "unbound" : code === "key" ? "key" : null; const action = `/bot/summary-here${home ? `?from=home${lang !== "ru" ? "&lang=" + lang : ""}` : q}`; const btn = off ? `${N("pickOff." + off)}
` : `${N(chat === "here" ? "summaryHereAgain" : "summaryHereHint")}
`; return line + btn; } // BRM-171/180: «Бот сейчас» — те же строки, что бот отвечает на «Статус»: команды, привязка, отправка, решения. function nowBox(lang, view, q) { const N = (k, v) => esc(t(lang, "now." + k, v)); const where = cmdWhere(view); const there = where === "elsewhere" && view.receiverUrl ? ` ${N("open")}` : ""; const d = view.delivery ?? { problem: null }; const dc = view.dcMsg ? `${N("dc." + view.dcMsg)}
` : ""; const detail = d.problem?.detail ? `${N("checkHint")}
` : `${N("checkOff")}
`}`; return `${N("lead")}
${N("q.moving")}
`; if (cmdWhere(view) === "elsewhere") return `${head}${N("q.elsewhere")}${view.receiverUrl ? ` ${N("open")}` : ""}
`; const sv = view.card; if (!sv) return ""; const at = (iso) => esc(almatyTime(iso)); const wait = `${S("waitOwner")}`; const qs = sv.questions.slice(0, 3).map((x, i) => { const state = x.answer ? `${S("q.answer")}: ${esc(x.answer)} (${at(x.answeredAt)})` : x.askedAt ? wait : N("q.notAsked"); return `${N("q.lead")}
${N("pub")}
`; } // BRM-150: «Бот в Telegram» — бот найден (имя подтвердил Telegram), получает ли сообщения, привязка владельца. // Ключ бота здесь не бывает: в view только имя бота, флаги и имя привязанного владельца. function tgBoxMain(lang, view, q) { const L = (k, v) => esc(t(lang, "botp.tg." + k, v)); const b = view.bot ?? {}; const time = b.checkedAt ? almatyTime(new Date(b.checkedAt).toISOString()) : ""; const name = b.found ? `${L("found", { name: "@" + (b.username ?? "") })}
${L("confirmed", { time })}
` : `${L("err." + (b.error ?? "unknown"))}
${L("do." + (b.error ?? "unknown"))}
`; const recv = b.found ? (b.receiving ? `${L("recv.on")}
` : `${L("recv.off")}
${L("recv.offDo")}
`) : ""; const o = view.bound; const who = whoOf(o); // BRM-155: статус привязки — не привязано (слова нет) / ждёт слова / привязано. const state = o ? "bound" : view.wordSet ? "waiting" : "none"; const stateBox = `${L("state." + state)}
${L("state." + state + "Why")}
`; const word = view.wordMsg ? `${L("word." + (view.wordMsg === "saved" && o ? "savedBound" : view.wordMsg))}
` : ""; // Неверное слово страница называет тем же текстом, что бот. const check = view.checkMsg ? `${view.checkMsg === "wrong" ? esc(t(lang, "bot.bind.wrong")) : L("check." + view.checkMsg)}
` : ""; const pw = (name, label, ac) => ``; // BRM-167: форма видна и до, и после привязки; если слово задано — сначала текущее слово. const form = view.wordSetup ? `${L(!view.wordSet ? "word.hint" : o ? "word.hintBound" : "word.hintReplace")}
${view.wordSet ? `${L("word.onlyOwner")}
` : ""}` + (view.wordSet ? `` : "") : view.wordWhere ? `${L("word.where", { where: t(lang, "now.env." + (view.wordWhereEnv ?? "local")) })} ${esc(view.wordWhere)}
` : `${L("word.whereNone")}
`; if (view.moving) { return `${L("recv.moving")}
${word}${esc(t(lang, "now.bind.moving"))}
${L("safe")}
`; } if (view.receiverUrl) { return `${L("recv.elsewhere")}
${word}${esc(t(lang, "now.bind.elsewhere"))} ${esc(t(lang, "now.open"))}
${L("safe")}
`; } const bind = o ? `${who ? L("bound", { who }) : L("boundNoName")}${o.at ? " " + L("boundAt", { time: almatyTime(o.at) }) : ""}
${check}${form}` : `${L("unbound")}
${L("safe")}
`; } // BRM-182: «Как проверено слово для одобрения в этой версии» — цепочка на отдельной копии проверочными словами // (src/word-proof.js): что вводили, что получили, прошло ли. Настоящего слова здесь нет. export function proofBox(lang, p) { const L = (k, v) => esc(t(lang, "botp.proof." + k, v)); if (!p) return `${L("pending")}
`; const rows = p.rows.map((r) => `${L(p.ok ? "allOk" : "someFail", { time: almatyTime(p.at) })}
${L("how")}
| ${L("col.did")} | ${L("col.got")} | ${L("col.ok")} |
|---|
${L("off")}
${p(esc(t(lang, "now.send.moving")))}` : view.sending ? `${L("on")}
` : d && d.ready && !d.confirmed && !view.paused ? `${L("unchecked")}
${p(esc(sendLine(lang, d, almatyTime)))}` : `${L("off")}
` + (view.paused ? p(L("why.paused")) : "") + (d?.problem && !view.paused ? p(esc(sendLine(lang, d, almatyTime))) : view.missing ? p(esc(t(lang, "why.tg." + view.missing))) : view.paused ? "" : p(L("why.noAccess"))); const btn = view.paused ? `${p(`${L("resume.hint")}`)}` : `${p(`${L("pause.hint")}`)}`; const report = (kind) => { const r = view.reports[kind]; const last = r.last ? `${L("last")}: ${esc(r.last.atText)} — ${L("state." + r.last.state)}` : `${L("last")}: ${L("never")}`; const next = r.next ? `${L("next")}: ${esc(r.next.atText)} — ${L("state.planned")}` : `${L("next")}: ${L("dayOff")} ${L("summaryLink")}.`; return `${L("noErrors")}
`; return `${L("lead")}
${L("reports.note")}