BRM-48: плашка выкладки на главной по-русски, собирается сервером

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Peppa 2026-11-16 23:29:02 +05:00
parent 595b8bf0fd
commit 9900e1818d
8 changed files with 76 additions and 35 deletions

View File

@ -336,8 +336,8 @@
"ui.mk.check.open": "not checked",
"ui.mk.check.yes": "confirmed",
"ui.mk.check.no": "rejected",
"deploy.title": "Staging update",
"deploy.none": "No updates after accepted tasks yet.",
"deploy.title": "Version update",
"deploy.none": "No updates yet: the first one will appear after the first task is accepted.",
"deploy.ok": "Success: the version was updated",
"deploy.failed": "The version could not be updated",
"deploy.after": "after task {task} “{title}”",

View File

@ -337,7 +337,7 @@
"ui.mk.check.yes": "расталды",
"ui.mk.check.no": "қабылданбады",
"deploy.title": "Тексеру нұсқасын жаңарту",
"deploy.none": "Қабылданған тапсырмалардан кейін жаңарту әлі болған жоқ.",
"deploy.none": "Жаңарту әлі болған жоқ: біріншісі бірінші тапсырма қабылданғаннан кейін пайда болады.",
"deploy.ok": "Сәтті: нұсқа жаңартылды",
"deploy.failed": "Нұсқаны жаңарту мүмкін болмады",
"deploy.after": "{task} «{title}» тапсырмасынан кейін",

View File

@ -337,7 +337,7 @@
"ui.mk.check.yes": "подтверждена",
"ui.mk.check.no": "отклонена",
"deploy.title": "Обновление версии для проверки",
"deploy.none": "Обновлений после принятых задач пока не было.",
"deploy.none": "Обновлений пока не было: первое появится после принятия первой задачи.",
"deploy.ok": "Успешно: версия обновлена",
"deploy.failed": "Не удалось обновить версию",
"deploy.after": "после задачи {task} «{title}»",

View File

@ -70,6 +70,17 @@ TBD - created by archiving change brm-31-staging-landing. Update Purpose after a
- **WHEN** следующая принятая задача выложена успешно
- **THEN** статус на главной снова «успешно»
#### Scenario: Плашка по-русски сразу при открытии (BRM-48)
- **GIVEN** главная открыта в браузере с английским языком
- **WHEN** страница загрузилась
- **THEN** плашка про обновление версии написана по-русски и видна без работы скриптов
- **AND** видны время по Алматы и номер с названием задачи
#### Scenario: Выкладок ещё не было (BRM-48)
- **GIVEN** ни одной выкладки ещё не было
- **WHEN** открыта главная
- **THEN** плашка объясняет, что первое обновление появится после принятия первой задачи
### Requirement: Статус меняет только скрипт выкладки
Запись статуса SHALL требовать ключ выкладки; без верного ключа запрос отклоняется.

View File

