brendmanager/src/bot-page.js

206 lines
15 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-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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
// Когда по расписанию уйдёт следующий отчёт вида 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) => `<p>${s}</p>`;
const TEST_LOG = 15;
const OLD_CARDS = 2;
const CARD_ACTIONS = ["approve", "rework", "reject"];
const multiline = (s) => esc(s).replace(/\n/g, "<br>");
// 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"
? `<p class="st ok" id="${id}-sent">${L("card.sent", { messageId: c.messageId, time: almatyTime(c.sentAt) })} <a href="${esc(c.link)}" target="_blank" rel="noopener">${L("card.open")}</a></p>`
: `<p class="st off" id="${id}-nothing">${L("card.nothing." + (c.status === "approved" ? (c.retryAt ? "retry" : "approved") : c.status === "waiting" ? "waiting" : "closed"), { time: almatyTime(c.retryAt ?? c.publishAt) })}</p>`;
let form = "";
if (full && c.status === "waiting") {
const off = wordSet ? "" : ' class="off" aria-disabled="true"';
const btns = CARD_ACTIONS.map((a) => `<button type="submit" name="action" value="${a}"${off}>${B("btn." + a)}</button>`).join(" ");
form = `<form method="post" action="/bot/test-card${q}" id="trform"><input type="hidden" name="id" value="${esc(c.id)}"><input type="hidden" name="h" value="${esc(c.hash)}">
<label><span>${L("card.word")}</span> <input name="word" type="password" autocomplete="current-password"${wordSet ? ' required aria-required="true"' : " disabled"}></label>
<p>${btns}</p>${wordSet ? `<p><small>${L("card.same")}</small></p>` : `<p><small id="trformwhy">${L("card.noWord")}</small></p>`}</form>`;
}
const body = `<p><b class="smp">${L("mark")}</b> ${L("card.state")}: <b>${B("state." + c.status)}</b></p>
<p>${B("card.text")}:</p><blockquote id="${id}-text">${multiline(c.post)}</blockquote>
<p>${B("card.assets")}: ${mats}</p>
<p>${B("card.channel", { title: c.chat?.title ?? "" })}</p>
<p>${B("card.time", { time: almatyTime(c.publishAt) })}</p>
${c.status === "waiting" ? `<p>${B("card.deadline", { time: almatyTime(c.expiresAt) })}</p>` : ""}${result}${form}`;
return full
? `<div id="${id}" class="card">${body}</div>`
: `<details id="${id}"><summary>${L("card.old", { time: almatyTime(c.createdAt) })} — ${B("state." + c.status)}</summary>${body}</details>`;
}
// BRM-143: проверочная публикация — запуск, канал, что мешает (причина, кто снимает, что сделать), журнал с меткой «тест».
function testBox(lang, tr, q, view = {}) {
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 next = !tr.armedAt ? "" : `<p id="trnext">${tr.next ? L("next", { time: almatyTime(tr.next.at) }) : L("noNext")}</p>`;
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.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>`;
const [last, ...older] = tr.cards ?? [];
const msg = view.cardMsg ? `<p id="trmsg" class="st ${view.cardMsg === "done" ? "ok" : "off"}" role="status">${L("card.msg." + view.cardMsg)}</p>` : "";
const cards = !tr.armedAt ? ""
: `<h3 id="trcards">${L("h.card")}</h3>${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("") : `<p id="trcard">${L("card.none")}</p>`}`;
return `<h2>${esc(t(lang, "botp.h.test"))}</h2>
<p>${esc(t(lang, "botp.test.lead"))}</p>
<p id="trarmed">${armed}</p>${next}${channel}${check}
<p id="trcount"><b class="smp">${L("mark")}</b> ${L("count", { n: tr.sentCount ?? 0 })}</p>
<form method="post" action="/bot/test-check${q}"><button type="submit">${L("check")}</button></form>
${cards}
<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}.smp{display:inline-block;border:1px dashed #9a7400;background:#fff6d6;color:#6b5000;border-radius:4px;padding:0 5px;font-size:12px}.card{border:1px solid #c9d3ee;border-radius:8px;padding:6px 14px;margin:8px 0}blockquote{margin:6px 0;padding:6px 10px;background:#f7f7f7;border-left:3px solid #c9d3ee}button.off{opacity:.55;cursor:not-allowed}</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, view)}
</body></html>`;
}