dika/test/fresh.test.js
peppa-bot d69bd1ddc3
All checks were successful
peppa/lint lint: success за 0с
peppa/test test: success за 1с
peppa/build build: success за 0с
ci / checks (pull_request) Successful in 16s
deploy / deploy (pull_request) Successful in 24s
DIK-50: новая версия базы доходит до карточек, правки владельца сохраняются
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-23 15:28:51 +00:00

229 lines
14 KiB
JavaScript
Raw Permalink 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 http from "node:http";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { buildList, offerStatus, astanaTime } from "../src/lib.js";
import { readRows, toCsv } from "../src/venues.js";
import { createStore, checkPassword } from "../src/admin.js";
import { createHandler } from "../src/index.js";
const wed = new Date("2026-11-18T08:00:00Z"); // среда 13:00 Астана
const venue = (over) => ({ id: "a", name: "A", address: "ул. А, 1", lat: 51.1283, lng: 71.4305,
lunch: { price: 3500, days: [1, 2, 3, 4, 5], from: "12:00", to: "15:00" }, promo: { text: "Кофе", until: "2026-12-31" }, checked: "2026-11-18", ...over });
const one = (v) => buildList([v], 51.1283, 71.4305, { now: wed })[0];
test("Сценарий: акция закончилась — заведение остаётся", () => {
const v = one(venue({ promo: { text: "Кофе", until: "2026-11-15" } }));
assert.equal(v.id, "a"); assert.equal(v.promo, null); assert.ok(v.lunch);
});
test("Сценарий: данные давно не проверяли — заведение без цены и акции", () => {
const v = one(venue({ checked: "2026-11-01" }));
assert.equal(v.id, "a"); assert.equal(v.lunch, null); assert.equal(v.promo, null);
});
test("Сценарий: граница в 14 дней", () => {
assert.ok(one(venue({ checked: "2026-11-04" })).lunch);
assert.equal(one(venue({ checked: "2026-11-03" })).lunch, null);
});
test("Сценарий: владелец обновил дату — запись снова на сайте", () => {
assert.equal(one(venue({ checked: "2026-11-01" })).lunch, null);
assert.ok(one(venue({ checked: "2026-11-18" })).lunch);
});
test("Сценарий: статусы для владельца", () => {
const t = astanaTime(wed);
assert.deepEqual(offerStatus(venue(), t), { lunch: "active", promo: "active" });
assert.deepEqual(offerStatus(venue({ checked: "2026-11-01" }), t), { lunch: "stale", promo: "stale" });
assert.deepEqual(offerStatus(venue({ lunch: null, promo: { text: "x", until: "2026-11-01" } }), t), { lunch: "none", promo: "expired" });
assert.deepEqual(offerStatus(venue({ promo: null }), t), { lunch: "active", promo: "none" });
});
const tmpBase = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dika-"));
fs.cpSync("data", dir, { recursive: true });
return dir;
};
const TODAY = astanaTime().date;
test("Запись таблицы не меняет остальное содержимое базы", () => {
const src = fs.readFileSync("data/venues.csv", "utf8");
assert.equal(toCsv(readRows("data").venues), src);
});
test("Сценарий: владелец меняет цену, акцию и дату", () => {
const dir = tmpBase();
const store = createStore(dir);
const id = readRows(dir).venues[0].id;
const r = store.update(id, { price: "3900", promo: "Кофе в подарок", promoUntil: TODAY, checked: TODAY });
assert.deepEqual(r, { ok: true });
const row = store.list().find((x) => x.id === id);
assert.equal(row.lunch.price, 3900); assert.equal(row.promo.text, "Кофе в подарок"); assert.equal(row.checked, TODAY);
assert.equal(store.db.venues.find((v) => v.id === id).lunch.price, 3900);
assert.equal(readRows(dir).venues.length, store.list().length); // записи не удаляются
assert.equal(store.update(id, { promo: "нет", checked: TODAY }).ok, true);
assert.equal(store.list().find((x) => x.id === id).promo, null);
});
test("Сценарий: неверное значение отклоняется, данные не меняются", () => {
const dir = tmpBase();
const store = createStore(dir);
const before = fs.readFileSync(`${dir}/venues.csv`, "utf8");
const id = readRows(dir).venues[0].id;
assert.equal(store.update(id, { price: "abc", checked: TODAY }).error, "bad_price");
assert.equal(store.update(id, { checked: "2099-01-01" }).error, "future_date");
assert.equal(store.update(id, { checked: "" }).error, "bad_date");
assert.equal(store.update("нет-такого", { checked: TODAY }).error, "not_found");
assert.equal(fs.readFileSync(`${dir}/venues.csv`, "utf8"), before);
});
test("Каталог данных без базы получает стартовую", () => {
const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "dika-")), "live");
const store = createStore(dir, "data");
assert.ok(store.db.venues.length >= 20 && fs.existsSync(`${dir}/venues.csv`));
});
test("Проверка пароля", () => {
const h = (p) => "Basic " + Buffer.from("owner:" + p).toString("base64");
assert.equal(checkPassword(h("s3cret"), "s3cret"), true);
assert.equal(checkPassword(h("wrong"), "s3cret"), false);
assert.equal(checkPassword(undefined, "s3cret"), false);
assert.equal(checkPassword(h(""), ""), false);
});
async function withServer(opts, fn) {
const s = http.createServer(createHandler(opts)).listen(0);
try { await fn(`http://127.0.0.1:${s.address().port}`); } finally { s.close(); }
}
test("Сценарий: пароль не задан / неверный / верный; изменение видно на сайте", async () => {
await withServer({ dataDir: tmpBase(), password: "" }, async (b) => {
const r = await fetch(b + "/admin"); assert.equal(r.status, 503);
});
await withServer({ dataDir: tmpBase(), password: "s3cret" }, async (b) => {
assert.equal((await fetch(b + "/admin")).status, 401);
assert.equal((await fetch(b + "/admin/api/venues")).status, 401);
const auth = { authorization: "Basic " + Buffer.from("o:s3cret").toString("base64") };
assert.equal((await fetch(b + "/admin", { headers: auth })).status, 200);
const rows = await (await fetch(b + "/admin/api/venues", { headers: auth })).json();
const v = rows[0];
const post = (body) => fetch(`${b}/admin/api/venues/${v.id}`, { method: "POST", headers: auth, body: JSON.stringify(body) });
assert.equal((await post({ price: "abc", checked: TODAY })).status, 400);
assert.equal((await post({ price: "4321", checked: TODAY })).status, 200);
const site = await (await fetch(`${b}/api/venues?lat=51.1283&lng=71.4305`)).json();
assert.equal(site.length > 0, true);
assert.equal((await fetch(b + "/healthz")).status, 200);
});
});
test("Сценарий: страница правки показывает дату проверки и подсказку; тексты есть на всех языках", async () => {
const html = fs.readFileSync(new URL("../admin/index.html", import.meta.url), "utf8");
for (const l of ["ru", "kk", "en"]) {
const t = JSON.parse(fs.readFileSync(new URL(`../public/i18n/${l}.json`, import.meta.url), "utf8"));
for (const k of ["admCheckedOn", "admNeverChecked", "admHiddenHint", "admAutoDate"]) {
assert.ok(t[k], `${l}:${k}`); assert.ok(html.includes(k), k);
}
}
});
test("Сценарий: цена не подтверждена — давние данные и нет данных", () => {
assert.equal(one(venue({ checked: "2026-11-01" })).unconfirmed, true);
assert.equal(one(venue({ lunch: null, promo: null })).unconfirmed, true);
assert.equal(one(venue()).unconfirmed, false);
assert.equal(one(venue({ checked: "2026-11-18", lunch: { price: 3500, days: [6], from: "12:00", to: "15:00" } })).unconfirmed, false);
});
test("владелец заменяет описание и фото: источник становится «владелец», дата проверки цен не меняется (DIK-42)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dika-"));
const store = createStore(dir, "data");
const id = store.list()[0].id;
const before = store.list().find((x) => x.id === id).checked;
assert.equal(store.update(id, { description: "Тихое место с домашней кухней", photo: "https://e.kz/a.jpg" }).ok, true);
const row = store.list().find((x) => x.id === id);
assert.equal(row.description, "Тихое место с домашней кухней");
assert.equal(row.descriptionSource, "владелец");
assert.equal(row.photoSource, "владелец");
assert.equal(row.checked, before);
const shown = store.all().find((x) => x.id === id);
assert.equal(shown.photo, "https://e.kz/a.jpg"); assert.equal(shown.photoSource, "владелец");
assert.equal(store.update(id, { description: "", photo: "" }).ok, true);
const empty = store.list().find((x) => x.id === id);
assert.equal(empty.description, ""); assert.equal(empty.descriptionSource, ""); assert.equal(empty.photoSource, "");
});
test("описание и фото владельца проверяются (DIK-42)", () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dika-"));
const store = createStore(dir, "data");
const id = store.list()[0].id;
assert.equal(store.update(id, { description: "я".repeat(301) }).error, "bad_description");
assert.equal(store.update(id, { photo: "javascript:alert(1)" }).error, "bad_photo");
});
test("Сценарий: ланч вечером или в выходной — «в другое время» с часами (DIK-26)", () => {
const v = buildList([venue({ checked: "2026-11-20" })], 51.1283, 71.4305, { now: new Date("2026-11-21T08:00:00Z") })[0]; // суббота 13:00
assert.equal(v.lunch, null);
assert.equal(v.price, "later");
assert.deepEqual(v.lunchHours, { from: "12:00", to: "15:00" });
assert.equal(v.unconfirmed, false);
});
test("Сценарий: нет данных о цене — «Цена не подтверждена», акция показана (DIK-26)", () => {
const v = one(venue({ lunch: null, promo: { text: "Кофе в подарок", until: null } }));
assert.equal(v.price, "unconfirmed"); assert.equal(v.unconfirmed, true);
assert.equal(v.promoState, "active"); assert.equal(v.promo.text, "Кофе в подарок");
assert.equal(v.lunchHours, null);
});
test("Сценарий: давние данные — цена не подтверждена, акции сейчас нет (DIK-26)", () => {
const v = one(venue({ checked: "2026-11-01" }));
assert.equal(v.price, "unconfirmed"); assert.equal(v.promoState, "none"); assert.equal(v.promo, null);
});
test("Сценарий: акция закончилась — не показана как действующая (DIK-26)", () => {
const v = one(venue({ promo: { text: "Кофе", until: "2026-11-17" } }));
assert.equal(v.promo, null); assert.equal(v.promoState, "ended");
assert.equal(one(venue({ promo: { text: "Кофе", until: "2026-11-01" }, checked: "2026-11-01" })).promoState, "ended");
});
test("Сценарий: акции нет — «Акции сейчас нет», без пустых значений (DIK-26)", () => {
const v = one(venue({ promo: null }));
assert.equal(v.promoState, "none"); assert.equal(v.price, "active");
});
// DIK-50: новая версия базы доходит до карточек, правки владельца сохраняются
function liveFrom(edit) {
const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "dika-")), "live");
createStore(dir, "data");
const { venues } = readRows(dir);
fs.writeFileSync(`${dir}/venues.csv`, toCsv(edit(venues)));
return dir;
}
const marm = (rows) => rows.find((r) => r.id === "esil-01");
test("Сценарий: В новой версии появились описания", () => {
const dir = liveFrom((rows) => rows.slice(1).map((r) => ({ ...r, "описание": "", "источник описания": "", "фото": "", "источник фото": "" }))
.concat({ ...marm(rows), "описание": "", "источник описания": "" }));
const store = createStore(dir, "data");
const shown = store.all();
assert.equal(shown.length, readRows("data").venues.length);
assert.match(shown.find((x) => x.id === "esil-01").description, /^Семейный ресторан в ТЦ Abu Dhabi Plaza/);
assert.equal(shown.filter((x) => x.description).length, readRows("data").venues.filter((r) => r["описание"]).length);
assert.deepEqual(shown.map((x) => x.id), readRows("data").venues.map((r) => r.id)); // порядок и места — из новой версии
});
test("Сценарий: Правка владельца не теряется", () => {
const dir = liveFrom((rows) => rows.map((r) => (r.id === "esil-01"
? { ...r, "цена ланча, ₸": "4200", "дата проверки": "20.11.2026", "описание": "Наше описание", "источник описания": "владелец" } : r)));
const row = createStore(dir, "data").list().find((x) => x.id === "esil-01");
assert.equal(row.lunch.price, 4200);
assert.equal(row.checked, "2026-11-20");
assert.equal(row.description, "Наше описание");
});
test("Сценарий: Агент проверил цену позже владельца", () => {
const dir = liveFrom((rows) => rows.map((r) => (r.id === "esil-01" ? { ...r, "цена ланча, ₸": "4200", "дата проверки": "10.11.2026" } : r)));
const row = createStore(dir, "data").list().find((x) => x.id === "esil-01");
assert.equal(row.lunch.price, Number(marm(readRows("data").venues)["цена ланча, ₸"]));
});
test("Старая живая база с ошибками не роняет сайт — берётся новая версия", () => {
const dir = liveFrom((rows) => rows.map((r) => (r.id === "esil-01"
? { ...r, "дата проверки": "20.11.2026", "акция до": "не дата" } : r)));
const store = createStore(dir, "data");
assert.equal(store.db.venues.length, readRows("data").venues.length);
});