// BRM-74: раздел «Бот и отчёты» — статус отправки, пауза, последние и следующие отчёты агента, ошибки отправки. // Страница целиком собирается сервером и работает без скриптов (кнопки — формы). import { t } from "./i18n.js"; import { almatyTime } from "./deploy-status.js"; import { localParts } from "./summary-schedule.js"; import { deployBox } from "./site.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 (/\((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 })); return { sending: connected && !paused, 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 ? `${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("empty")}
`; const [last, ...older] = tr.cards ?? []; const msg = view.cardMsg ? `${L("card.msg." + view.cardMsg)}
` : ""; const cards = !tr.armedAt ? "" : `${L("card.none")}
`}`; return `${esc(t(lang, "botp.test.lead"))}
${armed}
${next}${channel}${check}${L("mark")} ${L("count", { n: tr.sentCount ?? 0 })}
${cards}${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 = !o ? null : o.name && o.username ? `${o.name} (@${o.username})` : o.name ?? (o.username ? "@" + o.username : null); const word = view.wordMsg ? `${L("word." + view.wordMsg)}
` : ""; const form = !o && !view.wordSet ? `${L("word.hint")}
` : ""; const bind = o ? `${who ? L("bound", { who }) : L("boundNoName")}${o.at ? " " + L("boundAt", { time: almatyTime(o.at) }) : ""}
` : `${L("unbound")}
${L("safe")}
`; } export function botPage(lang = "ru", view, q = "", deployView = null) { const L = (k, v) => esc(t(lang, "botp." + k, v)); const status = view.sending ? `${L("on")}
` : `${L("off")}
` + (view.paused ? p(L("why.paused")) : "") + (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")}