// 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, "
"); // BRM-147: карточка согласования на странице — то же, что владелец получает в бот: текст, материалы, канал, // время, срок, состояние; до отправки «ничего не отправлено», после — ссылка, номер и время сообщения. // Кнопки — форма со словом для одобрения, сервер вызывает тот же testRun.onButton, что и бот. function cardBox(lang, c, { q, wordSet, full }) { const B = (k, v) => esc(t(lang, "tr." + k, v)); const L = (k, v) => esc(t(lang, "botp.test." + k, v)); const id = full ? "trcard" : `trcard-${c.id}`; const mats = c.attachments?.length ? c.attachments.map((a) => `«${esc(a.title)}»`).join(", ") : B("card.noAssets"); const result = c.status === "sent" ? `

${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 = `

${btns}

${wordSet ? `

${L("card.same")}

` : `

${L("card.noWord")}

`}
`; } 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 ? `
${body}
` : `
${L("card.old", { time: almatyTime(c.createdAt) })} — ${B("state." + c.status)}${body}
`; } // BRM-156: пустая карточка — пока карточки нет, видно, из чего она состоит, три кнопки в сером состоянии // с причиной рядом и «Ничего не отправлено». Формы нет: решать пока нечего. function emptyCard(lang, tr, approved) { const B = (k, v) => esc(t(lang, "tr." + k, v)); const L = (k, v) => esc(t(lang, "botp.test." + k, v)); const btns = CARD_ACTIONS.map((a) => ``).join(" "); const channel = tr.channel ? B("card.channel", { title: tr.channel.title }) : L("card.noChannel"); const time = approved && tr.next ? B("card.time", { time: almatyTime(tr.next.at) }) : L("card.timeLater"); return `

${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")}

`; } // BRM-143: проверочная публикация — запуск, канал, что мешает (причина, кто снимает, что сделать), журнал с меткой «тест». function testBox(lang, tr, q, view = {}) { if (!tr) return ""; const L = (k, v) => esc(t(lang, "botp.test." + k, v)); // BRM-157: место со временем запуска по Алматы — до утверждения стратегии «запуска не будет» и чего ждём. const approved = tr.approved ?? Boolean(tr.armedAt); const launch = !approved ? `

${L("notArmed")}

${L("launch.go")}

` : `${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) })}

`; const kind = (e) => { const v = { ...e, publishAt: e.publishAt ? almatyTime(e.publishAt) : "", sentAt: e.sentAt ? almatyTime(e.sentAt) : "", title: e.title ?? "" }; let s = L("k." + e.kind, v); if (e.kind === "blocked") s += ": " + e.problems.map((x) => esc(tr.why(x))).join(" "); if (e.link) s += ` ${L("open")}`; return s; }; // BRM-156: итог журнала — «Ничего не отправлено» или последняя отправка: номер, время, ссылка. const lastSent = tr.log.find((e) => e.kind === "sent"); const logSum = lastSent ? `

