168 lines
12 KiB
JavaScript
168 lines
12 KiB
JavaScript
// 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, ">").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(), why: testRun.why } : null };
|
||
}
|
||
|
||
const p = (s) => `<p>${s}</p>`;
|
||
const TEST_LOG = 15;
|
||
// BRM-143: проверочная публикация — запуск, канал, что мешает (причина, кто снимает, что сделать), журнал с меткой «тест».
|
||
function testBox(lang, tr, q) {
|
||
if (!tr) return "";
|
||
const L = (k, v) => esc(t(lang, "botp.test." + k, v));
|
||
const armed = tr.armedAt ? L("armed", { time: almatyTime(tr.armedAt) }) : L("notArmed");
|
||
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 ? `<p id="trcheck" class="st ok">${L("ok", { time: almatyTime(chk.at) })}</p>`
|
||
: `<p id="trcheck" class="st off">${L("blocked", { time: almatyTime(chk.at) })}</p><ul id="trwhy">${chk.problems.map((x) => `<li>${esc(tr.why(x))}</li>`).join("")}</ul>`;
|
||
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.kind === "stale" && e.what) s += ` (${L("what." + e.what)})`; // BRM-144: что поменялось
|
||
if (e.link) s += ` <a href="${esc(e.link)}" target="_blank" rel="noopener">${L("open")}</a>`;
|
||
return s;
|
||
};
|
||
const log = tr.log.length
|
||
? `<ul id="trlog">${tr.log.slice(0, TEST_LOG).map((e) => `<li>${esc(almatyTime(e.at))} — <b class="smp">${L("mark")}</b> ${kind(e)}</li>`).join("")}</ul>`
|
||
: `<p id="trlog">${L("empty")}</p>`;
|
||
return `<h2>${esc(t(lang, "botp.h.test"))}</h2>
|
||
<p>${esc(t(lang, "botp.test.lead"))}</p>
|
||
<p id="trarmed">${armed}</p>${channel}${check}
|
||
<p id="trweek"><a href="/week.html${q}">${L("week")}</a> — ${L("weekAbout")}</p>
|
||
<form method="post" action="/bot/test-check${q}"><button type="submit">${L("check")}</button></form>
|
||
<h3>${L("h.log")}</h3>
|
||
${log}`;
|
||
}
|
||
// BRM-150: «Бот в Telegram» — бот найден (имя подтвердил Telegram), получает ли сообщения, привязка владельца.
|
||
// Ключ бота здесь не бывает: в view только имя бота, флаги и имя привязанного владельца.
|
||
function tgBox(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
|
||
? `<p class="st ok" id="tgname">${L("found", { name: "@" + (b.username ?? "") })}</p><p><small>${L("confirmed", { time })}</small></p>`
|
||
: `<p class="st off" id="tgname">${L("err." + (b.error ?? "unknown"))}</p><p>${L("do." + (b.error ?? "unknown"))}</p>`;
|
||
const recv = b.found ? (b.receiving ? `<p class="st ok" id="tgrecv">${L("recv.on")}</p>` : `<p class="st off" id="tgrecv">${L("recv.off")}</p><p>${L("recv.offDo")}</p>`) : "";
|
||
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 ? `<p id="tgword" class="st ${view.wordMsg === "saved" ? "ok" : "off"}" role="status">${L("word." + view.wordMsg)}</p>` : "";
|
||
const form = !o && !view.wordSet
|
||
? `<form method="post" action="/bot/owner-word${q}"><label><span>${L("word.label")}</span> <input name="word" type="password" minlength="6" required autocomplete="new-password" aria-required="true"></label> <button type="submit">${L("word.save")}</button></form><p><small>${L("word.hint")}</small></p>`
|
||
: "";
|
||
const bind = o
|
||
? `<p class="st ok" id="tgowner">${who ? L("bound", { who }) : L("boundNoName")}${o.at ? " " + L("boundAt", { time: almatyTime(o.at) }) : ""}</p>`
|
||
: `<p class="st off" id="tgowner">${L("unbound")}</p><ol id="tgsteps">${!view.wordSet ? `<li>${L("step.word")}</li>` : ""}<li>${L("step.start", { name: b.found ? "@" + (b.username ?? "") : L("theBot") })}</li><li>${L("step.send")}</li></ol>${form}`;
|
||
return `<h2 id="tgbot">${esc(t(lang, "botp.h.tg"))}</h2>
|
||
${name}${recv}${word}${bind}
|
||
<p><small>${L("safe")}</small></p>`;
|
||
}
|
||
|
||
export function botPage(lang = "ru", view, q = "", deployView = null) {
|
||
const L = (k, v) => esc(t(lang, "botp." + k, v));
|
||
const status = view.sending
|
||
? `<p class="st ok" id="sending">${L("on")}</p>`
|
||
: `<p class="st off" id="sending">${L("off")}</p>` + (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
|
||
? `<form method="post" action="/bot/resume${q}"><button type="submit">${L("resume")}</button></form>${p(`<small>${L("resume.hint")}</small>`)}`
|
||
: `<form method="post" action="/bot/pause${q}"><button type="submit">${L("pause")}</button></form>${p(`<small>${L("pause.hint")}</small>`)}`;
|
||
const report = (kind) => {
|
||
const r = view.reports[kind];
|
||
const last = r.last
|
||
? `${L("last")}: ${esc(r.last.atText)} — <b class="${r.last.state}">${L("state." + r.last.state)}</b>`
|
||
: `${L("last")}: ${L("never")}`;
|
||
const next = r.next
|
||
? `${L("next")}: ${esc(r.next.atText)} — <b class="planned">${L("state.planned")}</b>`
|
||
: `${L("next")}: ${L("dayOff")} <a href="/summary.html${q}">${L("summaryLink")}</a>.`;
|
||
return `<li id="rep-${kind}"><b>${L("kind." + kind)}</b><br>${last}<br>${next}</li>`;
|
||
};
|
||
const errors = view.errors.length
|
||
? "<ul id=\"errors\">" + view.errors.map((e) => `<li>${esc(e.atText)} — ${L("what." + e.what)}: ${L("cause." + e.cause)}${e.retryText ? ". " + L("retry", { time: e.retryText }) : ""}<details><summary>${L("more")}</summary>${esc(e.reason ?? "")}</details></li>`).join("") + "</ul>"
|
||
: `<p id="errors">${L("noErrors")}</p>`;
|
||
return `<!doctype html><html lang="${lang}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${L("title")}</title>
|
||
<style>body{font:16px/1.5 system-ui,sans-serif;max-width:820px;margin:auto;padding:16px;color:#222}h1{font-size:24px}h2{font-size:18px;margin-top:28px}
|
||
.box{background:#f3f6ff;border-radius:8px;padding:10px 14px}.st{font-weight:600}.st.ok{color:#14532d}.st.off{color:#8a1c1c}
|
||
.published{color:#14532d}.planned{color:#6b4a00}.failed{color:#8a1c1c}li{margin:6px 0}small{color:#555}button{font:inherit;padding:6px 16px}details{font-size:14px;color:#555}</style></head><body>
|
||
<p><a href="/${q}">${L("back")}</a></p>
|
||
<h1>${L("title")}</h1>
|
||
<p class="box">${L("lead")}</p>
|
||
<div id="deploy" class="box" aria-live="polite">${deployBox(lang, deployView)}</div>
|
||
${tgBox(lang, view, q)}
|
||
<h2>${L("h.status")}</h2>
|
||
${status}
|
||
${btn}
|
||
<h2>${L("h.reports")}</h2>
|
||
<p>${L("reports.note")}</p>
|
||
<ul>${KINDS.map(report).join("")}</ul>
|
||
<h2>${L("h.errors")}</h2>
|
||
${errors}
|
||
${testBox(lang, view.testRun, q)}
|
||
</body></html>`;
|
||
}
|