brendmanager/src/test-week.js

130 lines
8.2 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-145: неделя проверки — 7 дней подряд по расписанию проверочного пути (BRM-143/144).
// Раз в минуту отмечает, что версия работала; после 21:30 по Алматы закрывает день: карточка по расписанию
// или конкретная причина, одобрение, отправка со ссылкой; владельцу уходит сводка дня тем же ботом согласований.
// Итог дня хранится отдельно: журнал проверочного пути обрезается (200 записей).
import fs from "node:fs";
import path from "node:path";
import { t } from "./i18n.js";
import { almatyTime } from "./deploy-status.js";
import { addDays } from "./plan.js";
import { OFFSET_MS } from "./test-run.js";
export const DAYS = 7;
export const CLOSE_AT = "21:30"; // по Алматы: после срока ответа на карточку (21:00)
export const SUMMARY_TRIES = 3;
export const PAGE = "/week.html";
const localDate = (ms) => new Date(ms + OFFSET_MS).toISOString().slice(0, 10);
const atLocal = (date, hm) => Date.parse(`${date}T${hm}:00Z`) - OFFSET_MS;
const iso = (ms) => new Date(ms).toISOString();
export function createTestWeek({ file, testRun, getPlan, strategy, siteUrl = "", lang = "ru" }) {
let st;
try { st = JSON.parse(fs.readFileSync(file, "utf8")); } catch { st = {}; }
st.start ??= null; st.seen ??= {}; st.days ??= [];
const save = () => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file + ".tmp", JSON.stringify(st, null, 2)); fs.renameSync(file + ".tmp", file); };
const L = (k, v) => t(lang, "tw." + k, v);
const dates = () => (st.start ? Array.from({ length: DAYS }, (_, i) => addDays(st.start, i)) : []);
const ideaOf = (id) => getPlan().ideas.find((i) => i.id === id);
// Итог дня из журнала и карточек проверочного пути на момент now.
function evaluate(date, now) {
const j = testRun.journal();
const ofDay = j.log.filter((e) => localDate(Date.parse(e.at)) === date);
const cards = ofDay.filter((e) => e.kind === "card").map((e) => {
const c = j.cards.find((x) => x.id === e.card) ?? {};
const idea = ideaOf(c.ideaId ?? e.ideaId);
return {
id: e.card, ideaId: c.ideaId ?? e.ideaId, title: idea?.title ?? "", sample: Boolean(idea?.sample), createdAt: e.at, trigger: e.trigger ?? c.trigger ?? "schedule",
publishAt: c.publishAt ?? e.publishAt, status: c.status ?? "waiting", approvedAt: c.approvedAt ?? null, sentAt: c.sentAt ?? null,
link: c.link ?? null, messageId: c.messageId ?? null, ...(c.what ? { what: c.what } : {}), ...(c.reason ? { reason: c.reason } : {}),
};
});
// Что мешало в этот день: без повторов по коду.
const problems = [];
// Блокировка пишется в журнал один раз, пока причины те же: если она тянется со вчера, берём последнюю проверку доступа этого дня.
const chk = j.lastCheck && !j.lastCheck.ok && localDate(Date.parse(j.lastCheck.at)) === date ? [{ problems: j.lastCheck.problems }] : [];
for (const e of [...ofDay.filter((x) => x.kind === "blocked"), ...chk]) for (const p of e.problems ?? []) if (!problems.some((x) => x.code === p.code)) problems.push(p);
const armed = ofDay.find((e) => e.kind === "armed");
let reason = null;
if (!cards.length) {
const ideas = getPlan().ideas.filter((i) => i.date === date);
if (problems.length) reason = "blocked";
else if (!st.seen[date]) reason = "down";
else if (!strategy.isApproved()) reason = "strategy";
else if (!ideas.length) reason = "noIdea";
else if (j.cards.some((c) => ideas.some((i) => i.id === c.ideaId))) reason = "already";
else if (ideas.every((i) => !["draft", "review"].includes(i.status))) reason = "status";
else reason = "notDue";
}
return { n: dates().indexOf(date) + 1, date, seen: Boolean(st.seen[date]), armedAt: armed?.at ?? null, cards, problems, reason, at: iso(now) };
}
// Текст ошибки Telegram владельцу не показываем: причина, кто снимает и что сделать — без технических подробностей.
const RAW = ["key.bad", "channel.gone", "rights.post", "send.error", "owner.unbound"];
const why = (p) => testRun.why(RAW.includes(p.code) ? { ...p, detail: undefined } : p);
const dmy = (date) => date.split("-").reverse().join(".");
const reasonText = (d) => (d.reason === "blocked" ? d.problems.map(why).join(" ") : L("reason." + d.reason));
function cardLine(c) {
const head = L("sum.card", { id: c.id, title: c.title, time: almatyTime(c.createdAt) });
if (c.status === "sent") return [head, L("sum.approved", { time: almatyTime(c.approvedAt) }), L("sum.sent", { time: almatyTime(c.sentAt), link: c.link })].join("\n");
return [head, ...(c.approvedAt ? [L("sum.approved", { time: almatyTime(c.approvedAt) })] : []), L("sum.state." + c.status)].join("\n");
}
function summaryText(d) {
const body = d.cards.length ? d.cards.map(cardLine) : [L("sum.noCard", { why: reasonText(d) })];
if (d.cards.length && d.problems.length) body.push(L("sum.problems") + "\n" + d.problems.map((p) => "• " + why(p)).join("\n"));
const page = siteUrl ? L("sum.page", { url: siteUrl + PAGE }) : L("sum.pageNoUrl");
return [L("sum.head", { n: d.n, total: DAYS, date: dmy(d.date) }), "", ...body, "", page].join("\n");
}
async function sendSummary(d, now) {
d.summary ??= { state: "pending", tries: 0 };
d.summary.tries++;
let r = null, err = null;
try { r = await testRun.toOwner(summaryText(d)); } catch (e) { err = e; }
if (r?.ok) Object.assign(d.summary, { state: "sent", at: iso(now), messageId: r.result.message_id });
else {
const code = r === null && !err ? (testRun.adapter.secrets().length ? "owner.unbound" : "key.missing") : "send.error";
Object.assign(d.summary, { state: d.summary.tries >= SUMMARY_TRIES ? "failed" : "pending", reason: { code, who: code === "owner.unbound" ? "tatiana" : "pm", ...(r?.description || err ? { detail: String(r?.description ?? err.message) } : {}) } });
}
save();
}
// Раз в минуту, после тика проверочного пути.
async function tick(now = Date.now()) {
const armedAt = testRun.journal().armedAt;
if (!armedAt) return { skipped: "notArmed" };
if (!st.start) { st.start = localDate(Date.parse(armedAt)); save(); }
const today = localDate(now);
const ds = dates();
if (ds.includes(today) && !st.seen[today]) { st.seen[today] = iso(now); save(); }
const closed = [];
for (const date of ds) {
if (st.days.some((d) => d.date === date) || now < atLocal(date, CLOSE_AT)) continue;
const d = { ...evaluate(date, now), closedAt: iso(now) };
st.days.push(d); save();
closed.push(d);
}
for (const d of st.days.filter((x) => !x.summary || x.summary.state === "pending")) await sendSummary(d, now);
return { closed };
}
// Для страницы: закрытые дни, текущий (идёт) и будущие; итог.
function view(now = Date.now()) {
const today = localDate(now);
const days = dates().map((date) => st.days.find((d) => d.date === date)
?? (date === today ? { ...evaluate(date, now), open: true } : { n: dates().indexOf(date) + 1, date, future: date > today, cards: [], problems: [], reason: date > today ? null : "down" }));
const done = st.days.length;
const totals = {
days: DAYS, closed: done,
withCard: days.filter((d) => d.cards.length).length,
approved: days.reduce((a, d) => a + d.cards.filter((c) => c.approvedAt).length, 0),
sent: days.reduce((a, d) => a + d.cards.filter((c) => c.status === "sent").length, 0),
summaries: st.days.filter((d) => d.summary?.state === "sent").length,
};
return { start: st.start, end: st.start ? addDays(st.start, DAYS - 1) : null, finished: done >= DAYS, days, totals, armedAt: testRun.journal().armedAt };
}
return { tick, view, evaluate, summaryText, reasonText, why };
}