${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 = `

${L("h.card")}

${msg}${last ? cardBox(lang, last, { q, wordSet: view.wordSet, full: true }) + older.slice(0, OLD_CARDS).map((c) => cardBox(lang, c, { q, full: false })).join("") : emptyCard(lang, tr, approved)}`; return `

${esc(t(lang, "botp.h.test"))}

${esc(t(lang, "botp.test.lead"))}

${L("h.launch")}

${launch}${channel}${check}

${L("mark")} ${L("count", { n: tr.sentCount ?? 0 })}

${cards}

${L("h.log")}

${logSum}${log}`; } // BRM-171: где принимаются команды бота: here — эта версия, elsewhere — другая (ссылка), none — никуда. export function cmdWhere(view) { const b = view.bot ?? {}; if (view.moving) return "moving"; // BRM-180: ваш продукт, а бота держит другая версия — без ссылок туда if (view.receiverUrl) return "elsewhere"; if (b.found && b.receiving && b.here) return "here"; if (b.found && !b.receiving) return "none"; if (b.found === false) return "noBot"; // BRM-180: бот ещё не проверен — как у доставки: эта версия не принимает сообщения — «пока никуда не приходят». return view.delivery?.problem?.code === "elsewhere" ? "none" : "here"; } const linesOf = (lang, view) => nowLines(lang, { where: cmdWhere(view), env: view.env, receiverEnv: view.receiverEnv, bound: Boolean(view.bound), who: whoOf(view.bound), wordSet: view.wordSet, delivery: view.delivery, decisions: view.decisions }, almatyTime); // BRM-179: под строкой «Ждут вашего решения» — какое решение, что сделать и ссылка на блок, где его принять. // base: "" на «Бот и отчёты» (якоря этой страницы), "/bot.html" на главной. const DEC_LINKS = { strategy: ["/strategy.html", "#svcard"], questions: [null, "#botqs"], channel: [null, "#botreq-ch"], summary: [null, "#botreq-sum"], plan: ["/plan.html", ""], cards: [null, "#trcards"] }; export function waitList(lang, dec, base = "") { const N = (k, v) => esc(t(lang, "now." + k, v)); const items = Object.entries(dec?.parts ?? {}).filter(([k, n]) => n > 0 && DEC_LINKS[k]).map(([k, n]) => { const [page, hash] = DEC_LINKS[k]; const href = (page ?? base) + hash; return `
  • ${N("dec." + k, { n })} ${N("go." + (page ? k : "here"))}
  • `; }).join(""); return items ? `` : ""; } const cls = (ok) => (ok === null ? "" : ` class="st ${ok ? "ok" : "off"}"`); // BRM-180/188: кнопка-ссылка «Открыть бота в Telegram» видна всегда: до привязки — завершить привязку, // после — открыть личный чат с ботом; бота нет или он отвечает не здесь — серая кнопка и причина рядом. function openBotBtn(lang, view) { const N = (k, v) => esc(t(lang, "now." + k, v)); const b = view.bot ?? {}; const where = cmdWhere(view); if (where === "here" && b.found && b.username) { const href = `https://t.me/${encodeURIComponent(b.username)}${view.bound ? "" : "?start=bind"}`; return `

    ${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 ? `
    ${esc(t(lang, "botp.more"))}${esc(d.problem.detail)}
    ` : ""; const items = linesOf(lang, view).map((x) => `
  • ${esc(x.text)}${x.id === "cmd" ? there : x.id === "send" ? detail : x.id === "wait" && where === "here" ? waitList(lang, view.decisions, "") : ""}
  • `).join("\n"); const pick = pickBox(lang, view, q); const canCheck = where === "here" && view.connected && !d.paused; const check = where !== "here" ? "" : `
    ${canCheck ? `

    ${N("checkHint")}

    ` : `

    ${N("checkOff")}

    `}`; return `

    ${N("h")}

    ${N("lead")}

    ${openBotBtn(lang, view)}${dc}${pick}${check}`; } // BRM-180/188: тот же блок «Бот сейчас» на главной — строки и обе кнопки (как на «Бот и отчёты»); подробности — на «Бот и отчёты». export function homeNowBox(lang, view) { const N = (k, v) => esc(t(lang, "now." + k, v)); const here = cmdWhere(view) === "here"; const items = linesOf(lang, view).map((x) => `
  • ${esc(x.text)}${x.id === "wait" && here ? waitList(lang, view.decisions, "/bot.html") : ""}
  • `).join(""); return `
    ${N("h")}${openBotBtn(lang, view)}${pickBox(lang, view, "", true)}

    ${N("more")}

    `; } // BRM-171: вопросы бота (не больше трёх, у каждого «зачем») и запросы канала и чата для сводок. function questionsBox(lang, view) { const S = (k, v) => esc(t(lang, "sv." + k, v)); const N = (k, v) => esc(t(lang, "now." + k, v)); const head = `

    ${N("q.h")}

    `; if (cmdWhere(view) === "moving") return `${head}

    ${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 `
  • ${esc(x.text)}
    ${S("q.why")}: ${esc(x.why)}
    ${state}
  • `; }).join(""); const ch = sv.channel.state === "confirmed" ? `${S("req.chConfirmed", { title: sv.channel.title })} (${at(sv.channel.at)})` : sv.channel.state === "waiting" ? `${wait}
    ${N("dec.channel")}` : N("q.notAsked"); const sm = ["here", "other"].includes(sv.summary.state) ? `${S("req.sm." + sv.summary.state)} (${at(sv.summary.at)})` : sv.summary.state === "waiting" ? `${wait}
    ${N("dec.summary")}` : N("q.notAsked"); return `${head}

    ${N("q.lead")}

      ${qs}

    ${S("reqH")}

    ${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("word.newH")}

    ${view.wordSet ? pw("current", "word.current", "current-password") + " " : ""}${pw("word", "word.label", "new-password")} ${pw("confirm", "word.confirm", "new-password")}

    ${L(!view.wordSet ? "word.hint" : o ? "word.hintBound" : "word.hintReplace")}

    ${view.wordSet ? `

    ${L("word.onlyOwner")}

    ` : ""}` + (view.wordSet ? `
    ${pw("word", "check.label", "current-password")}
    ` : "") : view.wordWhere ? `

    ${L("word.where", { where: t(lang, "now.env." + (view.wordWhereEnv ?? "local")) })} ${esc(view.wordWhere)}

    ` : `

    ${L("word.whereNone")}

    `; if (view.moving) { return `

    ${esc(t(lang, "botp.h.tg"))}

    ${name}

    ${L("recv.moving")}

    ${word}

    ${esc(t(lang, "now.bind.moving"))}

    ${L("safe")}

    `; } if (view.receiverUrl) { return `

    ${esc(t(lang, "botp.h.tg"))}

    ${name}

    ${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")}

      ${!view.wordSet ? `
    1. ${L("step.word")}
    2. ` : ""}
    3. ${L("step.start", { name: b.found ? "@" + (b.username ?? "") : L("theBot") })}
    4. ${L("step.send")}
    ${check}${form}`; return `

    ${esc(t(lang, "botp.h.tg"))}

    ${name}${recv}${stateBox}${word}${bind}

    ${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("h")}

    ${L("pending")}

    `; const rows = p.rows.map((r) => `${L("did." + r.step)}${r.word ? ` «${esc(r.word)}»` : ""}${r.got.map((k) => esc(t(lang, k))).join("
    ")}${L(r.ok ? "pass" : "fail")}`).join(""); return `

    ${L("h")}

    ${L(p.ok ? "allOk" : "someFail", { time: almatyTime(p.at) })}

    ${L("how")}

    ${rows}
    ${L("col.did")}${L("col.got")}${L("col.ok")}
    `; } function tgBox(lang, view, q) { // Там, где сообщения бота принимает другая версия, слово здесь не задаётся — и проверку не показываем. return tgBoxMain(lang, view, q) + (view.moving || view.receiverUrl ? "" : "\n" + proofBox(lang, view.wordProof)); } export function botPage(lang = "ru", view, q = "", deployView = null) { const L = (k, v) => esc(t(lang, "botp." + k, v)); // BRM-171: «включена» — только после подтверждённой доставки; иначе что мешает, кто снимает, что сделать. const d = view.delivery; const status = view.moving ? `

    ${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("kind." + kind)}
    ${last}
    ${next}
  • `; }; const errors = view.errors.length ? "" : `

    ${L("noErrors")}

    `; return `${L("title")}

    ${L("back")}

    ${L("title")}

    ${L("lead")}

    ${deployBox(lang, deployView)}
    ${nowBox(lang, view, q)} ${tgBox(lang, view, q)} ${questionsBox(lang, view)}

    ${L("h.status")}

    ${status} ${btn}

    ${L("h.reports")}

    ${L("reports.note")}

    ${L("h.errors")}

    ${errors} ${testBox(lang, view.testRun, q, view)} `; }