278 lines
19 KiB
JavaScript
278 lines
19 KiB
JavaScript
import test from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import fs from "node:fs";
|
||
import os from "node:os";
|
||
import path from "node:path";
|
||
import { fileURLToPath } from "node:url";
|
||
import { createApp } from "../src/server.js";
|
||
import { mockTelegram, createTelegram } from "../src/telegram.js";
|
||
import { TEXTS, LANGS } from "../src/i18n.js";
|
||
|
||
const PAGES = ["plan", "opportunities", "summary", "market", "channels", "strategy", "facts"];
|
||
const html = (p) => fs.readFileSync(`public/${p}.html`, "utf8");
|
||
const markup = (p) => html(p).split("<script>")[0].split("</style>")[1];
|
||
|
||
async function withServer(telegram, fn) {
|
||
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm33-")), "plan.json");
|
||
const srv = createApp({ file, telegram }).listen(0);
|
||
await new Promise((r) => srv.once("listening", r));
|
||
const get = async (u) => (await fetch(`http://127.0.0.1:${srv.address().port}${u}`)).json();
|
||
try { await fn(get, `http://127.0.0.1:${srv.address().port}`); } finally { srv.close(); }
|
||
}
|
||
|
||
test("Подписи на странице плана: у полей формы есть подписи, на кнопках текст", () => {
|
||
const ru = TEXTS.ru;
|
||
assert.equal(ru["ui.plan.start"], "Дата старта плана");
|
||
for (const k of ["ui.plan.start", "ui.plan.f.title", "ui.plan.f.desc", "ui.plan.f.rubric", "ui.plan.f.date", "ui.plan.save", "ui.plan.clear"])
|
||
assert.ok(markup("plan").includes(`data-t="${k}"`), k);
|
||
});
|
||
|
||
for (const p of PAGES) {
|
||
test(`Подписи полей и кнопок: ${p} — каждое поле подписано, у каждой кнопки текст и подсказка`, () => {
|
||
const m = markup(p);
|
||
for (const [tag] of m.matchAll(/<(input|select|textarea)\b[^>]*>/g)) {
|
||
if (/type="hidden"/.test(tag)) continue;
|
||
const before = m.slice(0, m.indexOf(tag));
|
||
const after = m.slice(m.indexOf(tag) + tag.length);
|
||
const labelled = /<label[^>]*><span (data-t="[\w.]+"|id="\w+")><\/span>$/.test(before) || (/type="checkbox"/.test(tag) && /^<span data-t=/.test(after));
|
||
assert.ok(labelled, `нет подписи: ${tag}`);
|
||
}
|
||
for (const [tag] of m.matchAll(/<button\b[^>]*>/g)) assert.match(tag, /data-t="[\w.]+"/, `кнопка без текста: ${tag}`);
|
||
for (const [tag] of m.matchAll(/<button\b[^>]*>/g)) if (!/id="l\w+"/.test(tag)) assert.match(tag, /data-tip="[\w.]+"/, `кнопка без подсказки: ${tag}`);
|
||
});
|
||
|
||
test(`Текста для подписи нет в переводах: ${p} — все ключи есть на трёх языках, текста в разметке нет`, () => {
|
||
const src = html(p);
|
||
assert.doesNotMatch(src, /[А-Яа-яЁёӘәҒғҚқҢңӨөҰұҮүҺһІі]/, "текст вписан в страницу, а не в переводы");
|
||
const keys = new Set();
|
||
for (const [, k] of src.matchAll(/data-(?:t|ph|tip)="([\w.]+)"/g)) keys.add(k);
|
||
for (const [, k] of src.matchAll(/\bt[x]?\(\s*"([\w.]+)"\s*[,)]/g)) keys.add(k);
|
||
for (const [, a, b] of src.matchAll(/\?\s*"((?:ui|ap|asset|letter)\.[\w.]+)"\s*:\s*"((?:ui|ap|asset|letter)\.[\w.]+)"/g)) { keys.add(a); keys.add(b); }
|
||
assert.ok(keys.size > 10);
|
||
for (const l of LANGS) for (const k of keys) if (!k.endsWith(".")) assert.ok(TEXTS[l][k], `${l}: ${k}`);
|
||
});
|
||
}
|
||
|
||
test("Переводы: одинаковый набор ключей на русском, казахском и английском", () => {
|
||
for (const l of LANGS) assert.deepEqual(Object.keys(TEXTS[l]).sort(), Object.keys(TEXTS.ru).sort(), l);
|
||
});
|
||
|
||
test("Нет карточек PR-возможностей / Фильтр ничего не нашёл: подсказки пустого списка", () => {
|
||
const src = html("opportunities");
|
||
assert.match(src, /\$\("filter"\)\.value\?"ui\.opp\.filterEmpty":"ui\.opp\.empty"/);
|
||
assert.equal(TEXTS.ru["ui.opp.empty"], "Карточек пока нет. Заполните форму ниже и нажмите «Сохранить карточку» — первая карточка появится здесь.");
|
||
assert.match(TEXTS.ru["ui.opp.filterEmpty"], /На этой стадии карточек нет/);
|
||
for (const k of ["ui.plan.sumEmpty", "ui.plan.unschedEmpty", "ui.plan.calEmpty", "ui.plan.filterEmpty"]) assert.ok(html("plan").includes(k), k);
|
||
for (const k of ["ui.sum.metricsEmpty", "ui.sum.textEmpty", "ui.sum.logEmpty"]) assert.ok(html("summary").includes(k), k);
|
||
});
|
||
|
||
test("Отправка выключена: без доступов к Telegram статус false, пометка рядом с «Сформировать»", () =>
|
||
withServer(createTelegram({ token: "", chatId: "" }), async (get, base) => {
|
||
assert.deepEqual(await get("/api/summary/status"), { telegram: false, missing: "key", paused: false });
|
||
const m = markup("summary");
|
||
assert.ok(m.indexOf('id="tg"') > m.indexOf('id="preview"') && m.indexOf('id="tg"') - m.indexOf('id="preview"') < 400);
|
||
assert.match(m, /<button id="send" class="off" aria-disabled="true"/, "кнопка серая, но нажимается (BRM-61)");
|
||
assert.doesNotMatch(m, /<button id="send"[^>]*\sdisabled/);
|
||
assert.match(m, /<p id="tg" data-t="ui.sum.tgOff"><\/p>/, "пометка не скрыта и есть в разметке");
|
||
const page = await (await fetch(`${base}/summary.html`)).text();
|
||
assert.match(page, /id="tg"[^>]*>Отправка в Telegram выключена/);
|
||
assert.match(TEXTS.ru["ui.sum.tgOff"], /Отправка в Telegram выключена/);
|
||
}));
|
||
|
||
test("Отправка включена: Telegram подключён — статус true", () =>
|
||
withServer(mockTelegram(), async (get) => assert.deepEqual(await get("/api/summary/status"), { telegram: true, missing: null, paused: false })));
|
||
|
||
test("Журнал пуст: пояснение под заголовком и подсказка в пустом журнале", () =>
|
||
withServer(mockTelegram(), async (get) => {
|
||
assert.deepEqual(await get("/api/summary/log"), []);
|
||
const m = markup("summary");
|
||
assert.match(m, /data-t="ui\.sum\.hLog"><\/h2><p class="hint" data-t="ui\.sum\.logIntro">/);
|
||
assert.equal(TEXTS.ru["ui.sum.logEmpty"], "Пока ни одной отправки не было.");
|
||
assert.match(TEXTS.ru["ui.sum.logIntro"], /время, результат и текст/);
|
||
}));
|
||
|
||
test("В журнале есть записи: после отправки в журнале запись с результатом «отправлено»", async () => {
|
||
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm33-")), "plan.json");
|
||
const srv = createApp({ file, telegram: mockTelegram() }).listen(0);
|
||
await new Promise((r) => srv.once("listening", r));
|
||
const base = `http://127.0.0.1:${srv.address().port}`;
|
||
try {
|
||
const r = await fetch(base + "/api/summary/send", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ period: "week", date: "2026-11-16" }) });
|
||
assert.equal(r.status, 200);
|
||
const log = await (await fetch(base + "/api/summary/log")).json();
|
||
assert.equal(log.length, 1);
|
||
assert.equal(log[0].result, "published");
|
||
assert.ok(log[0].time);
|
||
assert.equal(TEXTS.ru["ui.sum.log.published"], "отправлено");
|
||
assert.match(html("summary"), /e\.off\?"off"/, "запись о выключенной отправке видна словами (BRM-61)");
|
||
assert.equal(TEXTS.ru["ui.sum.log.off"], "не отправлено: на этой версии отправка выключена");
|
||
} finally { srv.close(); }
|
||
});
|
||
|
||
// BRM-36: подписи видны сразу при открытии страницы.
|
||
async function page(u, lang = "ru") {
|
||
const file = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "brm36-")), "plan.json");
|
||
const srv = createApp({ file, telegram: mockTelegram() }).listen(0);
|
||
await new Promise((r) => srv.once("listening", r));
|
||
try {
|
||
const r = await fetch(`http://127.0.0.1:${srv.address().port}${u}`, { headers: { "accept-language": lang } });
|
||
assert.equal(r.status, 200);
|
||
return (await r.text()).split("<script>")[0];
|
||
} finally { srv.close(); }
|
||
}
|
||
|
||
for (const [u, label, button] of [
|
||
["/plan.html", "Дата старта плана", "Сохранить идею"],
|
||
["/opportunities.html", "Организатор", "Сохранить карточку"],
|
||
["/summary.html", "Время отправки недельной сводки", "Сформировать"],
|
||
]) {
|
||
test(`Страница приходит с подписями: ${u} — у каждого поля подпись, у каждой кнопки текст`, async () => {
|
||
const m = await page(u);
|
||
assert.doesNotMatch(m, /data-t="[\w.]+"[^>]*><\//, "остался пустой текст");
|
||
const labels = [...m.matchAll(/<label[^>]*>(.*?)<\/label>/gs)];
|
||
assert.ok(labels.length >= 5);
|
||
for (const [all, inner] of labels) assert.match(inner, /<span[^>]*>[^<]+<\/span>/, `поле без подписи: ${all}`);
|
||
const fields = [...m.matchAll(/<(?:input|select|textarea)\b[^>]*>/g)].filter(([x]) => !/type="hidden"/.test(x));
|
||
assert.equal(fields.length, labels.length, "каждое поле стоит внутри своей подписи");
|
||
const buttons = [...m.matchAll(/<button\b[^>]*>([^<]*)<\/button>/g)];
|
||
assert.equal(buttons.length, (m.match(/<button\b/g) ?? []).length);
|
||
for (const [all, text] of buttons) assert.ok(text.trim(), `кнопка без текста: ${all}`);
|
||
assert.ok(m.includes(`">${label}</span><`), label);
|
||
assert.match(m, new RegExp(`<button\\b[^>]*>${button}</button>`));
|
||
assert.match(m, /<title[^>]*>[^<]+<\/title>/);
|
||
});
|
||
}
|
||
|
||
test("Подсказка кнопки и подсказка в поле: на странице плана есть подсказка при наведении и подсказка внутри поля", async () => {
|
||
const m = await page("/plan.html");
|
||
assert.ok(m.includes(`title="${TEXTS.ru["ui.plan.saveTip"]}">Сохранить идею</button>`));
|
||
assert.match(m, new RegExp(`<input id="title" data-ph="ui.plan.f.titlePh"[^>]* placeholder="${TEXTS.ru["ui.plan.f.titlePh"]}">`));
|
||
for (const u of ["/plan.html", "/opportunities.html", "/summary.html"])
|
||
for (const [tag] of (await page(u)).matchAll(/<button\b[^>]*data-tip=[^>]*>/g)) assert.match(tag, / title="[^"]+"/, tag);
|
||
});
|
||
|
||
test("Язык из адреса страницы: /plan.html?lang=en — подписи по-английски", async () => {
|
||
const m = await page("/plan.html?lang=en");
|
||
assert.ok(m.includes(">Plan start date</span>"));
|
||
assert.match(m, /<html lang="en">/);
|
||
});
|
||
|
||
test("Неизвестный язык: французский браузер получает подписи на русском", async () => {
|
||
const m = await page("/summary.html", "fr-FR,fr;q=0.9");
|
||
assert.ok(m.includes(">Время отправки недельной сводки</span>"));
|
||
assert.match(m, /<html lang="ru">/);
|
||
});
|
||
|
||
// BRM-39: «Рынок» по-русски, даже если браузер английский.
|
||
test("Рынок: английский браузер — страница всё равно русская; ?lang=en — английская", async () => {
|
||
const ru = await page("/market.html", "en-US");
|
||
assert.match(ru, /<h1[^>]*>Рынок<\/h1>/);
|
||
assert.match(ru, /Высокая — несколько/);
|
||
const en = await page("/market.html?lang=en", "ru");
|
||
assert.match(en, /<h1[^>]*>Market<\/h1>/);
|
||
assert.match(fs.readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "../public/market.html"), "utf8"), /get\("lang"\)\|\|"ru"/);
|
||
});
|
||
|
||
// BRM-72
|
||
test("Сводка: состояние рассылки — после остановки /api/summary/status отдаёт paused", async () => {
|
||
await withServer(mockTelegram(), async (get, base) => {
|
||
assert.equal((await get("/api/summary/status")).paused, false);
|
||
await fetch(base + "/api/summary/stop", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal((await get("/api/summary/status")).paused, true);
|
||
await fetch(base + "/api/summary/resume", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal((await get("/api/summary/status")).paused, false);
|
||
});
|
||
});
|
||
|
||
test("Письмо и сводка: у кнопок есть пояснения и строка состояния", () => {
|
||
const o = html("opportunities"), s = html("summary");
|
||
for (const k of ["sendNote", "markNote", "copyNote", "letter.pick", "letter.btnWhy.pick", "letter.why.dirty", "letter.why.draft", "letter.btnWhy.approve", "letter.btnWhy.save"]) assert.ok(o.includes(k), k);
|
||
for (const k of ["ui.sum.schedOn", "ui.sum.schedOff", "ui.sum.s.stopWhy", "ui.sum.s.resumeWhy", "ui.sum.sendWhy"]) assert.ok(s.includes(k), k);
|
||
assert.match(TEXTS.ru["letter.sendNote"], /не отправляется/);
|
||
// BRM-81: до выбора карточки — одна фраза, пустых «Стадия»/«Кому» нет, кнопки неактивны с причиной
|
||
assert.match(o, /<section id="letter">/);
|
||
assert.match(o, /id="lstagebox" hidden/);
|
||
assert.match(o, /id="ltobox" hidden/);
|
||
// BRM-101: подписи «Стадия»/«Кому» подставляет скрипт, в ответе сервера их текста нет
|
||
assert.doesNotMatch(o, /<div id="lstagebox"[^>]*><span[^>]*data-t/);
|
||
assert.doesNotMatch(o, /<div id="ltobox"[^>]*><span[^>]*data-t/);
|
||
assert.match(o, /id="lsend" disabled/);
|
||
assert.match(TEXTS.ru["letter.pick"], /Выберите карточку и нажмите «Подготовить письмо»/);
|
||
assert.equal(TEXTS.ru["ui.sum.schedOn"], "Отправка по расписанию включена.");
|
||
assert.equal(TEXTS.ru["ui.sum.schedOff"], "Отправка по расписанию приостановлена.");
|
||
});
|
||
|
||
// BRM-75: строка состояния рассылки видна в ответе сервера и совпадает после «перезагрузки».
|
||
test("Сводка: строка состояния рассылки приходит с сервера и меняется после остановки", async () => {
|
||
await withServer(mockTelegram(), async (_get, base) => {
|
||
const sched = async () => (await (await fetch(base + "/summary.html?lang=ru")).text()).match(/<p id="sched"[^>]*>([^<]*)<\/p>/)[1];
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOn"]);
|
||
await fetch(base + "/api/summary/stop", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOff"]);
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOff"]);
|
||
await fetch(base + "/api/summary/resume", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOn"]);
|
||
});
|
||
});
|
||
|
||
// BRM-95: пока Telegram выключен, строка не говорит просто «включена».
|
||
test("Сводка: при выключенном Telegram строка поясняет, что включено только расписание", async () => {
|
||
await withServer(createTelegram({ token: "", chatId: "" }), async (_get, base) => {
|
||
const sched = async () => (await (await fetch(base + "/summary.html?lang=ru")).text()).match(/<p id="sched"[^>]*>([^<]*)<\/p>/)[1];
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOnNoTg"]);
|
||
assert.match(TEXTS.ru["ui.sum.schedOnNoTg"], /сводки в Telegram не уходят/);
|
||
await fetch(base + "/api/summary/stop", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOff"]);
|
||
await fetch(base + "/api/summary/resume", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" });
|
||
assert.equal(await sched(), TEXTS.ru["ui.sum.schedOnNoTg"]);
|
||
});
|
||
});
|
||
|
||
// BRM-89: каждое поле подписано и подсказано, списки выбора заполнены сразу, обязательные отмечены одинаково.
|
||
const FORMS = ["/plan.html", "/summary.html", "/opportunities.html"];
|
||
const before = (m) => m.split("<script>")[0];
|
||
|
||
for (const u of FORMS)
|
||
test(`Подсказка у каждого поля: ${u} — у текстового поля подсказка внутри, у даты, времени и списка — при наведении`, async () => {
|
||
const m = before(await page(u));
|
||
for (const [tag] of m.matchAll(/<(input|select|textarea)\b[^>]*>/g)) {
|
||
if (/type="hidden"/.test(tag)) continue;
|
||
const ph = !/<select|type="(date|time|checkbox)"/.test(tag);
|
||
assert.match(tag, ph ? / placeholder="[^"]+"/ : / title="[^"]+"/, tag);
|
||
}
|
||
});
|
||
|
||
for (const [u, list, option] of [
|
||
["/plan.html", "rubric", "Полезные советы"],
|
||
["/plan.html", "filter", "на согласовании"],
|
||
["/opportunities.html", "filter", "Ждём ответа"],
|
||
["/opportunities.html", "stage", "Идея"],
|
||
["/opportunities.html", "type", "подкаст"],
|
||
["/summary.html", "period", "Неделя"],
|
||
])
|
||
test(`Список выбора заполнен сразу: ${u} #${list} — «${option}»`, async () => {
|
||
const m = before(await page(u));
|
||
const sel = m.match(new RegExp(`<select id="${list}"[^>]*>([\\s\\S]*?)</select>`))?.[1] ?? "";
|
||
assert.ok(sel.includes(`>${option}</option>`), sel);
|
||
for (const [, l] of sel.matchAll(/>([^<]*)<\/option>/g)) assert.match(l, /^[А-Яа-яЁё0-9 /—-]+$/, `не русское название: ${l}`);
|
||
});
|
||
|
||
test("Обязательные поля отмечены одинаково: «(обязательно)» в подписи и признак у поля", async () => {
|
||
const req = { "/plan.html": ["title"], "/summary.html": ["name", "value"], "/opportunities.html": ["title", "lsubject", "lbody"] };
|
||
for (const u of FORMS) {
|
||
const m = before(await page(u));
|
||
const marked = [...m.matchAll(/<span data-t="[\w.]+">([^<]*)<\/span><(?:input|textarea|select) id="(\w+)"([^>]*)>/g)];
|
||
const got = marked.filter(([, l]) => l.endsWith("(обязательно)")).map(([, , id]) => id);
|
||
assert.deepEqual(got.sort(), req[u].sort(), u);
|
||
for (const [, l, id, rest] of marked) assert.equal(/aria-required="true"/.test(rest), l.endsWith("(обязательно)"), `${u} #${id}`);
|
||
}
|
||
const m = await page("/opportunities.html");
|
||
for (const l of ["Название мероприятия (обязательно)", "Тема письма (обязательно)", "Текст письма (обязательно)"]) assert.ok(m.includes(`>${l}</span>`), l);
|
||
});
|
||
|
||
test("Стадии на другом языке: подпись по-английски, значение прежнее", async () => {
|
||
const m = before(await page("/opportunities.html?lang=en"));
|
||
assert.ok(m.includes('<option value="Ждём ответа">Waiting for a reply</option>'));
|
||
assert.ok(m.includes('<option value="подкаст">podcast</option>'));
|
||
});
|