107 lines
8.5 KiB
JavaScript
107 lines
8.5 KiB
JavaScript
// BRM-163: карточка согласования и журнал отправки у записи «Плана и банка идей».
|
||
// Собирает сервер (приёмка смотрит страницу до скриптов). Данные — запись плана, карточка проверочного
|
||
// пути с этой записью (testRun.view()), публикации записи. Кнопки — та же форма /bot/test-card,
|
||
// что на «Бот и отчёты», только с возвратом к записи (back=plan).
|
||
import { t } from "./i18n.js";
|
||
import { almatyTime } from "./deploy-status.js";
|
||
import { OFFSET_MS, SLOT } from "./test-run.js";
|
||
|
||
const ACTIONS = ["approve", "rework", "reject"];
|
||
const esc = (s) => String(s ?? "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||
const multiline = (s) => esc(s).replace(/\n/g, "<br>");
|
||
// Время публикации по Алматы, которое агент назначит записи с датой (SLOT).
|
||
export const slotTime = (date) => new Date(Date.parse(`${date}T${SLOT}:00Z`) - OFFSET_MS).toISOString();
|
||
|
||
// Какую запись показать: ?id, иначе ближайшую с датой от сегодня, иначе первую по дате, иначе любую.
|
||
export function pickIdea(ideas, id, today) {
|
||
const byId = ideas.find((i) => String(i.id) === String(id ?? ""));
|
||
if (byId) return byId;
|
||
const dated = ideas.filter((i) => i.date).sort((a, b) => a.date.localeCompare(b.date) || a.id - b.id);
|
||
return dated.find((i) => i.date >= today) ?? dated[0] ?? ideas[0] ?? null;
|
||
}
|
||
|
||
const cardsOf = (tr, idea) => (tr?.cards ?? []).filter((c) => c.ideaId === idea.id); // свежие первыми
|
||
|
||
export function planCard(lang, { ideas = [], idea, tr, assets = [], publications = [], why = () => "", wordSet = false, q = "", msg = null }) {
|
||
const L = (k, v) => esc(t(lang, "plan.card." + k, v));
|
||
const B = (k, v) => esc(t(lang, "tr." + k, v));
|
||
const P = (k, v) => esc(t(lang, "botp.test." + k, v));
|
||
const choose = ideas.length
|
||
? `<form method="get" action="/plan.html" id="appick">${q ? `<input type="hidden" name="lang" value="${esc(new URLSearchParams(q.slice(1)).get("lang"))}">` : ""}<label><span>${L("pick")}</span> <select name="id">${[...ideas]
|
||
.sort((a, b) => (a.date ?? "9999").localeCompare(b.date ?? "9999") || a.id - b.id)
|
||
.map((i) => `<option value="${i.id}"${idea && i.id === idea.id ? " selected" : ""}>${esc(i.date ? i.date + " · " : "")}${esc(i.title)}</option>`).join("")}</select></label> <button type="submit">${L("open")}</button></form>`
|
||
: "";
|
||
const note = msg ? `<p id="apmsg" class="st ${msg === "done" ? "ok" : "off"}" role="status">${P("card.msg." + msg)}</p>` : "";
|
||
const offBtns = (reason) => `<p>${ACTIONS.map((a) => `<button type="button" class="off" aria-disabled="true" aria-describedby="apwhy">${B("btn." + a)}</button>`).join(" ")}</p><p><small id="apwhy">${reason}</small></p>`;
|
||
|
||
if (!idea) {
|
||
return `<div id="apcard" class="card"><p><b class="smp">${P("mark")}</b> ${L("empty")}</p>
|
||
<p>${B("card.text")}: <i>${P("card.later")}</i></p><p>${B("card.assets")}: <i>${P("card.later")}</i></p>
|
||
<p>${tr?.channel ? B("card.channel", { title: tr.channel.title }) : P("card.noChannel")}</p><p>${P("card.timeLater")}</p>
|
||
${offBtns(L("why.noIdea"))}</div>
|
||
<h3 id="aplogh">${L("h.log")}</h3><div id="aplog"><p id="aplogsum" class="st off">${P("card.nothing.closed")}</p><p id="apcount">${L("count", { test: 0, real: 0 })}</p></div>`;
|
||
}
|
||
|
||
const [c] = cardsOf(tr, idea);
|
||
const text = c ? c.post : [idea.title, idea.description].map((s) => String(s ?? "").trim()).filter(Boolean).join("\n\n");
|
||
const att = c ? c.attachments ?? [] : assets;
|
||
const mats = att.length ? att.map((a) => `«${esc(a.title)}»`).join(", ") : B("card.noAssets");
|
||
const channel = c ? B("card.channel", { title: c.chat?.title ?? "" }) : tr?.channel ? B("card.channel", { title: tr.channel.title }) : P("card.noChannel");
|
||
const time = c ? B("card.time", { time: almatyTime(c.publishAt) }) : idea.date ? B("card.time", { time: almatyTime(slotTime(idea.date)) }) : L("noDate");
|
||
const state = c ? B("state." + c.status) : esc(t(lang, "ap.status." + (idea.status ?? "draft")));
|
||
|
||
let actions;
|
||
if (c && c.status === "waiting" && wordSet) {
|
||
actions = `<form method="post" action="/bot/test-card${q}" id="apform"><input type="hidden" name="back" value="plan"><input type="hidden" name="id" value="${esc(c.id)}"><input type="hidden" name="h" value="${esc(c.hash)}">
|
||
<label><span>${P("card.word")}</span> <input name="word" type="password" autocomplete="current-password" required aria-required="true"></label>
|
||
<p>${ACTIONS.map((a) => `<button type="submit" name="action" value="${a}">${B("btn." + a)}</button>`).join(" ")}</p><p><small>${P("card.same")}</small></p></form>`;
|
||
} else {
|
||
const reason = c && c.status === "waiting" ? L("why.noWord")
|
||
: c ? L("why.closed", { state: B("state." + c.status) })
|
||
: ["approved", "published"].includes(idea.status) ? L("why.agreed")
|
||
: !idea.date ? L("why.noDate")
|
||
: tr?.approved ? L("why.wait", { time: almatyTime(slotTime(idea.date)) }) : L("why.strategy");
|
||
actions = offBtns(reason);
|
||
}
|
||
|
||
const card = `<div id="apcard" class="card"><p><b class="smp">${P("mark")}</b> ${L("record")}: <b id="aptitle">${esc(idea.title)}</b></p>
|
||
<p>${P("card.state")}: <b id="apstate">${state}</b></p>
|
||
<p>${B("card.text")}:</p><blockquote id="aptext">${multiline(text)}</blockquote>
|
||
<p id="apassets">${B("card.assets")}: ${mats}</p>
|
||
<p id="apchannel">${channel}</p>
|
||
<p id="aptime">${time}</p>
|
||
${c && c.status === "waiting" ? `<p>${B("card.deadline", { time: almatyTime(c.expiresAt) })}</p>` : ""}${actions}</div>`;
|
||
|
||
// Журнал записи: публикации (тест / настоящая) и события проверочного пути по её карточкам.
|
||
const pubs = publications.filter((p) => p.ideaId === idea.id);
|
||
const tests = pubs.filter((p) => p.test), reals = pubs.filter((p) => !p.test);
|
||
const ids = new Set(cardsOf(tr, idea).map((x) => x.id));
|
||
const events = (tr?.log ?? []).filter((e) => e.ideaId === idea.id || (e.card != null && ids.has(e.card)));
|
||
const sentEv = events.find((e) => e.kind === "sent");
|
||
const sentCard = cardsOf(tr, idea).find((x) => x.status === "sent");
|
||
const lastTest = tests.at(-1);
|
||
const sent = sentEv ? { messageId: sentEv.messageId, at: sentEv.sentAt ?? sentEv.at, link: sentEv.link }
|
||
: sentCard ? { messageId: sentCard.messageId, at: sentCard.sentAt, link: sentCard.link }
|
||
: lastTest?.messageId ? { messageId: lastTest.messageId, at: lastTest.createdAt, link: lastTest.link } : null;
|
||
const open = (link) => (link ? ` <a href="${esc(link)}" target="_blank" rel="noopener">${P("card.open")}</a>` : "");
|
||
const nothing = !c ? (["approved", "published"].includes(idea.status) ? "nothing.agreed" : "nothing.notApproved")
|
||
: c.status === "waiting" ? "nothing.waiting" : c.status === "approved" ? "nothing.approved" : "nothing.closed";
|
||
const sum = sent
|
||
? `<p id="aplogsum" class="st ok"><b class="smp">${P("mark")}</b> ${L("sent", { messageId: sent.messageId, time: almatyTime(sent.at) })}${open(sent.link)}</p>`
|
||
: reals.length ? `<p id="aplogsum" class="st ok">${L("realOnly")}</p>`
|
||
: `<p id="aplogsum" class="st off">${L(nothing, { time: c ? almatyTime(c.publishAt) : "" })}</p>`;
|
||
const pubRows = pubs.map((p) => `<li>${p.test ? `<b class="smp">${P("mark")}</b>` : `<b class="real">${L("real")}</b>`} ${esc(t(lang, "ap.channel." + p.channel))}, ${esc(p.date)}${p.messageId ? ", " + L("msgNo", { messageId: p.messageId, time: almatyTime(p.createdAt) }) : p.test ? "" : ", " + L("manual")}${open(p.link)}</li>`);
|
||
const evRows = events.map((e) => {
|
||
const v = { ...e, publishAt: e.publishAt ? almatyTime(e.publishAt) : "", sentAt: e.sentAt ? almatyTime(e.sentAt) : "", title: e.title ?? "" };
|
||
let s = P("k." + e.kind, v);
|
||
if (e.kind === "blocked") s += ": " + (e.problems ?? []).map((x) => esc(why(x))).join(" ");
|
||
return `<li>${esc(almatyTime(e.at))} — <b class="smp">${P("mark")}</b> ${s}${open(e.link)}</li>`;
|
||
});
|
||
const list = pubRows.length || evRows.length
|
||
? `${pubRows.length ? `<p>${L("h.pubs")}</p><ul id="appubs">${pubRows.join("")}</ul>` : ""}${evRows.length ? `<p>${L("h.events")}</p><ul id="apevents">${evRows.join("")}</ul>` : ""}`
|
||
: "";
|
||
return `${note}${choose}${card}
|
||
<h3 id="aplogh">${L("h.log")}</h3><div id="aplog">${sum}<p id="apcount">${L("count", { test: tests.length, real: reals.length })}</p>${list}</div>
|
||
<p><a href="/bot.html${q}">${L("toBot")}</a></p>`;
|
||
}
|