brendmanager/test/letters.test.js
2026-11-17 18:41:30 +05:00

188 lines
11 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.

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 { createApp } from "../src/server.js";
import { LANGS, TEXTS } from "../src/i18n.js";
const CODE = "tanya-2026";
const CARD = { title: "Podcast Hub", organizer: "Анна", topic: "Личный бренд эксперта", deadline: "2026-12-01", email: "anna@podcasthub.kz" };
async function withServer(fn, { dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm20-")), ownerCode = CODE } = {}) {
const srv = createApp({ file: path.join(dir, "plan.json"), ownerCode }).listen(0);
await new Promise((r) => srv.once("listening", r));
const base = `http://127.0.0.1:${srv.address().port}`;
const call = async (m, u, b, lang = "ru") => {
const r = await fetch(base + u, { method: m, headers: { "content-type": "application/json", "x-lang": lang }, body: b && JSON.stringify(b) });
return [r.status, await r.json()];
};
const card = async (extra = {}) => (await call("POST", "/api/opportunities", { ...CARD, ...extra }))[1].id;
const letter = async (id) => (await call("GET", `/api/opportunities/${id}/letter`))[1].letter;
const approved = async (extra) => {
const id = await card(extra);
const { letter: l } = (await call("POST", `/api/opportunities/${id}/letter`))[1];
const [c] = await call("POST", `/api/opportunities/${id}/letter/approve`, { code: CODE, subject: l.subject, body: l.body });
assert.equal(c, 200);
return id;
};
try { await fn({ call, card, letter, approved }); } finally { srv.close(); }
}
test("Сценарий: Адрес сохранён / Несколько адресов", () => withServer(async ({ call, card }) => {
const id = await card();
assert.equal((await call("GET", `/api/opportunities/${id}`))[1].email, "anna@podcasthub.kz");
const [c, d] = await call("PUT", `/api/opportunities/${id}`, { email: "a@x.kz, b@x.kz" });
assert.equal(c, 400); assert.equal(d.error, TEXTS.ru["err.email"]);
assert.equal((await call("GET", `/api/opportunities/${id}`))[1].email, "anna@podcasthub.kz");
}));
test("Сценарий: Черновик создан", () => withServer(async ({ call, card }) => {
const id = await card();
assert.equal((await call("GET", `/api/opportunities/${id}/letter`))[1].letter, null);
const [c, { letter: l }] = await call("POST", `/api/opportunities/${id}/letter`);
assert.equal(c, 200);
assert.equal(l.status, "draft"); assert.equal(l.to, "anna@podcasthub.kz"); assert.equal(l.mailto, null);
for (const s of ["Podcast Hub", "Анна", "Личный бренд эксперта", "01.12.2026"]) assert.ok(l.body.includes(s), s);
assert.ok(l.subject.includes("Podcast Hub"));
}));
test("Сценарий: Повторная подготовка", () => withServer(async ({ call, card }) => {
const id = await card();
await call("POST", `/api/opportunities/${id}/letter`);
await call("PUT", `/api/opportunities/${id}/letter`, { subject: "Тема", body: "Мой текст" });
assert.equal((await call("POST", `/api/opportunities/${id}/letter`))[1].letter.body, "Мой текст");
}));
test("Сценарий: Не хватает данных", () => withServer(async ({ call, card, letter }) => {
for (const [extra, missing, key] of [
[{ organizer: "" }, ["organizer"], "err.missing.organizer"],
[{ email: "" }, ["email"], "err.missing.email"],
[{ organizer: "", email: "" }, ["organizer", "email"], "err.missing.both"],
]) {
const id = await card(extra);
const [c, d] = await call("POST", `/api/opportunities/${id}/letter`);
assert.equal(c, 400); assert.deepEqual(d.missing, missing); assert.equal(d.error, TEXTS.ru[key]);
assert.equal(await letter(id), null);
}
assert.equal((await call("POST", "/api/opportunities/999/letter"))[0], 404);
}));
test("Сценарий: Правка сохранена / Пустой текст", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "brm20-"));
let id;
await withServer(async ({ call, card }) => {
id = await card();
await call("POST", `/api/opportunities/${id}/letter`);
assert.equal((await call("PUT", `/api/opportunities/${id}/letter`, { subject: "Тема", body: "Здравствуйте, Анна! Новый текст." }))[0], 200);
assert.equal((await call("PUT", `/api/opportunities/${id}/letter`, { subject: "Тема", body: " " }))[0], 400);
}, { dir });
await withServer(async ({ letter }) => {
assert.equal((await letter(id)).body, "Здравствуйте, Анна! Новый текст.");
}, { dir });
});
test("Сценарий: Одобрение", () => withServer(async ({ approved, letter }) => {
const l = await letter(await approved());
assert.equal(l.status, "approved");
assert.ok(Math.abs(Date.now() - Date.parse(l.approvedAt)) < 60_000);
assert.ok(l.mailto.startsWith("mailto:anna%40podcasthub.kz?subject="));
assert.ok(!decodeURIComponent(l.mailto.split("?")[0]).includes(","));
}));
test("Сценарий: Чужой человек не может одобрить", () => withServer(async ({ call, card, letter }) => {
const id = await card();
const { letter: l } = (await call("POST", `/api/opportunities/${id}/letter`))[1];
for (const code of ["угадаю", "", undefined]) {
const [c, d] = await call("POST", `/api/opportunities/${id}/letter/approve`, { code, subject: l.subject, body: l.body });
assert.equal(c, 403); assert.equal(d.error, TEXTS.ru["err.wrongCode"]);
}
assert.equal((await letter(id)).status, "draft");
}));
test("Сценарий: Одобряется только прочитанный текст", () => withServer(async ({ call, card, letter }) => {
const id = await card();
await call("POST", `/api/opportunities/${id}/letter`);
assert.equal((await call("POST", `/api/opportunities/${id}/letter/approve`, { code: CODE, subject: "Другая", body: "Другой" }))[0], 409);
assert.equal((await letter(id)).status, "draft");
}));
test("Сценарий: Правка сбрасывает одобрение", () => withServer(async ({ call, approved, letter }) => {
const id = await approved();
const before = await letter(id);
await call("PUT", `/api/opportunities/${id}/letter`, { subject: before.subject, body: before.body });
assert.equal((await letter(id)).status, "approved", "сохранение без правок одобрение не трогает");
await call("PUT", `/api/opportunities/${id}/letter`, { subject: before.subject, body: before.body + "\nP.S." });
const l = await letter(id);
assert.equal(l.status, "draft"); assert.equal(l.approvedAt, null); assert.equal(l.mailto, null);
assert.equal((await call("POST", `/api/opportunities/${id}/letter/sent`, { code: CODE }))[0], 409);
}));
test("Сценарий: Смена адреса сбрасывает одобрение", () => withServer(async ({ call, approved, letter }) => {
const id = await approved();
await call("PUT", `/api/opportunities/${id}`, { stage: "Ждём ответа" });
assert.equal((await letter(id)).status, "approved", "правка других полей карточки одобрение не трогает");
await call("PUT", `/api/opportunities/${id}`, { email: "team@podcasthub.kz" });
const l = await letter(id);
assert.equal(l.to, "team@podcasthub.kz"); assert.equal(l.status, "draft");
}));
test("Сценарий: Отправка одобренного письма", () => withServer(async ({ call, approved, letter }) => {
const id = await approved();
assert.equal((await call("POST", `/api/opportunities/${id}/letter/sent`, { code: "не тот код" }))[0], 403);
assert.equal((await letter(id)).status, "approved");
assert.equal((await call("POST", `/api/opportunities/${id}/letter/sent`, { code: CODE }))[0], 200);
const l = await letter(id);
assert.equal(l.status, "sent"); assert.ok(l.sentAt);
}));
test("Сценарий: Без одобрения отправить нельзя", () => withServer(async ({ call, card, letter }) => {
const id = await card();
await call("POST", `/api/opportunities/${id}/letter`);
const [c, d] = await call("POST", `/api/opportunities/${id}/letter/sent`, { code: CODE });
assert.equal(c, 409); assert.equal(d.error, TEXTS.ru["err.notApproved"]);
const l = await letter(id);
assert.equal(l.status, "draft"); assert.equal(l.mailto, null);
}));
test("Сценарий: Отправленное письмо не меняется", () => withServer(async ({ call, approved, letter }) => {
const id = await approved();
await call("POST", `/api/opportunities/${id}/letter/sent`, { code: CODE });
const before = await letter(id);
assert.equal((await call("PUT", `/api/opportunities/${id}/letter`, { subject: "Новая", body: "Новый" }))[0], 409);
assert.equal((await call("POST", `/api/opportunities/${id}/letter/approve`, { code: CODE, subject: before.subject, body: before.body }))[0], 409);
await call("PUT", `/api/opportunities/${id}`, { email: "other@podcasthub.kz" });
assert.deepEqual(await letter(id), before);
}));
test("Сценарий: код владельца задаётся при первом одобрении, если не задан заранее", () => withServer(async ({ call, card, letter }) => {
const id = await card();
const { letter: l, codeSet } = (await call("POST", `/api/opportunities/${id}/letter`))[1];
assert.equal(codeSet, false);
const seen = { subject: l.subject, body: l.body };
assert.equal((await call("POST", `/api/opportunities/${id}/letter/approve`, { code: "123", ...seen }))[0], 400);
assert.equal((await call("POST", `/api/opportunities/${id}/letter/approve`, { code: "мой-код-1", ...seen }))[0], 200);
await call("PUT", `/api/opportunities/${id}/letter`, { subject: l.subject, body: "Правка" });
assert.equal((await call("POST", `/api/opportunities/${id}/letter/approve`, { code: "чужой-код", subject: l.subject, body: "Правка" }))[0], 403);
assert.equal((await letter(id)).status, "draft");
}, { ownerCode: null }));
test("Сценарий: удаление карточки удаляет письмо; тексты на трёх языках", () => withServer(async ({ call, card }) => {
const id = await card();
await call("POST", `/api/opportunities/${id}/letter`);
await call("DELETE", `/api/opportunities/${id}`);
assert.equal((await call("GET", `/api/opportunities/${id}/letter`, undefined, "en"))[1].error, TEXTS.en["err.cardNotFound"]);
assert.equal((await call("GET", "/api/texts", undefined, "kk"))[1].texts["letter.approve"], "Мақұлдау");
const keys = Object.keys(TEXTS.ru).sort();
for (const l of LANGS) assert.deepEqual(Object.keys(TEXTS[l]).sort(), keys, l);
const html = fs.readFileSync(new URL("../public/opportunities.html", import.meta.url), "utf8");
for (const [, k] of html.matchAll(/data-(?:t|ph)="([^"]+)"/g)) assert.ok(TEXTS.ru[k], k);
for (const [, k] of html.matchAll(/\bt\("([a-zA-Z.]+)"/g)) if (!k.endsWith(".")) assert.ok(TEXTS.ru[k], k);
}));
test("BRM-80: в словах про одобрение письма нет «код», «секретное», «токен»", () => {
for (const lang of ["ru", "kk", "en"]) for (const k of ["letter.code", "letter.codeHint", "letter.codeHintNew", "err.wrongCode", "err.shortCode"]) {
assert.doesNotMatch(TEXTS[lang][k], /код|секретн|токен|құпия|secret|token|\bcode\b/i, `${lang} ${k}`);
}
});