dika/public/base.js
Peppa 625df45335
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 13s
deploy / deploy (pull_request) Successful in 39s
DIK-40: переключатель языка на странице «Все заведения», текст меняется сразу
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 16:59:01 +05:00

104 lines
6.6 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.

const LANGS = ["ru", "kk", "en"];
const saved = () => { try { return localStorage.getItem("lang"); } catch { return null; } };
const fmt = (s, o) => s.replace(/\{(\w+)\}/g, (_, k) => o[k] ?? ""); // без undefined на экране
const date = (iso) => (iso ? iso.split("-").reverse().join(".") : "");
const today = new Date(Date.now() + 5 * 3600000).toISOString().slice(0, 10); // Астана UTC+5
let t = {}, list = null, failed = false;
const $ = (id) => document.getElementById(id);
const COLS = ["colName", "colAddress", "colCoords", "colLunch", "colPromo", "colChecked", "colDescription", "colPhoto", "colSource"];
// Ячейка с текстом и «Источник: …»; адрес в источнике («2ГИС — https://…») становится ссылкой
const safe = (u) => /^https?:\/\//.test(u);
function cell(text, source, photoUrl) {
const td = document.createElement("td");
if (photoUrl && safe(photoUrl)) { const a = document.createElement("a"); a.href = photoUrl; a.textContent = text; a.target = "_blank"; a.rel = "noopener noreferrer"; td.append(a); }
else td.append(text);
if (source) {
const d = document.createElement("div"); d.className = "srcnote";
const m = /^(.*?)\s*(https?:\/\/\S+)$/.exec(source);
const name = (m ? m[1] : source).replace(/[\s—-]+$/, "");
d.append(t.srcLabel + " ");
if (m) { const a = document.createElement("a"); a.href = m[2]; a.textContent = name === "владелец" ? t.srcOwner : name || m[2]; a.target = "_blank"; a.rel = "noopener noreferrer"; d.append(a); }
else d.append(name === "владелец" ? t.srcOwner : name);
td.append(d);
}
return td;
}
// Источник значения: «2ГИС; акция — digitalbusiness.kz, 04.11.2026» → основной источник и свои источники у отдельных полей
function sources(v) {
const [main, ...rest] = (v.source || "").split(";").map((x) => x.trim());
const own = {};
for (const x of rest) {
const m = /^(.*?)\s+—\s+(.*?)(?:,\s*(\d{2}\.\d{2}\.\d{4}))?$/.exec(x);
if (m) own[/акци/.test(m[1]) ? "promo" : "lunch"] = { name: m[2], date: m[3] || date(v.checked), own: true };
}
const base = { name: main, date: date(v.checked), link: v.link };
return { lunch: own.lunch || base, promo: own.promo || base };
}
// Ячейка значения с пометкой «Источник: …, проверено …»; если сайт и соцсети ничего не дали — пометка про прежние данные
function valueCell(text, src, web) {
const td = document.createElement("td");
td.append(text);
const d = document.createElement("div"); d.className = "srcnote";
d.append(t.srcLabel + " ");
if (src.link && /^https?:\/\//.test(src.link)) { const a = document.createElement("a"); a.href = src.link; a.textContent = src.name; a.target = "_blank"; a.rel = "noopener noreferrer"; d.append(a); }
else d.append(src.name || t.baseNoSource);
d.append(", " + (src.date ? fmt(t.checkedOn, { date: src.date }).toLowerCase() : t.baseNotChecked)); // без пустых значений (DIK-26)
td.append(d);
if (web === "нет данных" && !src.own) { const n = document.createElement("div"); n.className = "srcnote"; n.textContent = fmt(t.webNotFound, { source: src.name, date: src.date }); td.append(n); }
return td;
}
function render() {
document.title = t.baseTitle;
document.querySelectorAll("[data-i]").forEach((e) => (e.textContent = t[e.dataset.i]));
$("head").replaceChildren(...COLS.map((k) => { const th = document.createElement("th"); th.textContent = t[k]; return th; }));
const body = $("rows"), e = $("err");
body.replaceChildren(); e.hidden = true; $("count").textContent = "";
if (failed) { e.textContent = t.baseError; e.hidden = false; return; }
if (!list) return;
$("count").textContent = fmt(t.baseCount, { n: list.length });
if (!list.length) { e.textContent = t.listPreparing; e.hidden = false; }
for (const v of list) {
const ptext = v.promo && (t.promoTexts?.[v.promo.text] || v.promo.text);
// акция с прошедшим сроком не выглядит действующей; пустых ячеек нет (DIK-26)
// устаревшие данные (старше 14 дней) не выдаём за действующие — как на главной (DIK-65)
const stale = v.checked && Math.floor((Date.parse(today) - Date.parse(v.checked)) / 86400000) > 14;
const promo = !v.promo || (stale && !(v.promo.until && v.promo.until < today)) ? t.promoNone : v.promo.until && v.promo.until < today ? fmt(t.basePromoEnded, { text: ptext, until: date(v.promo.until) })
: ptext + (v.promo.until ? ` (${date(v.promo.until)})` : "");
const lunch = v.lunch && !stale ? fmt(t.baseLunch, v.lunch) : t.notConfirmed;
const tr = document.createElement("tr");
const src = sources(v);
for (const s of [v.name, v.address, `${v.lat}, ${v.lng}`]) {
const td = document.createElement("td"); td.textContent = s; tr.append(td);
}
tr.append(valueCell(lunch, src.lunch, v.web), valueCell(promo, src.promo, v.web));
{ const td = document.createElement("td"); td.textContent = v.checked ? date(v.checked) : t.baseNotChecked; tr.append(td); }
tr.append(cell(v.description || t.noDescriptionBase, v.description && v.descriptionSource), cell(v.photo ? t.photoOf : t.noPhotoBase, v.photo && v.photoSource, v.photo));
const srcTd = document.createElement("td");
if (/^https?:\/\//.test(v.link || "")) { const a = document.createElement("a"); a.href = v.link; a.target = "_blank"; a.rel = "noopener noreferrer"; a.textContent = v.source || t.baseNoSource; srcTd.append(a); }
else srcTd.textContent = v.source || t.baseNoSource;
const web = document.createElement("div"); web.className = "web"; web.textContent = t[v.web === "обновлено" ? "webUpdated" : v.web === "нет данных" ? "webNone" : "webNot"];
srcTd.append(web);
tr.append(srcTd);
body.append(tr);
}
}
async function setLang(l) {
try { localStorage.setItem("lang", l); } catch {}
t = await (await fetch(`i18n/${l}.json`)).json();
document.documentElement.lang = l;
document.querySelectorAll("[data-l]").forEach((b) => {
b.classList.toggle("on", b.dataset.l === l); b.setAttribute("aria-pressed", String(b.dataset.l === l));
});
render();
}
document.querySelectorAll("[data-l]").forEach((b) => (b.onclick = () => setLang(b.dataset.l)));
await setLang(LANGS.includes(saved()) ? saved() : "ru");
try {
const r = await fetch("/api/base");
if (!r.ok) throw new Error();
list = await r.json();
} catch { failed = true; }
render();