@ -1,5 +1,5 @@
<!doctype html>
<html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<html lang="<!--lang-->"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Бренд менеджер — версия для проверки</title>
<style>
body{font:16px/1.5 system-ui,sans-serif;max-width:820px;margin:auto;padding:16px;color:#222}
@ -11,7 +11,7 @@ li{margin:4px 0}small{color:#666}
<h1>Бренд менеджер</h1>
<p class="box">Это версия для проверки. Здесь можно посмотреть, что уже сделано в принятых задачах. Данные на ней демонстрационные, сообщения в Telegram и LinkedIn не отправляются.</p>
<div id="deploy" class="box" aria-live="polite"></div>
<div id="deploy" class="box" aria-live="polite"><!--deploy--></div>
<h2>Что это</h2>
<p>Помощник Татьяны Сафаровой по личному бренду: план публикаций, PR-возможности, сводка для владельца, обзор рынка и готовые документы о позиционировании. Для владельца бренда и тех, кто с ней работает.</p>
@ -51,31 +51,4 @@ li{margin:4px 0}small{color:#666}
<li>Откройте любой документ: он читается прямо в браузере.</li>
</ol>
<p><small>Если страница пустая или показывает ошибку — напишите об этом в комментарии к задаче.</small></p>
<script>
(async () => {
const el = document.getElementById("deploy");
const esc = (x) => String(x).replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
const lang = (navigator.language || "ru").slice(0, 2);
const h = { "x-lang": lang };
try {
const [{ texts }, st] = await Promise.all([
fetch("/api/texts", { headers: h }).then((r) => r.json()),
fetch("/api/deploy-status", { headers: h }).then((r) => r.json()),
]);
const f = (k, v = {}) => (texts[k] || k).replace(/\{(\w+)\}/g, (_, n) => esc(v[n] ?? ""));
const about = (r) => (r.task ? f("deploy.after", r) : "");
const parts = [`<b>${f("deploy.title")}</b>`];
if (!st.last) parts.push(f("deploy.none"));
else {
parts.push(`${f(st.last.status === "ok" ? "deploy.ok" : "deploy.failed")} ${about(st.last)}, ${f("deploy.at", { time: st.last.atText })}`);
if (st.last.status === "failed") {
if (st.last.reason) parts.push(f("deploy.reason", { reason: st.last.reason }));
parts.push(st.shown ? f("deploy.shown", { ...st.shown, time: st.shown.atText }) : f("deploy.shownNone"));
parts.push(f("deploy.next"));
}
}
el.innerHTML = parts.map((x, i) => (i ? "<br>" : "") + x).join("");
} catch { el.textContent = "Не удалось загрузить статус обновления. Обновите страницу."; }
})();
</script>
</body></html>

View File

@ -258,7 +258,7 @@ export function createApp({ file, oppsFile, metricsFile, telegram = createTelegr
// BRM-39: «Рынок» по умолчанию русский, другой язык — только по ?lang=
const marketLang = pickLang(new URLSearchParams(query).get("lang"));
if (req.method === "GET" && (url === "/" || url === "/index.html"))
return send(200, homePage(pageLang), "text/html");
return send(200, homePage(pickLang(new URLSearchParams(query).get("lang"), req.headers["x-lang"]), undefined, deploy.view()), "text/html");
const sm = url.match(/^\/design\/brand-visual\/([\w.-]+)$/);
if (req.method === "GET" && sm) {
const f = sampleFile(sm[1]);

View File

@ -79,12 +79,32 @@ export function docList(lang = "ru", status = readStatus()) {
}));
}
export function homePage(lang = "ru", status = readStatus()) {
// BRM-48: плашка про обновление версии собирается на сервере, чтобы текст был сразу и на нужном языке.
export function deployBox(lang, view) {
const last = view?.last;
const parts = [`<b>${esc(t(lang, "deploy.title"))}</b>`];
const about = (r) => (r.task ? " " + esc(t(lang, "deploy.after", { task: r.task, title: r.title })) : "");
if (!last) parts.push(esc(t(lang, "deploy.none")));
else {
parts.push(`${esc(t(lang, last.status === "ok" ? "deploy.ok" : "deploy.failed"))}${about(last)}, ${esc(t(lang, "deploy.at", { time: last.atText }))}`);
if (last.status === "failed") {
if (last.reason) parts.push(esc(t(lang, "deploy.reason", { reason: last.reason })));
const s = view.shown;
parts.push(s ? esc(t(lang, "deploy.shown", { task: s.task, title: s.title, time: s.atText })) : esc(t(lang, "deploy.shownNone")));
parts.push(esc(t(lang, "deploy.next")));
}
}
return parts.join("<br>");
}
export function homePage(lang = "ru", status = readStatus(), deployView = null) {
const docs = `<p>${esc(t(lang, "home.docs.note"))}</p>\n<ul>\n` + docList(lang, status)
.map((d) => `<li><a href="/docs/${d.name}">${esc(d.title)}</a> — <span class="st ${d.approved ? "ok" : "draft"}">${esc(d.label)}</span></li>`)
.join("\n") + "\n</ul>";
return fs.readFileSync(path.join(HERE, "../public/index.html"), "utf8")
.replace("<!--docs-->", docs)
.replace("<!--deploy-->", deployBox(lang, deployView))
.replace("<!--lang-->", lang)
.replace("<!--check-visual-->", `<li>${esc(t(lang, "home.check.visual"))}</li>`);
}

View File

@ -5,6 +5,7 @@ import os from "node:os";
import path from "node:path";
import { createApp } from "../src/server.js";
import { almatyTime } from "../src/deploy-status.js";
import { deployBox } from "../src/site.js";
async function withServer(fn, secret = "s3") {
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm32-")), "plan.json");
@ -56,3 +57,39 @@ test("BRM-32 Сценарий: чужой запрос и неверные да
test("BRM-32: без ключа на сервере запись закрыта", () => withServer(async (call) => {
assert.equal((await call("POST", "/api/deploy-status", { status: "ok" }, { "x-deploy-token": "" }))[0], 403);
}, ""));
test("BRM-48 Сценарий: пока выкладок не было — плашка по-русски объясняет, когда она появится", () => {
const html = deployBox("ru", { last: null, shown: null });
assert.match(html, /после принятия первой задачи/);
assert.doesNotMatch(html, /Staging|No updates/);
});
test("BRM-48 Сценарий: успех — время по Алматы, номер и название задачи", () => {
const rec = { status: "ok", task: "BRM-47", title: "Новая правка", at: "2026-11-16T09:05:00Z", atText: "16.11.2026 14:05" };
const html = deployBox("ru", { last: rec, shown: rec });
assert.match(html, /Успешно/);
assert.match(html, /BRM-47/);
assert.match(html, /Новая правка/);
assert.match(html, /16\.11\.2026 14:05 \(время по Алматы\)/);
});
test("BRM-48 Сценарий: сбой — причина простыми словами и прежняя версия", () => {
const ok = { status: "ok", task: "BRM-31", title: "Первая ссылка", atText: "15.11.2026 10:00" };
const bad = { status: "failed", task: "BRM-48", title: "Плашка", reason: "не удалось собрать новую версию", atText: "16.11.2026 15:00" };
const html = deployBox("ru", { last: bad, shown: ok });
assert.match(html, /Не удалось обновить версию/);
assert.match(html, /не удалось собрать новую версию/);
assert.match(html, /прежняя рабочая версия/);
});
test("BRM-48 Сценарий: главная в английском браузере остаётся русской", () => withServer(async () => {}).then(async () => {
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm48-")), "plan.json");
const srv = createApp({ file }).listen(0);
await new Promise((r) => srv.once("listening", r));
try {
const r = await fetch(`http://127.0.0.1:${srv.address().port}/`, { headers: { "accept-language": "en-US" } });
const body = await r.text();
assert.match(body, /Обновление версии для проверки/);
assert.match(body, /<html lang="ru">/);
} finally { srv.close(); }
}));