171 lines
7.6 KiB
JavaScript
171 lines
7.6 KiB
JavaScript
import { test, before } from "node:test";
|
||
import assert from "node:assert/strict";
|
||
import { once } from "node:events";
|
||
import { join } from "node:path";
|
||
import ExcelJS from "exceljs";
|
||
import { buildWorkbook } from "../src/finmodel/write.js";
|
||
import { valueAt } from "../src/finmodel/evaluate.js";
|
||
import { exampleInputs, sheetNames } from "../src/finmodel/model.js";
|
||
import { buildFinmodelFiles } from "../src/finmodel/build.js";
|
||
import { instructionDocx, licenseDocx } from "../src/finmodel/docs.js";
|
||
import { createApp } from "../src/server.js";
|
||
import { createBot } from "../src/bot.js";
|
||
import { Store } from "../src/store.js";
|
||
import { mockTelegram, testConfig, tmp } from "./helpers.js";
|
||
import { readFile } from "node:fs/promises";
|
||
import { inflateRawSync } from "node:zlib";
|
||
|
||
const CYR = /[Ѐ-ӿ]/;
|
||
const EN = sheetNames("en");
|
||
const RU = sheetNames("ru");
|
||
|
||
test("Сценарий: EN-модель — листы, подписи и формулы без кириллицы и «битых» символов", async () => {
|
||
for (const kind of ["example", "empty"]) {
|
||
const { workbook, result } = await buildWorkbook(kind, "en");
|
||
assert.deepEqual(result.errors, []);
|
||
const texts = [];
|
||
workbook.eachSheet((ws) => {
|
||
texts.push(ws.name);
|
||
ws.eachRow((row) => row.eachCell((c) => texts.push(typeof c.value === "object" && c.value ? (c.value.formula ?? "") : String(c.value))));
|
||
});
|
||
assert.deepEqual(workbook.worksheets.map((w) => w.name), Object.values(EN));
|
||
assert.deepEqual(texts.filter((t) => CYR.test(t) || t.includes("<22>")), []);
|
||
assert.equal(valueAt(result, EN.balance, "B18"), "OK");
|
||
}
|
||
});
|
||
|
||
test("Сценарий: на одинаковых вводах EN и RU считают одно и то же", async () => {
|
||
const inputs = exampleInputs("ru");
|
||
const ru = (await buildWorkbook("example", "ru", inputs)).result;
|
||
const en = (await buildWorkbook("example", "en", inputs)).result;
|
||
for (const key of Object.keys(RU)) {
|
||
if (key === "guide") continue;
|
||
const a = ru.values.get(RU[key]);
|
||
const b = en.values.get(EN[key]);
|
||
for (const [addr, v] of a) {
|
||
if (typeof v === "number") assert.equal(b.get(addr), v, `${key}!${addr}`);
|
||
}
|
||
}
|
||
});
|
||
|
||
test("Граница: пустая EN-версия — «not paid back» и «n/a» вместо русских слов", async () => {
|
||
const { result } = await buildWorkbook("empty", "en");
|
||
assert.equal(valueAt(result, EN.payback, "B10"), "not paid back");
|
||
});
|
||
|
||
test("Сценарий: EN-инструкция и лицензия без кириллицы", async () => {
|
||
for (const buf of [await instructionDocx("en"), await licenseDocx("en")]) {
|
||
// docx — zip; document.xml сжат deflate, ищем его локальную запись.
|
||
const xml = readZipEntry(buf, "word/document.xml");
|
||
assert.ok(xml.length > 100);
|
||
assert.doesNotMatch(xml, CYR);
|
||
}
|
||
});
|
||
|
||
function readZipEntry(buf, name) {
|
||
let i = 0;
|
||
while ((i = buf.indexOf(Buffer.from([0x50, 0x4b, 0x03, 0x04]), i)) !== -1) {
|
||
const method = buf.readUInt16LE(i + 8);
|
||
const csize = buf.readUInt32LE(i + 18);
|
||
const nlen = buf.readUInt16LE(i + 26);
|
||
const xlen = buf.readUInt16LE(i + 28);
|
||
const fname = buf.toString("utf8", i + 30, i + 30 + nlen);
|
||
const start = i + 30 + nlen + xlen;
|
||
if (fname === name && csize > 0) return (method === 8 ? inflateRawSync(buf.subarray(start, start + csize)) : buf.subarray(start, start + csize)).toString("utf8");
|
||
i = start;
|
||
}
|
||
return "";
|
||
}
|
||
|
||
let productDir;
|
||
let imgDir;
|
||
before(async () => {
|
||
productDir = await tmp();
|
||
imgDir = await tmp();
|
||
await buildFinmodelFiles({ productDir, imgDir });
|
||
});
|
||
|
||
test("Сценарий: файлы EN лежат отдельно, скриншоты EN без кириллицы", async () => {
|
||
const wb = new ExcelJS.Workbook();
|
||
await wb.xlsx.readFile(join(productDir, "en", "finmodel-example.xlsx"));
|
||
assert.equal(wb.worksheets.length, 12);
|
||
assert.equal(wb.worksheets[0].name, "Guide");
|
||
for (const f of ["dashboard-en.svg", "pnl-en.svg", "assumptions-en.svg"]) assert.doesNotMatch(await readFile(join(imgDir, f), "utf8"), CYR);
|
||
});
|
||
|
||
async function withServer(config, fn) {
|
||
const server = createApp(config).listen(0);
|
||
await once(server, "listening");
|
||
try {
|
||
await fn(`http://127.0.0.1:${server.address().port}`);
|
||
} finally {
|
||
server.close();
|
||
}
|
||
}
|
||
|
||
test("Сценарий: EN-лендинг — английский текст, цена в $, без ₸ и кириллицы, кнопка Coming soon", async () => {
|
||
await withServer(testConfig(), async (base) => {
|
||
const html = await (await fetch(`${base}/en`)).text();
|
||
assert.match(html, /<html lang="en">/);
|
||
assert.match(html, /\$19/);
|
||
assert.doesNotMatch(html, /₸/);
|
||
assert.doesNotMatch(html, CYR);
|
||
assert.match(html, /Coming soon/);
|
||
assert.doesNotMatch(html, /t\.me/);
|
||
assert.match(html, /href="\/"[^>]*>RU/);
|
||
});
|
||
});
|
||
|
||
test("Сценарий: EN-лендинг, международная оплата выбрана — кнопка Buy ведёт в бот", async () => {
|
||
await withServer(testConfig({ intlPaymentUrl: "https://pay.example/intl" }), async (base) => {
|
||
const html = await (await fetch(`${base}/en`)).text();
|
||
assert.match(html, /href="https:\/\/t\.me\/demo_bot\?start=site_en"[^>]*>Buy/);
|
||
assert.doesNotMatch(html, /Coming soon/);
|
||
});
|
||
});
|
||
|
||
test("Сценарий: RU-лендинг не изменился, есть переключатель EN", async () => {
|
||
await withServer(testConfig(), async (base) => {
|
||
const html = await (await fetch(`${base}/`)).text();
|
||
assert.match(html, /9 900 ₸/);
|
||
assert.match(html, /href="\/en"[^>]*>EN/);
|
||
assert.doesNotMatch(html, /\$/);
|
||
});
|
||
});
|
||
|
||
const BUYER = { id: 500, first_name: "Anna", username: "anna" };
|
||
const OWNER = { id: 1, first_name: "Owner" };
|
||
|
||
async function setup(extra) {
|
||
const telegram = mockTelegram();
|
||
const store = await new Store(await tmp()).load();
|
||
const config = testConfig({ productDir, ...extra });
|
||
return { telegram, store, bot: createBot({ telegram, store, config }) };
|
||
}
|
||
const startEn = (bot) => bot.handleUpdate({ message: { text: "/start site_en", chat: { id: 500, type: "private" }, from: BUYER } });
|
||
const paidEn = (bot) => bot.handleUpdate({ callback_query: { id: "c1", data: "paid:en", from: BUYER, message: { chat: { id: 500 } } } });
|
||
const confirm = (bot) => bot.handleUpdate({ callback_query: { id: "c2", data: "confirm:1", from: OWNER } });
|
||
|
||
test("Сценарий: EN-бот без международной оплаты — Coming soon, заказ не создаётся", async () => {
|
||
const { bot, telegram, store } = await setup();
|
||
await startEn(bot);
|
||
const msg = telegram.sent(500)[0];
|
||
assert.match(msg.text, /\$19/);
|
||
assert.match(msg.text, /Coming soon/);
|
||
assert.ok(!msg.extra.reply_markup.inline_keyboard.flat().some((b) => b.callback_data === "paid:en"));
|
||
await paidEn(bot);
|
||
assert.equal(store.lastByBuyer(500), undefined);
|
||
});
|
||
|
||
test("Сценарий: покупатель EN получает английские файлы, RU — русские", async () => {
|
||
const { bot, telegram } = await setup({ intlPaymentUrl: "https://pay.example/intl" });
|
||
await startEn(bot);
|
||
assert.match(telegram.sent(500)[0].text, /https:\/\/pay\.example\/intl/);
|
||
await paidEn(bot);
|
||
assert.match(telegram.sent(1)[0].text, /\$19/);
|
||
await confirm(bot);
|
||
const docs = telegram.calls.filter((c) => c.type === "document").map((d) => d.path.split("/").slice(-2).join("/"));
|
||
assert.deepEqual(docs, ["en/finmodel-example.xlsx", "en/finmodel-empty.xlsx", "en/instruction.docx", "en/license.docx"]);
|
||
assert.match(telegram.sent(500).at(-1).text, /Questions about the model/);
|
||
});
|