dika/src/admin.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

128 lines
7.5 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.

// Правка данных владельцем базы: хранилище поверх data/venues.csv и проверка пароля.
import fs from "node:fs";
import crypto from "node:crypto";
import path from "node:path";
import { readRows, loadBase, validateVenues, toVenue, toCsv, formatDate, parseDate, OWNER_SOURCE } from "./venues.js";
import { astanaTime, offerStatus } from "./lib.js";
const OFFER_FIELDS = ["цена ланча, ₸", "акция", "акция до", "дата проверки"];
const OWNER_FIELDS = [["описание", "источник описания"], ["фото", "источник фото"]];
// Стартовая база из новой версии + живая база с правками владельца (DIK-50).
// Места и данные агента — из стартовой; цена/акция — из живой, если владелец проверил их позже;
// описание и фото — из живой, если их заменил владелец.
export function mergeBase(seed, live) {
const byId = new Map(live.map((r) => [r.id, r]));
return seed.map((s) => {
const l = byId.get(s.id);
if (!l) return s;
const next = { ...s };
const ls = parseDate(l["дата проверки"] || ""), ss = parseDate(s["дата проверки"] || "");
const sameLunch = (l["бизнес-ланч"] === "есть") === (s["бизнес-ланч"] === "есть");
if (ls && ss && ls > ss && sameLunch) for (const f of OFFER_FIELDS) next[f] = l[f] ?? "";
for (const [f, src] of OWNER_FIELDS) if (l[src] === OWNER_SOURCE) { next[f] = l[f]; next[src] = l[src]; }
return next;
});
}
// Каталог данных: если в нём ещё нет базы, копируем стартовую из образа; если есть — сливаем с новой версией.
export function createStore(dataDir, seedDir = dataDir) {
fs.mkdirSync(dataDir, { recursive: true });
const file = `${dataDir}/venues.csv`;
if (!fs.existsSync(file)) fs.copyFileSync(`${seedDir}/venues.csv`, file);
else if (path.resolve(dataDir) !== path.resolve(seedDir)) {
const seed = readRows(seedDir).venues;
let merged = mergeBase(seed, readRows(dataDir).venues);
if (validateVenues(merged).length) merged = seed; // старый файл не должен ронять сайт
const csv = toCsv(merged);
if (csv !== fs.readFileSync(file, "utf8")) { fs.writeFileSync(file + ".tmp", csv); fs.renameSync(file + ".tmp", file); }
}
let db = loadBase(dataDir);
return {
get db() { return db; },
// Вся база как есть, ничего не скрывая: страница «Вся база»
all() {
return readRows(dataDir).venues.map((r) => {
const v = toVenue(r);
return { id: v.id, name: v.name, address: v.address, lat: v.lat, lng: v.lng,
lunch: v.lunch ? { price: v.lunch.price, from: v.lunch.from, to: v.lunch.to } : null,
promo: v.promo ? { text: v.promo.text, until: v.promo.until } : null, checked: v.checked,
description: v.description, descriptionSource: v.descriptionSource, photo: v.photo, photoSource: v.photoSource,
source: r["источник"], link: /^https?:\/\//.test(r["ссылка"]) ? r["ссылка"] : "", web: r["сайт и соцсети"] || "" };
});
},
// Строки для страницы правки: поля + статус «действует / скрыта»
list(now = new Date()) {
const t = astanaTime(now);
return readRows(dataDir).venues.map((r) => {
const v = toVenue(r);
return {
id: r.id, name: r["название"], address: r["адрес"],
lunch: v.lunch ? { price: v.lunch.price } : null,
promo: v.promo ? { text: v.promo.text, until: v.promo.until } : null,
checked: v.checked, status: offerStatus(v, t),
description: v.description || "", descriptionSource: v.descriptionSource || "", photo: v.photo || "", photoSource: v.photoSource || "",
};
});
},
// patch: { price?, promo?, promoUntil?, checked } → { ok } или { error: код }
update(id, patch, now = new Date()) {
const today = astanaTime(now).date;
const { venues } = readRows(dataDir);
const r = venues.find((x) => x.id === id);
if (!r) return { error: "not_found" };
const next = { ...r };
if (patch.price !== undefined && patch.price !== null && patch.price !== "") {
if (r["бизнес-ланч"] !== "есть") return { error: "no_lunch" };
if (!/^\d+$/.test(String(patch.price)) || Number(patch.price) <= 0 || Number(patch.price) > 1e6) return { error: "bad_price" };
next["цена ланча, ₸"] = String(Number(patch.price));
}
if (patch.promo !== undefined) {
const text = String(patch.promo).trim().replace(/[\r\n]+/g, " ");
if (!text || text.toLowerCase() === "нет") { next["акция"] = "нет"; next["акция до"] = ""; }
else {
next["акция"] = text;
const until = patch.promoUntil ? String(patch.promoUntil) : "";
if (until && !parseDate(formatDate(until))) return { error: "bad_date" };
next["акция до"] = formatDate(until);
}
}
// Описание и фото владельца: заменяют найденные агентом, источник становится «владелец»; пусто — вернуть заглушку.
if (patch.description !== undefined) {
const text = String(patch.description).trim().replace(/\s+/g, " ");
if (text.length > 300) return { error: "bad_description" };
if (text !== r["описание"]) { next["описание"] = text; next["источник описания"] = text ? OWNER_SOURCE : ""; }
}
if (patch.photo !== undefined) {
const url = String(patch.photo).trim();
if (url && !/^https?:\/\/\S+$/.test(url)) return { error: "bad_photo" };
if (url !== r["фото"]) { next["фото"] = url; next["источник фото"] = url ? OWNER_SOURCE : ""; }
}
// Правка только описания и фото дату проверки цен не меняет и её не требует.
const textOnly = patch.checked === undefined && (patch.description !== undefined || patch.photo !== undefined);
if (!textOnly) {
if (!patch.checked || !parseDate(formatDate(String(patch.checked)))) return { error: "bad_date" };
if (String(patch.checked) > today) return { error: "future_date" };
next["дата проверки"] = formatDate(String(patch.checked));
}
const all = venues.map((x) => (x === r ? next : x));
if (validateVenues(all).length) return { error: "invalid" };
const tmp = `${dataDir}/venues.csv.tmp`;
fs.writeFileSync(tmp, toCsv(all));
fs.renameSync(tmp, `${dataDir}/venues.csv`);
db = loadBase(dataDir);
return { ok: true };
},
};
}
// HTTP Basic: имя любое, пароль — из окружения. Сравнение без утечки по времени.
export function checkPassword(header, password) {
if (!password || !header?.startsWith("Basic ")) return false;
const given = Buffer.from(header.slice(6), "base64").toString("utf8");
const pass = given.slice(given.indexOf(":") + 1);
const a = crypto.createHash("sha256").update(pass).digest();
const b = crypto.createHash("sha256").update(password).digest();
return given.includes(":") && crypto.timingSafeEqual(a, b);
}